text stringlengths 54 60.6k |
|---|
<commit_before>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <list>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/program_options.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// Trademgen
#include <trademgen/TRADEMGEN_Service.hpp>
#include <trademgen/config/trademgen-paths.hpp>
#include <trademgen/basic/DemandCharacteristics.hpp>
#include <trademgen/basic/DemandCharacteristicTypes.hpp>
#include <trademgen/basic/DemandDistribution.hpp>
#include <trademgen/basic/RandomGeneration.hpp>
#include <trademgen/basic/RandomGenerationContext.hpp>
#include <trademgen/basic/DictionaryManager.hpp>
#include <trademgen/bom/BomManager.hpp>
#include <trademgen/config/trademgen-paths.hpp>
// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_TRADEMGEN_DEFAULT_LOG_FILENAME ("trademgen.log");
/** Default name and location for the (CSV) input file. */
const std::string K_TRADEMGEN_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/demand01.csv");
/** Default name and location for the (CSV) output file. */
const std::string K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME ("request.csv");
/** Default query string. */
const std::string K_TRADEMGEN_DEFAULT_QUERY_STRING ("my good old query");
// //////////////////////////////////////////////////////////////////////
void tokeniseStringIntoWordList (const std::string& iPhrase,
WordList_T& ioWordList) {
// Empty the word list
ioWordList.clear();
// Boost Tokeniser
typedef boost::tokenizer<boost::char_separator<char> > Tokeniser_T;
// Define the separators
const boost::char_separator<char> lSepatorList(" .,;:|+-*/_=!@#$%`~^&(){}[]?'<>\"");
// Initialise the phrase to be tokenised
Tokeniser_T lTokens (iPhrase, lSepatorList);
for (Tokeniser_T::const_iterator tok_iter = lTokens.begin();
tok_iter != lTokens.end(); ++tok_iter) {
const std::string& lTerm = *tok_iter;
ioWordList.push_back (lTerm);
}
}
// //////////////////////////////////////////////////////////////////////
std::string createStringFromWordList (const WordList_T& iWordList) {
std::ostringstream oStr;
unsigned short idx = iWordList.size();
for (WordList_T::const_iterator itWord = iWordList.begin();
itWord != iWordList.end(); ++itWord, --idx) {
const std::string& lWord = *itWord;
oStr << lWord;
if (idx > 1) {
oStr << " ";
}
}
return oStr.str();
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_TRADEMGEN_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
std::string& ioQueryString,
stdair::Filename_T& ioInputFilename,
stdair::Filename_T& ioOutputFilename,
std::string& ioLogFilename) {
// Initialise the travel query string, if that one is empty
if (ioQueryString.empty() == true) {
ioQueryString = K_TRADEMGEN_DEFAULT_QUERY_STRING;
}
// Transform the query string into a list of words (STL strings)
WordList_T lWordList;
tokeniseStringIntoWordList (ioQueryString, lWordList);
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("input,i",
boost::program_options::value< std::string >(&ioInputFilename)->default_value(K_TRADEMGEN_DEFAULT_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("output,o",
boost::program_options::value< std::string >(&ioOutputFilename)->default_value(K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME),
"(CVS) output file for the generated requests")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_TRADEMGEN_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
("query,q",
boost::program_options::value< WordList_T >(&lWordList)->multitoken(),
"Query word list")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("trademgen.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("input")) {
ioInputFilename = vm["input"].as< std::string >();
std::cout << "Input filename is: " << ioInputFilename << std::endl;
}
if (vm.count ("output")) {
ioOutputFilename = vm["output"].as< std::string >();
std::cout << "Output filename is: " << ioOutputFilename << std::endl;
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << ioLogFilename << std::endl;
}
ioQueryString = createStringFromWordList (lWordList);
std::cout << "The query string is: " << ioQueryString << std::endl;
return 0;
}
// /////////////// M A I N /////////////////
int main (int argc, char* argv[]) {
// Query
std::string lQuery;
// Input file name
stdair::Filename_T lInputFilename;
// Output file name
stdair::Filename_T lOutputFilename;
// Output log File
std::string lLogFilename;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lQuery, lInputFilename,
lOutputFilename, lLogFilename);
if (lOptionParserStatus == K_TRADEMGEN_EARLY_RETURN_STATUS) {
return 0;
}
// Number of generations.
const int lNbOfRuns = 10;
// Open and clean the .csv output file
std::ofstream output;
output.open (lOutputFilename.c_str());
output.clear();
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the TraDemGen service object
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);
// DEBUG
//return 0;
for (int i = 1; i <= lNbOfRuns; ++i) {
// /////////////////////////////////////////////////////
output << "Generation number " << i << std::endl;
// Event queue
stdair::EventQueue lEventQueue = stdair::EventQueue ();
// Browse the list of DemandStreams and Generate the first event for each
// DemandStream.
trademgenService.generateFirstRequests (lEventQueue);
// Pop requests, get type, and generate next request of same type
while (lEventQueue.isQueueDone() == false) {
stdair::EventStruct& lEventStruct = lEventQueue.popEvent ();
const stdair::BookingRequestStruct& lPoppedRequest =
lEventStruct.getBookingRequest ();
// Output the request.
TRADEMGEN::BomManager::csvDisplay (output, lPoppedRequest);
// Retrieve the corresponding demand stream
const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
lEventStruct.getDemandStreamKey ();
// generate next request
bool stillHavingRequestsToBeGenerated =
trademgenService.stillHavingRequestsToBeGenerated(lDemandStreamKey);
if (stillHavingRequestsToBeGenerated) {
stdair::BookingRequestPtr_T lNextRequest =
trademgenService.generateNextRequest (lDemandStreamKey);
assert (lNextRequest != NULL);
stdair::Duration_T lDuration = lNextRequest->getRequestDateTime() -
lPoppedRequest.getRequestDateTime();
if (lDuration.total_milliseconds() < 0) {
STDAIR_LOG_DEBUG (lDemandStreamKey);
STDAIR_LOG_DEBUG (lPoppedRequest.getRequestDateTime());
STDAIR_LOG_DEBUG (lNextRequest->getRequestDateTime());
assert (false);
}
stdair::EventStruct lNextEventStruct ("Request", lDemandStreamKey,
lNextRequest);
lEventQueue.addEvent (lNextEventStruct);
}
lEventQueue.eraseLastUsedEvent ();
}
trademgenService.reset();
}
// Close the Log outputFile
logOutputFile.close();
return 0;
}
<commit_msg>[TraDemGen][Dev] Improved the logging output of the TraDemGen batch.<commit_after>// STL
#include <cassert>
#include <sstream>
#include <fstream>
#include <vector>
#include <list>
#include <string>
// //// Boost (Extended STL) ////
// Boost Date-Time
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
// Boost Tokeniser
#include <boost/tokenizer.hpp>
// Boost Program Options
#include <boost/program_options.hpp>
// Boost Accumulators
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// Trademgen
#include <trademgen/TRADEMGEN_Service.hpp>
#include <trademgen/config/trademgen-paths.hpp>
#include <trademgen/basic/DemandCharacteristics.hpp>
#include <trademgen/basic/DemandCharacteristicTypes.hpp>
#include <trademgen/basic/DemandDistribution.hpp>
#include <trademgen/basic/RandomGeneration.hpp>
#include <trademgen/basic/RandomGenerationContext.hpp>
#include <trademgen/basic/DictionaryManager.hpp>
#include <trademgen/bom/BomManager.hpp>
#include <trademgen/config/trademgen-paths.hpp>
// Aliases for namespaces
namespace ba = boost::accumulators;
// //////// Specific type definitions ///////
typedef unsigned int NbOfRuns_T;
/** Type definition to gather statistics. */
typedef ba::accumulator_set<double,
ba::stats<ba::tag::min, ba::tag::max,
ba::tag::mean (ba::immediate),
ba::tag::sum,
ba::tag::variance> > stat_acc_type;
// //////// Constants //////
/** Default name and location for the log file. */
const stdair::Filename_T K_TRADEMGEN_DEFAULT_LOG_FILENAME ("trademgen.log");
/** Default name and location for the (CSV) input file. */
const stdair::Filename_T K_TRADEMGEN_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR
"/demand01.csv");
/** Default name and location for the (CSV) output file. */
const stdair::Filename_T K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME ("request.csv");
/** Default number of random draws to be generated (best if over 100). */
const NbOfRuns_T K_TRADEMGEN_DEFAULT_RANDOM_DRAWS = 100;
/** Display the statistics held by the dedicated accumulator. */
void stat_display (std::ostream& oStream, const stat_acc_type& iStatAcc) {
// Store current formatting flags of the output stream
std::ios::fmtflags oldFlags = oStream.flags();
//
oStream.setf (std::ios::fixed);
//
oStream << "Statistics for the demand generation runs: " << std::endl;
oStream << " minimum = " << ba::min (iStatAcc) << std::endl;
oStream << " mean = " << ba::mean (iStatAcc) << std::endl;
oStream << " maximum = " << ba::max (iStatAcc) << std::endl;
oStream << " count = " << ba::count (iStatAcc) << std::endl;
oStream << " variance = " << ba::variance (iStatAcc) << std::endl;
// Reset formatting flags of output stream
oStream.flags (oldFlags);
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_TRADEMGEN_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[], NbOfRuns_T& ioRandomRuns,
stdair::Filename_T& ioInputFilename,
stdair::Filename_T& ioOutputFilename,
stdair::Filename_T& ioLogFilename) {
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("draws,d",
boost::program_options::value<NbOfRuns_T>(&ioRandomRuns)->default_value(K_TRADEMGEN_DEFAULT_RANDOM_DRAWS),
"Number of runs for the demand generations")
("input,i",
boost::program_options::value< std::string >(&ioInputFilename)->default_value(K_TRADEMGEN_DEFAULT_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("output,o",
boost::program_options::value< std::string >(&ioOutputFilename)->default_value(K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME),
"(CVS) output file for the generated requests")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_TRADEMGEN_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("trademgen.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_TRADEMGEN_EARLY_RETURN_STATUS;
}
if (vm.count ("input")) {
ioInputFilename = vm["input"].as< std::string >();
}
if (vm.count ("output")) {
ioOutputFilename = vm["output"].as< std::string >();
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
}
//
std::cout << "The number of runs is: " << ioRandomRuns << std::endl;
std::cout << "Input filename is: " << ioInputFilename << std::endl;
std::cout << "Output filename is: " << ioOutputFilename << std::endl;
std::cout << "Log filename is: " << ioLogFilename << std::endl;
return 0;
}
// /////////////// M A I N /////////////////
int main (int argc, char* argv[]) {
// Number of random draws to be generated (best if greater than 100)
NbOfRuns_T lNbOfRuns;
// Initialise the statistics collector/accumulator
stat_acc_type lStatAccumulator;
// Input file name
stdair::Filename_T lInputFilename;
// Output file name
stdair::Filename_T lOutputFilename;
// Output log File
stdair::Filename_T lLogFilename;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lNbOfRuns, lInputFilename,
lOutputFilename, lLogFilename);
if (lOptionParserStatus == K_TRADEMGEN_EARLY_RETURN_STATUS) {
return 0;
}
// Open and clean the .csv output file
std::ofstream output;
output.open (lOutputFilename.c_str());
output.clear();
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the TraDemGen service object
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);
// DEBUG
//return 0;
for (NbOfRuns_T runIdx = 1; runIdx <= lNbOfRuns; ++runIdx) {
// /////////////////////////////////////////////////////
output << "Run number: " << runIdx << std::endl;
// Event queue
stdair::EventQueue lEventQueue = stdair::EventQueue ();
/**
Initialisation step.
<br>Generate the first event for each demand stream.
*/
trademgenService.generateFirstRequests (lEventQueue);
/**
Main loop.
<ul>
<li>Pop a request and get its associated type/demand stream.</li>
<li>Generate the next request for the same type/demand stream.</li>
</ul>
*/
stdair::Count_T eventIdx = 1;
while (lEventQueue.isQueueDone() == false) {
// Get the next event from the event queue
stdair::EventStruct& lEventStruct = lEventQueue.popEvent();
// Extract the corresponding demand/booking request
const stdair::BookingRequestStruct& lPoppedRequest =
lEventStruct.getBookingRequest();
// DEBUG
STDAIR_LOG_DEBUG ("[" << runIdx << "][" << eventIdx
<< "] Poped booking request: '"
<< lPoppedRequest.describe() << "'.");
// Dump the request into the dedicated CSV file
TRADEMGEN::BomManager::csvDisplay (output, lPoppedRequest);
// Retrieve the corresponding demand stream
const stdair::DemandStreamKeyStr_T& lDemandStreamKey =
lEventStruct.getDemandStreamKey ();
// Assess whether more events should be generated for that demand stream
const bool stillHavingRequestsToBeGenerated =
trademgenService.stillHavingRequestsToBeGenerated (lDemandStreamKey);
// Retrieve, from the demand stream, the total number of events
// to be generated
const stdair::NbOfRequests_T& lNbOfRequests = trademgenService.
getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey);
// DEBUG
STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
<< "Still generate events for that demand stream? "
<< stillHavingRequestsToBeGenerated);
// If there are still events to be generated for that demand stream,
// generate and add them to the event queue
if (stillHavingRequestsToBeGenerated) {
stdair::BookingRequestPtr_T lNextRequest_ptr =
trademgenService.generateNextRequest (lDemandStreamKey);
assert (lNextRequest_ptr != NULL);
// Sanity check
const stdair::Duration_T lDuration =
lNextRequest_ptr->getRequestDateTime()
- lPoppedRequest.getRequestDateTime();
if (lDuration.total_milliseconds() < 0) {
STDAIR_LOG_ERROR ("[" << lDemandStreamKey << "] The date-time of the "
<< "generated event ("
<< lNextRequest_ptr->getRequestDateTime()
<< ") is lower than the date-time "
<< "of the current event ("
<< lPoppedRequest.getRequestDateTime() << ")");
assert (false);
}
//
const stdair::EventType_T lEventTypeStr ("Request");
stdair::EventStruct lNextEventStruct (lEventTypeStr, lDemandStreamKey,
lNextRequest_ptr);
/**
Note that when adding an event in the event queue, the
former can be altered. It happends when an event already
exists in the event queue with exactly the same date-time
stamp. In that case, the date-time stamp is altered for the
newly added event, so that the unicity on the date-time
stamp can be guaranteed.
*/
lEventQueue.addEvent (lNextEventStruct);
// DEBUG
STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
<< lNextRequest_ptr->describe()
<< "'. Is queue done? " << lEventQueue.isQueueDone());
}
/**
Remove the last used event, so that, at any given moment, the
queue keeps only the active events.
*/
lEventQueue.eraseLastUsedEvent ();
// Iterate
++eventIdx;
}
// Add the number of events to the statistics accumulator
lStatAccumulator (eventIdx);
// Reset the service (including the event queue) for the next run
eventIdx = 0;
trademgenService.reset();
}
// DEBUG
std::ostringstream oStr;
stat_display (oStr, lStatAccumulator);
STDAIR_LOG_DEBUG (oStr.str());
// Close the Log outputFile
logOutputFile.close();
return 0;
}
<|endoftext|> |
<commit_before>#include <dsp.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <maSize.h>
#include <maMesh.h>
#include <PCU.h>
#include <sstream>
#include <vector>
using namespace std;
static void writeStep(apf::Mesh* m, int i)
{
std::stringstream ss;
ss << "step_" << i << "_";
std::string s = ss.str();
apf::writeVtkFiles(s.c_str(), m);
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
if ( argc != 3 ) {
fprintf(stderr, "Usage: %s <model> <mesh>\n", argv[0]);
return 0;
}
gmi_register_mesh();
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
dsp::Boundary moving;
moving.insert(m->findModelEntity(2, 57));
moving.insert(m->findModelEntity(2, 62));
moving.insert(m->findModelEntity(2, 66));
dsp::closeBoundary(m, moving);
dsp::Boundary fixed;
fixed.insert(m->findModelEntity(2, 26));
fixed.insert(m->findModelEntity(2, 6));
fixed.insert(m->findModelEntity(2, 17));
dsp::closeBoundary(m, fixed);
// dsp::Smoother* smoother = dsp::Smoother::makeSemiSpring();
dsp::Smoother* smoother = dsp::Smoother::makeLaplacian();
//double avgEdgeLen = ma::getAverageEdgeLength(m);
//dsp::Adapter* adapter = dsp::Adapter::makeUniform(avgEdgeLen);
dsp::Adapter* adapter = dsp::Adapter::makeEmpty();
apf::Vector3 a;
apf::Vector3 b;
ma::getBoundingBox(m, a, b);
double zDist = b.z() - a.z();
apf::Vector3 t(0,0, zDist / 30);
apf::Matrix3x3 r(1,0,0,
0,1,0,
0,0,1);
writeStep(m, 0);
vector < apf::MeshEntity* > V_total;
int in_0; int fb_0;
smoother->preprocess(m, fixed, moving, V_total, in_0, fb_0);
/* number of displacement steps */
for (int i = 0; i < 10; ++i) {
apf::Field* dsp = dsp::applyRigidMotion(m, moving, r, t);
smoother->smooth(dsp, V_total, in_0, fb_0);
//dsp::tryToDisplace(m, dsp);
apf::axpy(1, dsp, m->getCoordinateField());
apf::destroyField(dsp);
writeStep(m, i + 1);
smoother->cleanup(m);
}
delete smoother;
delete adapter;
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>try to print mesh quality<commit_after>#include <dsp.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <maSize.h>
#include <maMesh.h>
#include <PCU.h>
#include <sstream>
#include <vector>
using namespace std;
static void writeStep(apf::Mesh* m, int i)
{
std::stringstream ss;
ss << "step_" << i << "_";
std::string s = ss.str();
apf::writeVtkFiles(s.c_str(), m);
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
if ( argc != 3 ) {
fprintf(stderr, "Usage: %s <model> <mesh>\n", argv[0]);
return 0;
}
gmi_register_mesh();
apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
dsp::Boundary moving;
moving.insert(m->findModelEntity(2, 57));
moving.insert(m->findModelEntity(2, 62));
moving.insert(m->findModelEntity(2, 66));
dsp::closeBoundary(m, moving);
dsp::Boundary fixed;
fixed.insert(m->findModelEntity(2, 26));
fixed.insert(m->findModelEntity(2, 6));
fixed.insert(m->findModelEntity(2, 17));
dsp::closeBoundary(m, fixed);
// dsp::Smoother* smoother = dsp::Smoother::makeSemiSpring();
dsp::Smoother* smoother = dsp::Smoother::makeLaplacian();
//double avgEdgeLen = ma::getAverageEdgeLength(m);
//dsp::Adapter* adapter = dsp::Adapter::makeUniform(avgEdgeLen);
dsp::Adapter* adapter = dsp::Adapter::makeEmpty();
apf::Vector3 a;
apf::Vector3 b;
ma::getBoundingBox(m, a, b);
double zDist = b.z() - a.z();
apf::Vector3 t(0,0, zDist / 30);
apf::Matrix3x3 r(1,0,0,
0,1,0,
0,0,1);
writeStep(m, 0);
vector < apf::MeshEntity* > V_total;
int in_0; int fb_0;
smoother->preprocess(m, fixed, moving, V_total, in_0, fb_0);
/* number of displacement steps */
for (int i = 0; i < 10; ++i) {
apf::Field* dsp = dsp::applyRigidMotion(m, moving, r, t);
smoother->smooth(dsp, V_total, in_0, fb_0);
//dsp::tryToDisplace(m, dsp);
apf::axpy(1, dsp, m->getCoordinateField());
writeStep(m, i + 1);
apf::destroyField(dsp);
smoother->cleanup(m);
}
delete smoother;
delete adapter;
m->destroyNative();
apf::destroyMesh(m);
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|> |
<commit_before>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
const int lenn(100000000);
int tr(ftruncate(hdl, lenn));
if (tr == -1)
perror("ftruncate");
void* area(mmap(reinterpret_cast<void*>(0xF0000000UL),
lenn,
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == area)
perror("mmap");
else
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
sleep(3);
int um(munmap(area, lenn));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<commit_msg>some more docu and layout take down some ideas that keep coming<commit_after>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// The number of pages a cluster consists of (2^p) is dependent
// on the cluster, so the world must store the ps in the special
// cluster in order to be able to find the cluster boundaries.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// World: define the layout of a world in the memory
// and subdivide in pages. Provide info about the
// location and
// NUMPAGES
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct World
{
struct Page
{
char raw[1 << PAGE];
};
Page pages[NUMPAGES];
};
// MISC ideas
// allocation: tell a cluster to allocate an obj of a certain
// metadata "class". returns a cluster address, which may be the
// same as the current cluster or pointer to a new cluster with
// the object being in there. In this case the pointer must be
// stored away for the next allocation request.
// GC: use a posix message queue to tell which thread stack ranges
// must be mprotected. This way the threads can be starved out
// systematically.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
const int lenn(100000000);
int tr(ftruncate(hdl, lenn));
if (tr == -1)
perror("ftruncate");
void* area(mmap(reinterpret_cast<void*>(0xF0000000UL),
lenn,
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == area)
perror("mmap");
else
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
sleep(3);
int um(munmap(area, lenn));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<|endoftext|> |
<commit_before>#include "line_plot.hpp"
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <QPainter>
#include <QPainterPath>
#include <QDebug>
using namespace std;
namespace datavis {
LinePlot::LinePlot(QObject * parent):
Plot(parent)
{}
json LinePlot::save()
{
json d;
d["type"] = "line";
d["dim"] = m_dim;
return d;
}
void LinePlot::restore(const DataSetPtr & dataset, const json & options)
{
int dim = options.at("dim");
setDataSet(dataset, dim);
}
void LinePlot::setDataSet(DataSetPtr dataset)
{
setDataSet(dataset, 0);
}
void LinePlot::setDataSet(DataSetPtr dataset, int dim)
{
if (m_dataset)
m_dataset->disconnect(this);
m_dataset = dataset;
if (m_dataset)
{
connect(m_dataset.get(), &DataSet::selectionChanged,
this, &LinePlot::onSelectionChanged);
}
if (!dataset || dataset->data()->size().empty())
{
m_dim = -1;
m_start = 0;
m_end = 0;
}
else
{
auto size = dataset->data()->size();
if (size.size() > dim)
{
m_dim = dim;
}
else
{
m_dim = 0;
}
m_start = 0;
m_end = size[dim];
}
findEntireValueRange();
update_selected_region();
emit sourceChanged();
emit dimensionChanged();
emit xRangeChanged();
emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setDimension(int dim)
{
if (!m_dataset)
return;
auto size = m_dataset->data()->size();
if (dim < 0 || dim >= size.size())
dim = -1;
m_dim = dim;
if (dim >= 0)
{
m_start = 0;
m_end = size[dim];
}
else
{
m_start = 0;
m_end = 0;
}
update_selected_region();
emit dimensionChanged();
emit xRangeChanged();
//emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setRange(int start, int end)
{
if (!m_dataset)
return;
auto size = m_dataset->data()->size();
if (size.empty())
return;
if (m_dim < 0 || m_dim >= size.size())
{
cerr << "Unexpected: current dimension is invalid." << endl;
return;
}
if (end < start)
{
cerr << "Warning: negative range." << endl;
return;
}
if (start < 0 || start + end >= size[m_dim])
{
cerr << "Warning: selected range out of array bounds." << endl;
return;
}
m_start = start;
m_end = end;
update_selected_region();
emit xRangeChanged();
//emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setColor(const QColor & color)
{
m_color = color;
emit colorChanged();
emit contentChanged();
}
void LinePlot::onSelectionChanged()
{
// FIXME: Optimize: only update if needed
update_selected_region();
emit contentChanged();
}
void LinePlot::findEntireValueRange()
{
if (!m_dataset)
m_value_range = Range(0,0);
auto region = get_all(*m_dataset->data());
double min = 0;
double max = 0;
auto it = region.begin();
if (it != region.end())
{
min = max = it.value();
}
for(; it != region.end(); ++it)
{
double v = it.value();
min = std::min(min, v);
max = std::max(max, v);
}
m_value_range.min = min;
m_value_range.max = max;
}
void LinePlot::update_selected_region()
{
m_data_region = getDataRegion(m_start, m_end - m_start);
m_cache.clear();
}
LinePlot::data_region_type LinePlot::getDataRegion(int region_start, int region_size)
{
if (!m_dataset)
{
return data_region_type();
}
if (m_dim < 0)
{
return data_region_type();
}
auto data_size = m_dataset->data()->size();
auto n_dim = data_size.size();
vector<int> offset(n_dim, 0);
vector<int> size(n_dim, 1);
auto selected_index = m_dataset->selectedIndex();
#if 0
cout << "LinePlot: selected index: ";
for (auto & i : selected_index)
cout << i << " ";
cout << endl;
#endif
for (int dim = 0; dim < n_dim; ++dim)
{
if (dim == m_dim)
{
offset[dim] = region_start;
size[dim] = region_size;
}
else
{
offset[dim] = selected_index[dim];
}
}
return get_region(*m_dataset->data(), offset, size);
}
Plot::Range LinePlot::xRange()
{
if (!m_data_region.is_valid())
{
return Range();
}
auto dim = m_dataset->dimension(m_dim);
return Range { dim.map * m_start, dim.map * (m_end - 1) };
}
Plot::Range LinePlot::yRange()
{
return m_value_range;
#if 0
if (!m_data_region.is_valid())
{
return Range();
}
auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());
auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());
double min_value = min_it.value();
double max_value = max_it.value();
return Range { min_value, max_value };
#endif
}
tuple<vector<double>, vector<double>> LinePlot::dataLocation(const QPointF & point)
{
if (isEmpty())
return {};
auto offset = m_data_region.offset();
vector<double> location(m_dataset->dimensionCount());
for (int d = 0; d < offset.size(); ++d)
{
if (d == m_dim)
{
location[d] = point.x();
}
else
{
auto dim = m_dataset->dimension(d);
location[d] = dim.map * offset[d];
}
}
vector<double> attributes(m_dataset->attributeCount(), 0);
attributes[0] = point.y();
return { location, attributes };
}
LinePlot::DataCache * LinePlot::getCache(double dataPerPixel)
{
//cout << "Requested cache for resolution: " << dataPerPixel << endl;
double required_data_per_pixel = dataPerPixel / m_cache_use_factor;
int cache_level = int(std::log(required_data_per_pixel) / std::log(m_cache_factor));
if (cache_level < 1)
return nullptr;
int required_block_size = std::pow(m_cache_factor, cache_level);
//cout << "Block size: " << required_block_size << endl;
auto cache_iter = m_cache.begin();
for(; cache_iter != m_cache.end(); ++cache_iter)
{
if (cache_iter->block_size == required_block_size)
return &(*cache_iter);
else if (cache_iter->block_size < required_block_size)
break;
}
cache_iter = m_cache.emplace(cache_iter);
makeCache(*cache_iter, required_block_size);
return &(*cache_iter);
}
void LinePlot::makeCache(DataCache & cache, int blockSize)
{
//cout << "Making cache with block size: " << blockSize << endl;
cache.data.clear();
cache.block_size = blockSize;
if (!m_data_region.is_valid())
return;
auto it = m_data_region.begin();
while(it != m_data_region.end())
{
double min, max;
for(int i = 0; i < blockSize && it != m_data_region.end(); ++i, ++it)
{
auto & element = *it;
auto value = element.value();
if (i == 0)
{
min = max = value;
}
else
{
min = std::min(min, value);
max = std::max(max, value);
}
}
cache.data.emplace_back(min, max);
}
}
void LinePlot::plot(QPainter * painter, const Mapping2d & transform, const QRectF & region)
{
if (!m_data_region.is_valid())
return;
auto dim = m_dataset->dimension(m_dim);
int region_start = int(region.x() / dim.map);
int region_size = int(region.width() / dim.map);
region_start = std::max(region_start, m_start);
region_size = std::min(region_size, m_end - m_start);
//cout << "Region: " << region_start << " + " << region_size << endl;
if (region_size <= 0)
return;
auto min_x = transform.x_scale * region.x() + transform.x_offset;
auto max_x = transform.x_scale * (region.x() + region.width()) + transform.x_offset;
//cout << "View X range: " << min_x << ", " << max_x << endl;
if (max_x <= min_x)
return;
data_region_type data_region = getDataRegion(region_start, region_size);
double data_per_pixel = region_size / double(max_x - min_x);
auto cache = getCache(data_per_pixel);
painter->save();
if (cache)
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, false);
int cache_index = 0;
double min_y, max_y;
for (int x = min_x; x < max_x; ++x)
{
bool first = true;
for(; cache_index < cache->data.size(); ++cache_index)
{
int data_index = cache_index * cache->block_size;
QPointF data_point(dim.map * data_index, 0);
auto point = transform * data_point;
if (point.x() >= x + 1)
break;
auto & data = cache->data[cache_index];
if (first)
{
min_y = data.min;
max_y = data.max;
}
else
{
min_y = std::min(min_y, data.min);
max_y = std::max(max_y, data.max);
}
first = false;
}
if (!first) // Make sure we got at least one item
{
auto min_point = transform * QPointF(0, min_y);
auto max_point = transform * QPointF(0, max_y);
painter->drawLine(x, min_point.y(), x, max_point.y());
}
}
}
else if (max_x - min_x < region_size * 0.8)
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, false);
auto it = data_region.begin();
bool first = true;
double max_y;
double min_y;
double last_y;
for (int x = min_x; x < max_x; ++x)
{
while(it != data_region.end())
{
const auto & element = *it;
double loc = element.location()[m_dim];
loc = dim.map * loc;
double value = element.value();
auto point = transform * QPointF(loc, value);
if (point.x() >= x + 1)
break;
if (first)
{
min_y = max_y = point.y();
}
else
{
if (point.y() > max_y)
max_y = point.y();
else if (point.y() < min_y)
min_y = point.y();
}
last_y = point.y();
++it;
first = false;
}
if (!first) // Just in case, make sure we got at least one item
{
int min_y_pixel = int(round(min_y));
int max_y_pixel = int(round(max_y));
if (max_y_pixel == min_y_pixel)
max_y_pixel += 1;
painter->drawLine(x, min_y_pixel, x, max_y_pixel);
// Include last point to connect old and new line
max_y = min_y = last_y;
}
}
}
else
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, true);
QPainterPath path;
bool first = true;
for (auto & element : data_region)
{
double loc = element.location()[m_dim];
loc = dim.map * loc;
double value = element.value();
auto point = transform * QPointF(loc, value);
if (first)
path.moveTo(point);
else
path.lineTo(point);
first = false;
}
painter->drawPath(path);
}
painter->restore();
}
}
<commit_msg>LinePlot: Fix displayed data region<commit_after>#include "line_plot.hpp"
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <QPainter>
#include <QPainterPath>
#include <QDebug>
using namespace std;
namespace datavis {
LinePlot::LinePlot(QObject * parent):
Plot(parent)
{}
json LinePlot::save()
{
json d;
d["type"] = "line";
d["dim"] = m_dim;
return d;
}
void LinePlot::restore(const DataSetPtr & dataset, const json & options)
{
int dim = options.at("dim");
setDataSet(dataset, dim);
}
void LinePlot::setDataSet(DataSetPtr dataset)
{
setDataSet(dataset, 0);
}
void LinePlot::setDataSet(DataSetPtr dataset, int dim)
{
if (m_dataset)
m_dataset->disconnect(this);
m_dataset = dataset;
if (m_dataset)
{
connect(m_dataset.get(), &DataSet::selectionChanged,
this, &LinePlot::onSelectionChanged);
}
if (!dataset || dataset->data()->size().empty())
{
m_dim = -1;
m_start = 0;
m_end = 0;
}
else
{
auto size = dataset->data()->size();
if (size.size() > dim)
{
m_dim = dim;
}
else
{
m_dim = 0;
}
m_start = 0;
m_end = size[dim];
}
findEntireValueRange();
update_selected_region();
emit sourceChanged();
emit dimensionChanged();
emit xRangeChanged();
emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setDimension(int dim)
{
if (!m_dataset)
return;
auto size = m_dataset->data()->size();
if (dim < 0 || dim >= size.size())
dim = -1;
m_dim = dim;
if (dim >= 0)
{
m_start = 0;
m_end = size[dim];
}
else
{
m_start = 0;
m_end = 0;
}
update_selected_region();
emit dimensionChanged();
emit xRangeChanged();
//emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setRange(int start, int end)
{
if (!m_dataset)
return;
auto size = m_dataset->data()->size();
if (size.empty())
return;
if (m_dim < 0 || m_dim >= size.size())
{
cerr << "Unexpected: current dimension is invalid." << endl;
return;
}
if (end < start)
{
cerr << "Warning: negative range." << endl;
return;
}
if (start < 0 || start + end >= size[m_dim])
{
cerr << "Warning: selected range out of array bounds." << endl;
return;
}
m_start = start;
m_end = end;
update_selected_region();
emit xRangeChanged();
//emit yRangeChanged();
emit contentChanged();
}
void LinePlot::setColor(const QColor & color)
{
m_color = color;
emit colorChanged();
emit contentChanged();
}
void LinePlot::onSelectionChanged()
{
// FIXME: Optimize: only update if needed
update_selected_region();
emit contentChanged();
}
void LinePlot::findEntireValueRange()
{
if (!m_dataset)
m_value_range = Range(0,0);
auto region = get_all(*m_dataset->data());
double min = 0;
double max = 0;
auto it = region.begin();
if (it != region.end())
{
min = max = it.value();
}
for(; it != region.end(); ++it)
{
double v = it.value();
min = std::min(min, v);
max = std::max(max, v);
}
m_value_range.min = min;
m_value_range.max = max;
}
void LinePlot::update_selected_region()
{
m_data_region = getDataRegion(m_start, m_end - m_start);
m_cache.clear();
}
LinePlot::data_region_type LinePlot::getDataRegion(int region_start, int region_size)
{
if (!m_dataset)
{
return data_region_type();
}
if (m_dim < 0)
{
return data_region_type();
}
auto data_size = m_dataset->data()->size();
auto n_dim = data_size.size();
vector<int> offset(n_dim, 0);
vector<int> size(n_dim, 1);
auto selected_index = m_dataset->selectedIndex();
#if 0
cout << "LinePlot: selected index: ";
for (auto & i : selected_index)
cout << i << " ";
cout << endl;
#endif
for (int dim = 0; dim < n_dim; ++dim)
{
if (dim == m_dim)
{
offset[dim] = region_start;
size[dim] = region_size;
}
else
{
offset[dim] = selected_index[dim];
}
}
return get_region(*m_dataset->data(), offset, size);
}
Plot::Range LinePlot::xRange()
{
if (!m_data_region.is_valid())
{
return Range();
}
auto dim = m_dataset->dimension(m_dim);
return Range { dim.map * m_start, dim.map * (m_end - 1) };
}
Plot::Range LinePlot::yRange()
{
return m_value_range;
#if 0
if (!m_data_region.is_valid())
{
return Range();
}
auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());
auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());
double min_value = min_it.value();
double max_value = max_it.value();
return Range { min_value, max_value };
#endif
}
tuple<vector<double>, vector<double>> LinePlot::dataLocation(const QPointF & point)
{
if (isEmpty())
return {};
auto offset = m_data_region.offset();
vector<double> location(m_dataset->dimensionCount());
for (int d = 0; d < offset.size(); ++d)
{
if (d == m_dim)
{
location[d] = point.x();
}
else
{
auto dim = m_dataset->dimension(d);
location[d] = dim.map * offset[d];
}
}
vector<double> attributes(m_dataset->attributeCount(), 0);
attributes[0] = point.y();
return { location, attributes };
}
LinePlot::DataCache * LinePlot::getCache(double dataPerPixel)
{
//cout << "Requested cache for resolution: " << dataPerPixel << endl;
double required_data_per_pixel = dataPerPixel / m_cache_use_factor;
int cache_level = int(std::log(required_data_per_pixel) / std::log(m_cache_factor));
if (cache_level < 1)
return nullptr;
int required_block_size = std::pow(m_cache_factor, cache_level);
//cout << "Block size: " << required_block_size << endl;
auto cache_iter = m_cache.begin();
for(; cache_iter != m_cache.end(); ++cache_iter)
{
if (cache_iter->block_size == required_block_size)
return &(*cache_iter);
else if (cache_iter->block_size < required_block_size)
break;
}
cache_iter = m_cache.emplace(cache_iter);
makeCache(*cache_iter, required_block_size);
return &(*cache_iter);
}
void LinePlot::makeCache(DataCache & cache, int blockSize)
{
//cout << "Making cache with block size: " << blockSize << endl;
cache.data.clear();
cache.block_size = blockSize;
if (!m_data_region.is_valid())
return;
auto it = m_data_region.begin();
while(it != m_data_region.end())
{
double min, max;
for(int i = 0; i < blockSize && it != m_data_region.end(); ++i, ++it)
{
auto & element = *it;
auto value = element.value();
if (i == 0)
{
min = max = value;
}
else
{
min = std::min(min, value);
max = std::max(max, value);
}
}
cache.data.emplace_back(min, max);
}
}
void LinePlot::plot(QPainter * painter, const Mapping2d & transform, const QRectF & region)
{
if (!m_data_region.is_valid())
return;
auto dim = m_dataset->dimension(m_dim);
int region_start = int(region.x() / dim.map);
int region_end = int((region.x() + region.width()) / dim.map);
int region_size = region_end - region_start + 1;
region_start = std::max(region_start, m_start);
region_size = std::min(region_size, m_end - m_start);
if (region_size <= 0)
return;
auto min_x = transform.x_scale * region.x() + transform.x_offset;
auto max_x = transform.x_scale * (region.x() + region.width()) + transform.x_offset;
//cout << "View X range: " << min_x << ", " << max_x << endl;
if (max_x <= min_x)
return;
data_region_type data_region = getDataRegion(region_start, region_size);
double data_per_pixel = region_size / double(max_x - min_x);
auto cache = getCache(data_per_pixel);
painter->save();
if (cache)
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, false);
int cache_index = 0;
double min_y, max_y;
for (int x = min_x; x < max_x; ++x)
{
bool first = true;
for(; cache_index < cache->data.size(); ++cache_index)
{
int data_index = cache_index * cache->block_size;
QPointF data_point(dim.map * data_index, 0);
auto point = transform * data_point;
if (point.x() >= x + 1)
break;
auto & data = cache->data[cache_index];
if (first)
{
min_y = data.min;
max_y = data.max;
}
else
{
min_y = std::min(min_y, data.min);
max_y = std::max(max_y, data.max);
}
first = false;
}
if (!first) // Make sure we got at least one item
{
auto min_point = transform * QPointF(0, min_y);
auto max_point = transform * QPointF(0, max_y);
painter->drawLine(x, min_point.y(), x, max_point.y());
}
}
}
else if (max_x - min_x < region_size * 0.8)
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, false);
auto it = data_region.begin();
bool first = true;
double max_y;
double min_y;
double last_y;
for (int x = min_x; x < max_x; ++x)
{
while(it != data_region.end())
{
const auto & element = *it;
double loc = element.location()[m_dim];
loc = dim.map * loc;
double value = element.value();
auto point = transform * QPointF(loc, value);
if (point.x() >= x + 1)
break;
if (first)
{
min_y = max_y = point.y();
}
else
{
if (point.y() > max_y)
max_y = point.y();
else if (point.y() < min_y)
min_y = point.y();
}
last_y = point.y();
++it;
first = false;
}
if (!first) // Just in case, make sure we got at least one item
{
int min_y_pixel = int(round(min_y));
int max_y_pixel = int(round(max_y));
if (max_y_pixel == min_y_pixel)
max_y_pixel += 1;
painter->drawLine(x, min_y_pixel, x, max_y_pixel);
// Include last point to connect old and new line
max_y = min_y = last_y;
}
}
}
else
{
QPen line_pen;
line_pen.setWidth(1);
line_pen.setColor(m_color);
painter->setPen(line_pen);
painter->setBrush(Qt::NoBrush);
painter->setRenderHint(QPainter::Antialiasing, true);
QPainterPath path;
bool first = true;
for (auto & element : data_region)
{
double loc = element.location()[m_dim];
loc = dim.map * loc;
double value = element.value();
auto point = transform * QPointF(loc, value);
if (first)
path.moveTo(point);
else
path.lineTo(point);
first = false;
}
painter->drawPath(path);
}
painter->restore();
}
}
<|endoftext|> |
<commit_before>//===- llvm/unittest/ADT/OptionalTest.cpp - Optional unit tests -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/Optional.h"
using namespace llvm;
namespace {
struct NonDefaultConstructible {
static unsigned CopyConstructions;
static unsigned Destructions;
static unsigned CopyAssignments;
explicit NonDefaultConstructible(int) {
}
NonDefaultConstructible(const NonDefaultConstructible&) {
++CopyConstructions;
}
NonDefaultConstructible &operator=(const NonDefaultConstructible&) {
++CopyAssignments;
return *this;
}
~NonDefaultConstructible() {
++Destructions;
}
static void ResetCounts() {
CopyConstructions = 0;
Destructions = 0;
CopyAssignments = 0;
}
};
unsigned NonDefaultConstructible::CopyConstructions = 0;
unsigned NonDefaultConstructible::Destructions = 0;
unsigned NonDefaultConstructible::CopyAssignments = 0;
// Test fixture
class OptionalTest : public testing::Test {
};
TEST_F(OptionalTest, NonDefaultConstructibleTest) {
Optional<NonDefaultConstructible> O;
EXPECT_FALSE(O);
}
TEST_F(OptionalTest, ResetTest) {
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible> O(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
O.reset();
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, InitializationLeakTest) {
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible>(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, CopyConstructionTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible> B(A);
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, ConstructingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
Optional<NonDefaultConstructible> B;
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, CopyingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
Optional<NonDefaultConstructible> B(NonDefaultConstructible(4));
EXPECT_EQ(2u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(1u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, DeletingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A;
Optional<NonDefaultConstructible> B(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, NullCopyConstructionTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A;
Optional<NonDefaultConstructible> B;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, GetValueOr) {
Optional<int> A;
EXPECT_EQ(42, A.getValueOr(42));
A = 5;
EXPECT_EQ(5, A.getValueOr(42));
}
struct MultiArgConstructor {
int x, y;
MultiArgConstructor(int x, int y) : x(x), y(y) {}
explicit MultiArgConstructor(int x, bool positive)
: x(x), y(positive ? x : -x) {}
MultiArgConstructor(const MultiArgConstructor &) = delete;
MultiArgConstructor(MultiArgConstructor &&) = delete;
MultiArgConstructor &operator=(const MultiArgConstructor &) = delete;
MultiArgConstructor &operator=(MultiArgConstructor &&) = delete;
static unsigned Destructions;
~MultiArgConstructor() {
++Destructions;
}
static void ResetCounts() {
Destructions = 0;
}
};
unsigned MultiArgConstructor::Destructions = 0;
TEST_F(OptionalTest, Emplace) {
MultiArgConstructor::ResetCounts();
Optional<MultiArgConstructor> A;
A.emplace(1, 2);
EXPECT_TRUE(A.hasValue());
EXPECT_EQ(1, A->x);
EXPECT_EQ(2, A->y);
EXPECT_EQ(0u, MultiArgConstructor::Destructions);
A.emplace(5, false);
EXPECT_TRUE(A.hasValue());
EXPECT_EQ(5, A->x);
EXPECT_EQ(-5, A->y);
EXPECT_EQ(1u, MultiArgConstructor::Destructions);
}
struct MoveOnly {
static unsigned MoveConstructions;
static unsigned Destructions;
static unsigned MoveAssignments;
int val;
explicit MoveOnly(int val) : val(val) {
}
MoveOnly(MoveOnly&& other) {
val = other.val;
++MoveConstructions;
}
MoveOnly &operator=(MoveOnly&& other) {
val = other.val;
++MoveAssignments;
return *this;
}
~MoveOnly() {
++Destructions;
}
static void ResetCounts() {
MoveConstructions = 0;
Destructions = 0;
MoveAssignments = 0;
}
};
unsigned MoveOnly::MoveConstructions = 0;
unsigned MoveOnly::Destructions = 0;
unsigned MoveOnly::MoveAssignments = 0;
TEST_F(OptionalTest, MoveOnlyNull) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O;
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(0u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyConstruction) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O(MoveOnly(3));
EXPECT_TRUE((bool)O);
EXPECT_EQ(3, O->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyMoveConstruction) {
Optional<MoveOnly> A(MoveOnly(3));
MoveOnly::ResetCounts();
Optional<MoveOnly> B(std::move(A));
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyAssignment) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O;
O = MoveOnly(3);
EXPECT_TRUE((bool)O);
EXPECT_EQ(3, O->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyInitializingAssignment) {
Optional<MoveOnly> A(MoveOnly(3));
Optional<MoveOnly> B;
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyNullingAssignment) {
Optional<MoveOnly> A;
Optional<MoveOnly> B(MoveOnly(3));
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_FALSE((bool)B);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyAssigningAssignment) {
Optional<MoveOnly> A(MoveOnly(3));
Optional<MoveOnly> B(MoveOnly(4));
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(1u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyEmplace) {
Optional<MoveOnly> A;
MoveOnly::ResetCounts();
A.emplace(4);
EXPECT_TRUE((bool)A);
EXPECT_EQ(4, A->val);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(0u, MoveOnly::Destructions);
}
#if LLVM_HAS_RVALUE_REFERENCE_THIS
TEST_F(OptionalTest, MoveGetValueOr) {
Optional<MoveOnly> A;
MoveOnly::ResetCounts();
EXPECT_EQ(42, std::move(A).getValueOr(MoveOnly(42)).val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(2u, MoveOnly::Destructions);
A = MoveOnly(5);
MoveOnly::ResetCounts();
EXPECT_EQ(5, std::move(A).getValueOr(MoveOnly(42)).val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(2u, MoveOnly::Destructions);
}
#endif // LLVM_HAS_RVALUE_REFERENCE_THIS
} // end anonymous namespace
<commit_msg>ADTTests/OptionalTest.cpp: Use LLVM_DELETED_FUNCTION.<commit_after>//===- llvm/unittest/ADT/OptionalTest.cpp - Optional unit tests -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/Optional.h"
using namespace llvm;
namespace {
struct NonDefaultConstructible {
static unsigned CopyConstructions;
static unsigned Destructions;
static unsigned CopyAssignments;
explicit NonDefaultConstructible(int) {
}
NonDefaultConstructible(const NonDefaultConstructible&) {
++CopyConstructions;
}
NonDefaultConstructible &operator=(const NonDefaultConstructible&) {
++CopyAssignments;
return *this;
}
~NonDefaultConstructible() {
++Destructions;
}
static void ResetCounts() {
CopyConstructions = 0;
Destructions = 0;
CopyAssignments = 0;
}
};
unsigned NonDefaultConstructible::CopyConstructions = 0;
unsigned NonDefaultConstructible::Destructions = 0;
unsigned NonDefaultConstructible::CopyAssignments = 0;
// Test fixture
class OptionalTest : public testing::Test {
};
TEST_F(OptionalTest, NonDefaultConstructibleTest) {
Optional<NonDefaultConstructible> O;
EXPECT_FALSE(O);
}
TEST_F(OptionalTest, ResetTest) {
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible> O(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
O.reset();
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, InitializationLeakTest) {
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible>(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, CopyConstructionTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
Optional<NonDefaultConstructible> B(A);
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, ConstructingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
Optional<NonDefaultConstructible> B;
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, CopyingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A(NonDefaultConstructible(3));
Optional<NonDefaultConstructible> B(NonDefaultConstructible(4));
EXPECT_EQ(2u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(1u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(2u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, DeletingCopyAssignmentTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A;
Optional<NonDefaultConstructible> B(NonDefaultConstructible(3));
EXPECT_EQ(1u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(1u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, NullCopyConstructionTest) {
NonDefaultConstructible::ResetCounts();
{
Optional<NonDefaultConstructible> A;
Optional<NonDefaultConstructible> B;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
B = A;
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
NonDefaultConstructible::ResetCounts();
}
EXPECT_EQ(0u, NonDefaultConstructible::CopyConstructions);
EXPECT_EQ(0u, NonDefaultConstructible::CopyAssignments);
EXPECT_EQ(0u, NonDefaultConstructible::Destructions);
}
TEST_F(OptionalTest, GetValueOr) {
Optional<int> A;
EXPECT_EQ(42, A.getValueOr(42));
A = 5;
EXPECT_EQ(5, A.getValueOr(42));
}
struct MultiArgConstructor {
int x, y;
MultiArgConstructor(int x, int y) : x(x), y(y) {}
explicit MultiArgConstructor(int x, bool positive)
: x(x), y(positive ? x : -x) {}
MultiArgConstructor(const MultiArgConstructor &) LLVM_DELETED_FUNCTION;
MultiArgConstructor(MultiArgConstructor &&) LLVM_DELETED_FUNCTION;
MultiArgConstructor &operator=(const MultiArgConstructor &) LLVM_DELETED_FUNCTION;
MultiArgConstructor &operator=(MultiArgConstructor &&) LLVM_DELETED_FUNCTION;
static unsigned Destructions;
~MultiArgConstructor() {
++Destructions;
}
static void ResetCounts() {
Destructions = 0;
}
};
unsigned MultiArgConstructor::Destructions = 0;
TEST_F(OptionalTest, Emplace) {
MultiArgConstructor::ResetCounts();
Optional<MultiArgConstructor> A;
A.emplace(1, 2);
EXPECT_TRUE(A.hasValue());
EXPECT_EQ(1, A->x);
EXPECT_EQ(2, A->y);
EXPECT_EQ(0u, MultiArgConstructor::Destructions);
A.emplace(5, false);
EXPECT_TRUE(A.hasValue());
EXPECT_EQ(5, A->x);
EXPECT_EQ(-5, A->y);
EXPECT_EQ(1u, MultiArgConstructor::Destructions);
}
struct MoveOnly {
static unsigned MoveConstructions;
static unsigned Destructions;
static unsigned MoveAssignments;
int val;
explicit MoveOnly(int val) : val(val) {
}
MoveOnly(MoveOnly&& other) {
val = other.val;
++MoveConstructions;
}
MoveOnly &operator=(MoveOnly&& other) {
val = other.val;
++MoveAssignments;
return *this;
}
~MoveOnly() {
++Destructions;
}
static void ResetCounts() {
MoveConstructions = 0;
Destructions = 0;
MoveAssignments = 0;
}
};
unsigned MoveOnly::MoveConstructions = 0;
unsigned MoveOnly::Destructions = 0;
unsigned MoveOnly::MoveAssignments = 0;
TEST_F(OptionalTest, MoveOnlyNull) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O;
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(0u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyConstruction) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O(MoveOnly(3));
EXPECT_TRUE((bool)O);
EXPECT_EQ(3, O->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyMoveConstruction) {
Optional<MoveOnly> A(MoveOnly(3));
MoveOnly::ResetCounts();
Optional<MoveOnly> B(std::move(A));
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyAssignment) {
MoveOnly::ResetCounts();
Optional<MoveOnly> O;
O = MoveOnly(3);
EXPECT_TRUE((bool)O);
EXPECT_EQ(3, O->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyInitializingAssignment) {
Optional<MoveOnly> A(MoveOnly(3));
Optional<MoveOnly> B;
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyNullingAssignment) {
Optional<MoveOnly> A;
Optional<MoveOnly> B(MoveOnly(3));
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_FALSE((bool)B);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyAssigningAssignment) {
Optional<MoveOnly> A(MoveOnly(3));
Optional<MoveOnly> B(MoveOnly(4));
MoveOnly::ResetCounts();
B = std::move(A);
EXPECT_FALSE((bool)A);
EXPECT_TRUE((bool)B);
EXPECT_EQ(3, B->val);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(1u, MoveOnly::MoveAssignments);
EXPECT_EQ(1u, MoveOnly::Destructions);
}
TEST_F(OptionalTest, MoveOnlyEmplace) {
Optional<MoveOnly> A;
MoveOnly::ResetCounts();
A.emplace(4);
EXPECT_TRUE((bool)A);
EXPECT_EQ(4, A->val);
EXPECT_EQ(0u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(0u, MoveOnly::Destructions);
}
#if LLVM_HAS_RVALUE_REFERENCE_THIS
TEST_F(OptionalTest, MoveGetValueOr) {
Optional<MoveOnly> A;
MoveOnly::ResetCounts();
EXPECT_EQ(42, std::move(A).getValueOr(MoveOnly(42)).val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(2u, MoveOnly::Destructions);
A = MoveOnly(5);
MoveOnly::ResetCounts();
EXPECT_EQ(5, std::move(A).getValueOr(MoveOnly(42)).val);
EXPECT_EQ(1u, MoveOnly::MoveConstructions);
EXPECT_EQ(0u, MoveOnly::MoveAssignments);
EXPECT_EQ(2u, MoveOnly::Destructions);
}
#endif // LLVM_HAS_RVALUE_REFERENCE_THIS
} // end anonymous namespace
<|endoftext|> |
<commit_before>#include <unordered_map>
#include <dafs/handler.hpp>
#include <dafs/node.hpp>
#include <gtest/gtest.h>
#include "mock_partition.hpp"
#include "mock_sender.hpp"
class HandlerTest: public testing::Test
{
virtual void SetUp()
{
node_under_test = std::make_shared<dafs::Node>(
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Identity("11111111-1111-1111-1111-111111111111")
),
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Identity("22222222-2222-2222-2222-222222222222")
),
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Identity("33333333-3333-3333-3333-333333333333")
)
);
}
std::shared_ptr<dafs::Node> node_under_test;
public:
dafs::Node& GetNode()
{
return *node_under_test;
}
};
void ASSERT_ADDRESS_EQUAL(dafs::Address a, dafs::Address b)
{
ASSERT_EQ(a.ip, b.ip);
ASSERT_EQ(a.port, b.port);
}
TEST_F(HandlerTest, testHandleReadBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
GetNode().GetPartition(
dafs::Identity("22222222-2222-2222-2222-222222222222")
)->WriteBlock(info, format);
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
}
}
);
dafs::Message m = HandleReadBlock(GetNode(), parser);
dafs::BlockFormat result(
dafs::MetaDataParser(m.metadata).GetValue<dafs::BlockFormat>(
dafs::BlockFormatKey)
);
ASSERT_EQ(format.contents, result.contents);
}
TEST_F(HandlerTest, testHandleWriteBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
},
dafs::MetaData
{
dafs::BlockFormatKey,
dafs::Serialize(format)
}
}
);
HandleWriteBlock(GetNode(), parser);
ASSERT_EQ(
format.contents,
GetNode().GetPartition(dafs::Identity("22222222-2222-2222-2222-222222222222"))
->ReadBlock(info).contents);
}
TEST_F(HandlerTest, testHandleDeleteBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
},
dafs::MetaData
{
dafs::BlockFormatKey,
dafs::Serialize(format)
}
}
);
HandleWriteBlock(GetNode(), parser);
HandleDeleteBlock(GetNode(), parser);
ASSERT_EQ(
"",
GetNode().GetPartition(dafs::Identity("22222222-2222-2222-2222-222222222222"))
->ReadBlock(info).contents);
}
TEST_F(HandlerTest, testGetNodeDetails)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
}
);
MockSender mock_sender;
dafs::Message m = HandleGetNodeDetails(GetNode(), parser);
auto parsed = dafs::MetaDataParser(m.metadata);
auto m_identity = parsed.GetValue<dafs::Identity>(dafs::MinusIdentityKey);
auto z_identity = parsed.GetValue<dafs::Identity>(dafs::ZeroIdentityKey);
auto p_identity = parsed.GetValue<dafs::Identity>(dafs::PlusIdentityKey);
auto m_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::MinusReplicatedEndpointsKey);
auto z_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::ZeroReplicatedEndpointsKey);
auto p_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::PlusReplicatedEndpointsKey);
ASSERT_EQ(
dafs::Identity("11111111-1111-1111-1111-111111111111"),
m_identity);
ASSERT_EQ(
dafs::Identity("22222222-2222-2222-2222-222222222222"),
z_identity);
ASSERT_EQ(
dafs::Identity("33333333-3333-3333-3333-333333333333"),
p_identity);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), m_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), m_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), m_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), m_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), m_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), m_endpoints.plus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), z_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), z_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), z_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), z_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), z_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), z_endpoints.plus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), p_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), p_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), p_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), p_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), p_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), p_endpoints.plus.replication);
}
TEST_F(HandlerTest, testHandleJoinCluster)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::AddressKey,
dafs::Serialize(dafs::Address("A.B.C.D", 1234))
}
}
);
MockSender mock_sender;
HandleJoinCluster(GetNode(), parser, mock_sender);
dafs::Message sent_message = mock_sender.sentMessages()[0];
ASSERT_EQ(dafs::MessageType::_RequestMinusInitiation, sent_message.type);
auto parsed = dafs::MetaDataParser(sent_message.metadata);
auto endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::NodeEndpointsKey);
auto identity = parsed.GetValue<dafs::Identity>(dafs::IdentityKey);
ASSERT_EQ(
dafs::Identity("22222222-2222-2222-2222-222222222222"),
identity);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), endpoints.plus.replication);
}
TEST_F(HandlerTest, testHandleMinusInitiationWithOutOfOrderIdentity)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::IdentityKey,
dafs::Serialize(
dafs::Identity("99999999-9999-9999-9999-999999999999")
)
},
dafs::MetaData
{
dafs::NodeEndpointsKey,
dafs::Serialize(
dafs::ReplicatedEndpoints
{
}
)
}
}
);
MockSender mock_sender;
HandleRequestMinusInitiation(GetNode(), parser, mock_sender);
dafs::Message sent_message = mock_sender.sentMessages()[0];
ASSERT_EQ(dafs::MessageType::_JoinCluster, sent_message.type);
}
<commit_msg>Add unittest for active initiation of minus partition<commit_after>#include <unordered_map>
#include <dafs/handler.hpp>
#include <dafs/node.hpp>
#include <gtest/gtest.h>
#include "mock_partition.hpp"
#include "mock_sender.hpp"
class HandlerTest: public testing::Test
{
virtual void SetUp()
{
node_under_test = std::make_shared<dafs::Node>(
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Identity("11111111-1111-1111-1111-111111111111")
),
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Identity("22222222-2222-2222-2222-222222222222")
),
std::make_shared<MockPartition>(
dafs::Endpoint
{
dafs::Address("2.2.2.2", 2000),
dafs::Address("2.2.2.2", 2222)
},
dafs::Endpoint
{
dafs::Address("3.3.3.3", 3000),
dafs::Address("3.3.3.3", 3333)
},
dafs::Endpoint
{
dafs::Address("1.1.1.1", 1000),
dafs::Address("1.1.1.1", 1111)
},
dafs::Identity("33333333-3333-3333-3333-333333333333")
)
);
}
std::shared_ptr<dafs::Node> node_under_test;
public:
dafs::Node& GetNode()
{
return *node_under_test;
}
};
void ASSERT_ADDRESS_EQUAL(dafs::Address a, dafs::Address b)
{
ASSERT_EQ(a.ip, b.ip);
ASSERT_EQ(a.port, b.port);
}
TEST_F(HandlerTest, testHandleReadBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
GetNode().GetPartition(
dafs::Identity("22222222-2222-2222-2222-222222222222")
)->WriteBlock(info, format);
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
}
}
);
dafs::Message m = HandleReadBlock(GetNode(), parser);
dafs::BlockFormat result(
dafs::MetaDataParser(m.metadata).GetValue<dafs::BlockFormat>(
dafs::BlockFormatKey)
);
ASSERT_EQ(format.contents, result.contents);
}
TEST_F(HandlerTest, testHandleWriteBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
},
dafs::MetaData
{
dafs::BlockFormatKey,
dafs::Serialize(format)
}
}
);
HandleWriteBlock(GetNode(), parser);
ASSERT_EQ(
format.contents,
GetNode().GetPartition(dafs::Identity("22222222-2222-2222-2222-222222222222"))
->ReadBlock(info).contents);
}
TEST_F(HandlerTest, testHandleDeleteBlock)
{
dafs::BlockInfo info
{
"path/to/blockinfo",
dafs::Identity("22222222-2222-2222-2222-222222222222"),
0
};
dafs::BlockFormat format
{
"this is the content of the block format.",
};
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::BlockInfoKey,
dafs::Serialize(info)
},
dafs::MetaData
{
dafs::BlockFormatKey,
dafs::Serialize(format)
}
}
);
HandleWriteBlock(GetNode(), parser);
HandleDeleteBlock(GetNode(), parser);
ASSERT_EQ(
"",
GetNode().GetPartition(dafs::Identity("22222222-2222-2222-2222-222222222222"))
->ReadBlock(info).contents);
}
TEST_F(HandlerTest, testGetNodeDetails)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
}
);
MockSender mock_sender;
dafs::Message m = HandleGetNodeDetails(GetNode(), parser);
auto parsed = dafs::MetaDataParser(m.metadata);
auto m_identity = parsed.GetValue<dafs::Identity>(dafs::MinusIdentityKey);
auto z_identity = parsed.GetValue<dafs::Identity>(dafs::ZeroIdentityKey);
auto p_identity = parsed.GetValue<dafs::Identity>(dafs::PlusIdentityKey);
auto m_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::MinusReplicatedEndpointsKey);
auto z_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::ZeroReplicatedEndpointsKey);
auto p_endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::PlusReplicatedEndpointsKey);
ASSERT_EQ(
dafs::Identity("11111111-1111-1111-1111-111111111111"),
m_identity);
ASSERT_EQ(
dafs::Identity("22222222-2222-2222-2222-222222222222"),
z_identity);
ASSERT_EQ(
dafs::Identity("33333333-3333-3333-3333-333333333333"),
p_identity);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), m_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), m_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), m_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), m_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), m_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), m_endpoints.plus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), z_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), z_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), z_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), z_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), z_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), z_endpoints.plus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), p_endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), p_endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), p_endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), p_endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), p_endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), p_endpoints.plus.replication);
}
TEST_F(HandlerTest, testHandleJoinCluster)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::AddressKey,
dafs::Serialize(dafs::Address("A.B.C.D", 1234))
}
}
);
MockSender mock_sender;
HandleJoinCluster(GetNode(), parser, mock_sender);
dafs::Message sent_message = mock_sender.sentMessages()[0];
ASSERT_EQ(dafs::MessageType::_RequestMinusInitiation, sent_message.type);
auto parsed = dafs::MetaDataParser(sent_message.metadata);
auto endpoints = parsed.GetValue<dafs::ReplicatedEndpoints>(dafs::NodeEndpointsKey);
auto identity = parsed.GetValue<dafs::Identity>(dafs::IdentityKey);
ASSERT_EQ(
dafs::Identity("22222222-2222-2222-2222-222222222222"),
identity);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3000), endpoints.minus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("3.3.3.3", 3333), endpoints.minus.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), endpoints.zero.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1111), endpoints.zero.replication);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), endpoints.plus.management);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2222), endpoints.plus.replication);
}
TEST_F(HandlerTest, testHandleMinusInitiationWithOutOfOrderIdentity)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::IdentityKey,
dafs::Serialize(
dafs::Identity("99999999-9999-9999-9999-999999999999")
)
},
dafs::MetaData
{
dafs::NodeEndpointsKey,
dafs::Serialize(
dafs::ReplicatedEndpoints
{
}
)
}
}
);
MockSender mock_sender;
HandleRequestMinusInitiation(GetNode(), parser, mock_sender);
dafs::Message sent_message = mock_sender.sentMessages()[0];
ASSERT_EQ(dafs::MessageType::_JoinCluster, sent_message.type);
}
TEST_F(HandlerTest, testHandleMinusInitiationWithActivePartition)
{
dafs::MetaDataParser parser(
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::IdentityKey,
dafs::Serialize(
dafs::Identity("11111111-1111-1111-5555-555555555555")
)
},
dafs::MetaData
{
dafs::NodeEndpointsKey,
dafs::Serialize(
dafs::ReplicatedEndpoints
{
}
)
}
}
);
MockSender mock_sender;
HandleRequestMinusInitiation(GetNode(), parser, mock_sender);
dafs::Message sent_message = mock_sender.sentMessages()[0];
ASSERT_EQ(dafs::MessageType::_RequestPlusInitiation, sent_message.type);
ASSERT_ADDRESS_EQUAL(dafs::Address("1.1.1.1", 1000), sent_message.from);
ASSERT_ADDRESS_EQUAL(dafs::Address("2.2.2.2", 2000), sent_message.to);
}
<|endoftext|> |
<commit_before>#include "HalfEdgeMesh.h"
using namespace voom;
int main(){
HalfEdgeMesh::ConnectivityContainer connect(2);
//
//
// 0---3
// | \ |
// 1---2
connect[0] << 0, 1, 2;
connect[1] << 2, 3, 0;
int nverts=4;
HalfEdgeMesh mesh(connect,nverts);
std::cout << "vertices:"<< std::endl;
for(int a=0; a<mesh.vertices.size(); a++) {
std::cout << mesh.vertices[a]->id << std::endl;
}
std::cout << "HalfEdges:"<< std::endl;
for(int h=0; h<mesh.halfEdges.size(); h++) {
std::cout << "h: "<< mesh.halfEdges[h]->id << std::endl
<< "v: "<< (mesh.halfEdges[h]->vertex)->id << std::endl
<< "n: "<< (mesh.halfEdges[h]->next)->id << std::endl;
if(mesh.halfEdges[h]->opposite)
std::cout << "o: "<< (mesh.halfEdges[h]->opposite)->id << std::endl;
else
std::cout << "o: "<< -1 << std::endl;
std::cout << "f: "<< (mesh.halfEdges[h]->face)->id << std::endl
<< std::endl;
}
}
<commit_msg>Halfedge test passed.<commit_after>#include "HalfEdgeMesh.h"
using namespace voom;
int main(){
// HalfEdgeMesh::ConnectivityContainer connect(2);
// //
// //
// // 0---3
// // | \ |
// // 1---2
// connect[0] << 0, 1, 2;
// connect[1] << 2, 3, 0;
// int nverts=4;
HalfEdgeMesh::ConnectivityContainer connect(4);
// 0
// / \
// 1 ___ 2
// / \ / \
// 3__ 4 __ 5
//
connect[0] << 0, 1, 2; //face 0
connect[1] << 1, 4, 2; //face 1
connect[2] << 1, 3, 4; //face 2
connect[3] << 4, 5, 2; //face 3
int nverts=6;
HalfEdgeMesh mesh(connect,nverts);
std::cout << "vertices:"<< std::endl;
for(int a=0; a<mesh.vertices.size(); a++) {
std::cout << mesh.vertices[a]->id << std::endl;
}
std::cout << "HalfEdges:"<< std::endl;
for(int h=0; h<mesh.halfEdges.size(); h++) {
std::cout << "h: "<< mesh.halfEdges[h]->id << std::endl
<< "v: "<< (mesh.halfEdges[h]->vertex)->id << std::endl
<< "n: "<< (mesh.halfEdges[h]->next)->id << std::endl;
if(mesh.halfEdges[h]->opposite)
std::cout << "o: "<< (mesh.halfEdges[h]->opposite)->id << std::endl;
else
std::cout << "o: "<< -1 << std::endl;
std::cout << "f: "<< (mesh.halfEdges[h]->face)->id << std::endl
<< std::endl;
}
}
<|endoftext|> |
<commit_before>/**
* @file IntegerVectorEncoding.hpp
* @brief encoder interface implementation
*/
#include "../include/IntegerVectorEncoding.hpp"
#include <stdint.h>
#include <vector>
#include <unordered_map>
namespace backend
{
namespace genetic
{
IntegerVectorEncoding::IntegerVectorEncoding(const common::types::AbstractGraph& g) : ClusterEncoding(g)
{
}
} // namespace genetic
} // namespace backend
<commit_msg>Implemented constructor<commit_after>/**
* @file IntegerVectorEncoding.hpp
* @brief encoder interface implementation
*/
#include "../include/IntegerVectorEncoding.hpp"
#include <stdint.h>
#include <vector>
#include <unordered_map>
namespace backend
{
namespace genetic
{
IntegerVectorEncoding::IntegerVectorEncoding(const common::types::AbstractGraph& g) : ClusterEncoding(g)
{
// Set encoding to be as big as the vertex array
encoding.resize(g.getVertices().size());
}
} // namespace genetic
} // namespace backend
<|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 "content/gpu/gpu_info_collector.h"
#include <windows.h>
#include <d3d9.h>
#include <setupapi.h>
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/scoped_native_library.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "third_party/libxml/chromium/libxml_utils.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_surface_egl.h"
// ANGLE seems to require that main.h be included before any other ANGLE header.
#include "libEGL/Display.h"
#include "libEGL/main.h"
namespace {
// The version number stores the major and minor version in the least 16 bits;
// for example, 2.5 is 0x00000205.
// Returned string is in the format of "major.minor".
std::string VersionNumberToString(uint32 version_number) {
int hi = (version_number >> 8) & 0xff;
int low = version_number & 0xff;
return base::IntToString(hi) + "." + base::IntToString(low);
}
float ReadXMLFloatValue(XmlReader* reader) {
std::string score_string;
if (!reader->ReadElementContent(&score_string))
return 0.0;
double score;
if (!base::StringToDouble(score_string, &score))
return 0.0;
return static_cast<float>(score);
}
content::GpuPerformanceStats RetrieveGpuPerformanceStats() {
TRACE_EVENT0("gpu", "RetrieveGpuPerformanceStats");
// If the user re-runs the assessment without restarting, the COM API
// returns WINSAT_ASSESSMENT_STATE_NOT_AVAILABLE. Because of that and
// http://crbug.com/124325, read the assessment result files directly.
content::GpuPerformanceStats stats;
// Get path to WinSAT results files.
wchar_t winsat_results_path[MAX_PATH];
DWORD size = ExpandEnvironmentStrings(
L"%WinDir%\\Performance\\WinSAT\\DataStore\\",
winsat_results_path, MAX_PATH);
if (size == 0 || size > MAX_PATH) {
LOG(ERROR) << "The path to the WinSAT results is too long: "
<< size << " chars.";
return stats;
}
// Find most recent formal assessment results.
file_util::FileEnumerator file_enumerator(
FilePath(winsat_results_path),
false, // not recursive
file_util::FileEnumerator::FILES,
FILE_PATH_LITERAL("* * Formal.Assessment (*).WinSAT.xml"));
FilePath current_results;
for (FilePath results = file_enumerator.Next(); !results.empty();
results = file_enumerator.Next()) {
// The filenames start with the date and time as yyyy-mm-dd hh.mm.ss.xxx,
// so the greatest file lexicographically is also the most recent file.
if (FilePath::CompareLessIgnoreCase(current_results.value(),
results.value()))
current_results = results;
}
std::string current_results_string = current_results.MaybeAsASCII();
if (current_results_string.empty()) {
LOG(ERROR) << "Can't retrieve a valid WinSAT assessment.";
return stats;
}
// Get relevant scores from results file. XML schema at:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa969210.aspx
XmlReader reader;
if (!reader.LoadFile(current_results_string)) {
LOG(ERROR) << "Could not open WinSAT results file.";
return stats;
}
// Descend into <WinSAT> root element.
if (!reader.SkipToElement() || !reader.Read()) {
LOG(ERROR) << "Could not read WinSAT results file.";
return stats;
}
// Search for <WinSPR> element containing the results.
do {
if (reader.NodeName() == "WinSPR")
break;
} while (reader.Next());
// Descend into <WinSPR> element.
if (!reader.Read()) {
LOG(ERROR) << "Could not find WinSPR element in results file.";
return stats;
}
// Read scores.
for (int depth = reader.Depth(); reader.Depth() == depth; reader.Next()) {
std::string node_name = reader.NodeName();
if (node_name == "SystemScore")
stats.overall = ReadXMLFloatValue(&reader);
else if (node_name == "GraphicsScore")
stats.graphics = ReadXMLFloatValue(&reader);
else if (node_name == "GamingScore")
stats.gaming = ReadXMLFloatValue(&reader);
}
if (stats.overall == 0.0)
LOG(ERROR) << "Could not read overall score from assessment results.";
if (stats.graphics == 0.0)
LOG(ERROR) << "Could not read graphics score from assessment results.";
if (stats.gaming == 0.0)
LOG(ERROR) << "Could not read gaming score from assessment results.";
return stats;
}
content::GpuPerformanceStats RetrieveGpuPerformanceStatsWithHistograms() {
base::TimeTicks start_time = base::TimeTicks::Now();
content::GpuPerformanceStats stats = RetrieveGpuPerformanceStats();
UMA_HISTOGRAM_TIMES("GPU.WinSAT.ReadResultsFileTime",
base::TimeTicks::Now() - start_time);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.OverallScore2",
stats.overall * 10, 10, 200, 50);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.GraphicsScore2",
stats.graphics * 10, 10, 200, 50);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.GamingScore2",
stats.gaming * 10, 10, 200, 50);
UMA_HISTOGRAM_BOOLEAN(
"GPU.WinSAT.HasResults",
stats.overall != 0.0 && stats.graphics != 0.0 && stats.gaming != 0.0);
return stats;
}
} // namespace anonymous
namespace gpu_info_collector {
#if !defined(GOOGLE_CHROME_BUILD)
AMDVideoCardType GetAMDVideocardType() {
return UNKNOWN;
}
#else
// This function has a real implementation for official builds that can
// be found in src/third_party/amd.
AMDVideoCardType GetAMDVideocardType();
#endif
bool CollectGraphicsInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectGraphicsInfo");
DCHECK(gpu_info);
gpu_info->performance_stats = RetrieveGpuPerformanceStats();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) {
std::string requested_implementation_name =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);
if (requested_implementation_name == "swiftshader") {
gpu_info->software_rendering = true;
return false;
}
}
if (gfx::GetGLImplementation() != gfx::kGLImplementationEGLGLES2) {
gpu_info->finalized = true;
return CollectGraphicsInfoGL(gpu_info);
}
// TODO(zmo): the following code only works if running on top of ANGLE.
// Need to handle the case when running on top of real EGL/GLES2 drivers.
egl::Display* display = static_cast<egl::Display*>(
gfx::GLSurfaceEGL::GetHardwareDisplay());
if (!display) {
LOG(ERROR) << "gfx::BaseEGLContext::GetDisplay() failed";
return false;
}
IDirect3DDevice9* device = display->getDevice();
if (!device) {
LOG(ERROR) << "display->getDevice() failed";
return false;
}
base::win::ScopedComPtr<IDirect3D9> d3d;
if (FAILED(device->GetDirect3D(d3d.Receive()))) {
LOG(ERROR) << "device->GetDirect3D(&d3d) failed";
return false;
}
if (!CollectGraphicsInfoD3D(d3d, gpu_info))
return false;
// DirectX diagnostics are collected asynchronously because it takes a
// couple of seconds. Do not mark gpu_info as complete until that is done.
return true;
}
bool CollectPreliminaryGraphicsInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectPreliminaryGraphicsInfo");
DCHECK(gpu_info);
bool rt = true;
if (!CollectVideoCardInfo(gpu_info))
rt = false;
gpu_info->performance_stats = RetrieveGpuPerformanceStatsWithHistograms();
return rt;
}
bool CollectGraphicsInfoD3D(IDirect3D9* d3d, content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectGraphicsInfoD3D");
DCHECK(d3d);
DCHECK(gpu_info);
bool succeed = CollectVideoCardInfo(gpu_info);
// Get version information
D3DCAPS9 d3d_caps;
if (d3d->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
&d3d_caps) == D3D_OK) {
gpu_info->pixel_shader_version =
VersionNumberToString(d3d_caps.PixelShaderVersion);
gpu_info->vertex_shader_version =
VersionNumberToString(d3d_caps.VertexShaderVersion);
} else {
LOG(ERROR) << "d3d->GetDeviceCaps() failed";
succeed = false;
}
// Get can_lose_context
base::win::ScopedComPtr<IDirect3D9Ex> d3dex;
if (SUCCEEDED(d3dex.QueryFrom(d3d)))
gpu_info->can_lose_context = false;
else
gpu_info->can_lose_context = true;
return true;
}
bool CollectVideoCardInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectVideoCardInfo");
DCHECK(gpu_info);
// nvd3d9wrap.dll is loaded into all processes when Optimus is enabled.
HMODULE nvd3d9wrap = GetModuleHandleW(L"nvd3d9wrap.dll");
gpu_info->optimus = nvd3d9wrap != NULL;
// Taken from http://developer.nvidia.com/object/device_ids.html
DISPLAY_DEVICE dd;
dd.cb = sizeof(DISPLAY_DEVICE);
int i = 0;
std::wstring id;
for (int i = 0; EnumDisplayDevices(NULL, i, &dd, 0); ++i) {
if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
id = dd.DeviceID;
break;
}
}
if (id.length() > 20) {
int vendor_id = 0, device_id = 0;
std::wstring vendor_id_string = id.substr(8, 4);
std::wstring device_id_string = id.substr(17, 4);
base::HexStringToInt(WideToASCII(vendor_id_string), &vendor_id);
base::HexStringToInt(WideToASCII(device_id_string), &device_id);
gpu_info->gpu.vendor_id = vendor_id;
gpu_info->gpu.device_id = device_id;
// TODO(zmo): we only need to call CollectDriverInfoD3D() if we use ANGLE.
return CollectDriverInfoD3D(id, gpu_info);
}
return false;
}
bool CollectDriverInfoD3D(const std::wstring& device_id,
content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectDriverInfoD3D");
// create device info for the display device
HDEVINFO device_info = SetupDiGetClassDevsW(
NULL, device_id.c_str(), NULL,
DIGCF_PRESENT | DIGCF_PROFILE | DIGCF_ALLCLASSES);
if (device_info == INVALID_HANDLE_VALUE) {
LOG(ERROR) << "Creating device info failed";
return false;
}
DWORD index = 0;
bool found = false;
SP_DEVINFO_DATA device_info_data;
device_info_data.cbSize = sizeof(device_info_data);
while (SetupDiEnumDeviceInfo(device_info, index++, &device_info_data)) {
WCHAR value[255];
if (SetupDiGetDeviceRegistryPropertyW(device_info,
&device_info_data,
SPDRP_DRIVER,
NULL,
reinterpret_cast<PBYTE>(value),
sizeof(value),
NULL)) {
HKEY key;
std::wstring driver_key = L"System\\CurrentControlSet\\Control\\Class\\";
driver_key += value;
LONG result = RegOpenKeyExW(
HKEY_LOCAL_MACHINE, driver_key.c_str(), 0, KEY_QUERY_VALUE, &key);
if (result == ERROR_SUCCESS) {
DWORD dwcb_data = sizeof(value);
std::string driver_version;
result = RegQueryValueExW(
key, L"DriverVersion", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS)
driver_version = WideToASCII(std::wstring(value));
std::string driver_date;
dwcb_data = sizeof(value);
result = RegQueryValueExW(
key, L"DriverDate", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS)
driver_date = WideToASCII(std::wstring(value));
std::string driver_vendor;
dwcb_data = sizeof(value);
result = RegQueryValueExW(
key, L"ProviderName", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS) {
driver_vendor = WideToASCII(std::wstring(value));
if (driver_vendor == "Advanced Micro Devices, Inc." ||
driver_vendor == "ATI Technologies Inc.") {
// We are conservative and assume that in the absense of a clear
// signal the videocard is assumed to be switchable.
AMDVideoCardType amd_card_type = GetAMDVideocardType();
gpu_info->amd_switchable = (amd_card_type != STANDALONE);
}
}
gpu_info->driver_vendor = driver_vendor;
gpu_info->driver_version = driver_version;
gpu_info->driver_date = driver_date;
found = true;
RegCloseKey(key);
break;
}
}
}
SetupDiDestroyDeviceInfoList(device_info);
return found;
}
bool CollectDriverInfoGL(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectDriverInfoGL");
DCHECK(gpu_info);
std::string gl_version_string = gpu_info->gl_version_string;
// TODO(zmo): We assume the driver version is in the end of GL_VERSION
// string. Need to verify if it is true for majority drivers.
size_t pos = gl_version_string.find_last_not_of("0123456789.");
if (pos != std::string::npos && pos < gl_version_string.length() - 1) {
gpu_info->driver_version = gl_version_string.substr(pos + 1);
return true;
}
return false;
}
} // namespace gpu_info_collector
<commit_msg>Count all systems with an AMD driver and Intel GPU PCI ID as AMD switchable<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 "content/gpu/gpu_info_collector.h"
#include <windows.h>
#include <d3d9.h>
#include <setupapi.h>
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/scoped_native_library.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_comptr.h"
#include "third_party/libxml/chromium/libxml_utils.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_surface_egl.h"
// ANGLE seems to require that main.h be included before any other ANGLE header.
#include "libEGL/Display.h"
#include "libEGL/main.h"
namespace {
// The version number stores the major and minor version in the least 16 bits;
// for example, 2.5 is 0x00000205.
// Returned string is in the format of "major.minor".
std::string VersionNumberToString(uint32 version_number) {
int hi = (version_number >> 8) & 0xff;
int low = version_number & 0xff;
return base::IntToString(hi) + "." + base::IntToString(low);
}
float ReadXMLFloatValue(XmlReader* reader) {
std::string score_string;
if (!reader->ReadElementContent(&score_string))
return 0.0;
double score;
if (!base::StringToDouble(score_string, &score))
return 0.0;
return static_cast<float>(score);
}
content::GpuPerformanceStats RetrieveGpuPerformanceStats() {
TRACE_EVENT0("gpu", "RetrieveGpuPerformanceStats");
// If the user re-runs the assessment without restarting, the COM API
// returns WINSAT_ASSESSMENT_STATE_NOT_AVAILABLE. Because of that and
// http://crbug.com/124325, read the assessment result files directly.
content::GpuPerformanceStats stats;
// Get path to WinSAT results files.
wchar_t winsat_results_path[MAX_PATH];
DWORD size = ExpandEnvironmentStrings(
L"%WinDir%\\Performance\\WinSAT\\DataStore\\",
winsat_results_path, MAX_PATH);
if (size == 0 || size > MAX_PATH) {
LOG(ERROR) << "The path to the WinSAT results is too long: "
<< size << " chars.";
return stats;
}
// Find most recent formal assessment results.
file_util::FileEnumerator file_enumerator(
FilePath(winsat_results_path),
false, // not recursive
file_util::FileEnumerator::FILES,
FILE_PATH_LITERAL("* * Formal.Assessment (*).WinSAT.xml"));
FilePath current_results;
for (FilePath results = file_enumerator.Next(); !results.empty();
results = file_enumerator.Next()) {
// The filenames start with the date and time as yyyy-mm-dd hh.mm.ss.xxx,
// so the greatest file lexicographically is also the most recent file.
if (FilePath::CompareLessIgnoreCase(current_results.value(),
results.value()))
current_results = results;
}
std::string current_results_string = current_results.MaybeAsASCII();
if (current_results_string.empty()) {
LOG(ERROR) << "Can't retrieve a valid WinSAT assessment.";
return stats;
}
// Get relevant scores from results file. XML schema at:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa969210.aspx
XmlReader reader;
if (!reader.LoadFile(current_results_string)) {
LOG(ERROR) << "Could not open WinSAT results file.";
return stats;
}
// Descend into <WinSAT> root element.
if (!reader.SkipToElement() || !reader.Read()) {
LOG(ERROR) << "Could not read WinSAT results file.";
return stats;
}
// Search for <WinSPR> element containing the results.
do {
if (reader.NodeName() == "WinSPR")
break;
} while (reader.Next());
// Descend into <WinSPR> element.
if (!reader.Read()) {
LOG(ERROR) << "Could not find WinSPR element in results file.";
return stats;
}
// Read scores.
for (int depth = reader.Depth(); reader.Depth() == depth; reader.Next()) {
std::string node_name = reader.NodeName();
if (node_name == "SystemScore")
stats.overall = ReadXMLFloatValue(&reader);
else if (node_name == "GraphicsScore")
stats.graphics = ReadXMLFloatValue(&reader);
else if (node_name == "GamingScore")
stats.gaming = ReadXMLFloatValue(&reader);
}
if (stats.overall == 0.0)
LOG(ERROR) << "Could not read overall score from assessment results.";
if (stats.graphics == 0.0)
LOG(ERROR) << "Could not read graphics score from assessment results.";
if (stats.gaming == 0.0)
LOG(ERROR) << "Could not read gaming score from assessment results.";
return stats;
}
content::GpuPerformanceStats RetrieveGpuPerformanceStatsWithHistograms() {
base::TimeTicks start_time = base::TimeTicks::Now();
content::GpuPerformanceStats stats = RetrieveGpuPerformanceStats();
UMA_HISTOGRAM_TIMES("GPU.WinSAT.ReadResultsFileTime",
base::TimeTicks::Now() - start_time);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.OverallScore2",
stats.overall * 10, 10, 200, 50);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.GraphicsScore2",
stats.graphics * 10, 10, 200, 50);
UMA_HISTOGRAM_CUSTOM_COUNTS("GPU.WinSAT.GamingScore2",
stats.gaming * 10, 10, 200, 50);
UMA_HISTOGRAM_BOOLEAN(
"GPU.WinSAT.HasResults",
stats.overall != 0.0 && stats.graphics != 0.0 && stats.gaming != 0.0);
return stats;
}
} // namespace anonymous
namespace gpu_info_collector {
#if !defined(GOOGLE_CHROME_BUILD)
AMDVideoCardType GetAMDVideocardType() {
return UNKNOWN;
}
#else
// This function has a real implementation for official builds that can
// be found in src/third_party/amd.
AMDVideoCardType GetAMDVideocardType();
#endif
bool CollectGraphicsInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectGraphicsInfo");
DCHECK(gpu_info);
gpu_info->performance_stats = RetrieveGpuPerformanceStats();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseGL)) {
std::string requested_implementation_name =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);
if (requested_implementation_name == "swiftshader") {
gpu_info->software_rendering = true;
return false;
}
}
if (gfx::GetGLImplementation() != gfx::kGLImplementationEGLGLES2) {
gpu_info->finalized = true;
return CollectGraphicsInfoGL(gpu_info);
}
// TODO(zmo): the following code only works if running on top of ANGLE.
// Need to handle the case when running on top of real EGL/GLES2 drivers.
egl::Display* display = static_cast<egl::Display*>(
gfx::GLSurfaceEGL::GetHardwareDisplay());
if (!display) {
LOG(ERROR) << "gfx::BaseEGLContext::GetDisplay() failed";
return false;
}
IDirect3DDevice9* device = display->getDevice();
if (!device) {
LOG(ERROR) << "display->getDevice() failed";
return false;
}
base::win::ScopedComPtr<IDirect3D9> d3d;
if (FAILED(device->GetDirect3D(d3d.Receive()))) {
LOG(ERROR) << "device->GetDirect3D(&d3d) failed";
return false;
}
if (!CollectGraphicsInfoD3D(d3d, gpu_info))
return false;
// DirectX diagnostics are collected asynchronously because it takes a
// couple of seconds. Do not mark gpu_info as complete until that is done.
return true;
}
bool CollectPreliminaryGraphicsInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectPreliminaryGraphicsInfo");
DCHECK(gpu_info);
bool rt = true;
if (!CollectVideoCardInfo(gpu_info))
rt = false;
gpu_info->performance_stats = RetrieveGpuPerformanceStatsWithHistograms();
return rt;
}
bool CollectGraphicsInfoD3D(IDirect3D9* d3d, content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectGraphicsInfoD3D");
DCHECK(d3d);
DCHECK(gpu_info);
bool succeed = CollectVideoCardInfo(gpu_info);
// Get version information
D3DCAPS9 d3d_caps;
if (d3d->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
&d3d_caps) == D3D_OK) {
gpu_info->pixel_shader_version =
VersionNumberToString(d3d_caps.PixelShaderVersion);
gpu_info->vertex_shader_version =
VersionNumberToString(d3d_caps.VertexShaderVersion);
} else {
LOG(ERROR) << "d3d->GetDeviceCaps() failed";
succeed = false;
}
// Get can_lose_context
base::win::ScopedComPtr<IDirect3D9Ex> d3dex;
if (SUCCEEDED(d3dex.QueryFrom(d3d)))
gpu_info->can_lose_context = false;
else
gpu_info->can_lose_context = true;
return true;
}
bool CollectVideoCardInfo(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectVideoCardInfo");
DCHECK(gpu_info);
// nvd3d9wrap.dll is loaded into all processes when Optimus is enabled.
HMODULE nvd3d9wrap = GetModuleHandleW(L"nvd3d9wrap.dll");
gpu_info->optimus = nvd3d9wrap != NULL;
// Taken from http://developer.nvidia.com/object/device_ids.html
DISPLAY_DEVICE dd;
dd.cb = sizeof(DISPLAY_DEVICE);
int i = 0;
std::wstring id;
for (int i = 0; EnumDisplayDevices(NULL, i, &dd, 0); ++i) {
if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
id = dd.DeviceID;
break;
}
}
if (id.length() > 20) {
int vendor_id = 0, device_id = 0;
std::wstring vendor_id_string = id.substr(8, 4);
std::wstring device_id_string = id.substr(17, 4);
base::HexStringToInt(WideToASCII(vendor_id_string), &vendor_id);
base::HexStringToInt(WideToASCII(device_id_string), &device_id);
gpu_info->gpu.vendor_id = vendor_id;
gpu_info->gpu.device_id = device_id;
// TODO(zmo): we only need to call CollectDriverInfoD3D() if we use ANGLE.
return CollectDriverInfoD3D(id, gpu_info);
}
return false;
}
bool CollectDriverInfoD3D(const std::wstring& device_id,
content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectDriverInfoD3D");
// create device info for the display device
HDEVINFO device_info = SetupDiGetClassDevsW(
NULL, device_id.c_str(), NULL,
DIGCF_PRESENT | DIGCF_PROFILE | DIGCF_ALLCLASSES);
if (device_info == INVALID_HANDLE_VALUE) {
LOG(ERROR) << "Creating device info failed";
return false;
}
DWORD index = 0;
bool found = false;
SP_DEVINFO_DATA device_info_data;
device_info_data.cbSize = sizeof(device_info_data);
while (SetupDiEnumDeviceInfo(device_info, index++, &device_info_data)) {
WCHAR value[255];
if (SetupDiGetDeviceRegistryPropertyW(device_info,
&device_info_data,
SPDRP_DRIVER,
NULL,
reinterpret_cast<PBYTE>(value),
sizeof(value),
NULL)) {
HKEY key;
std::wstring driver_key = L"System\\CurrentControlSet\\Control\\Class\\";
driver_key += value;
LONG result = RegOpenKeyExW(
HKEY_LOCAL_MACHINE, driver_key.c_str(), 0, KEY_QUERY_VALUE, &key);
if (result == ERROR_SUCCESS) {
DWORD dwcb_data = sizeof(value);
std::string driver_version;
result = RegQueryValueExW(
key, L"DriverVersion", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS)
driver_version = WideToASCII(std::wstring(value));
std::string driver_date;
dwcb_data = sizeof(value);
result = RegQueryValueExW(
key, L"DriverDate", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS)
driver_date = WideToASCII(std::wstring(value));
std::string driver_vendor;
dwcb_data = sizeof(value);
result = RegQueryValueExW(
key, L"ProviderName", NULL, NULL,
reinterpret_cast<LPBYTE>(value), &dwcb_data);
if (result == ERROR_SUCCESS) {
driver_vendor = WideToASCII(std::wstring(value));
if (driver_vendor == "Advanced Micro Devices, Inc." ||
driver_vendor == "ATI Technologies Inc.") {
// We are conservative and assume that in the absence of a clear
// signal the videocard is assumed to be switchable. Additionally,
// some switchable systems with Intel GPUs aren't correctly
// detected, so always count them.
AMDVideoCardType amd_card_type = GetAMDVideocardType();
gpu_info->amd_switchable = (gpu_info->gpu.vendor_id == 0x8086) ||
(amd_card_type != STANDALONE);
}
}
gpu_info->driver_vendor = driver_vendor;
gpu_info->driver_version = driver_version;
gpu_info->driver_date = driver_date;
found = true;
RegCloseKey(key);
break;
}
}
}
SetupDiDestroyDeviceInfoList(device_info);
return found;
}
bool CollectDriverInfoGL(content::GPUInfo* gpu_info) {
TRACE_EVENT0("gpu", "CollectDriverInfoGL");
DCHECK(gpu_info);
std::string gl_version_string = gpu_info->gl_version_string;
// TODO(zmo): We assume the driver version is in the end of GL_VERSION
// string. Need to verify if it is true for majority drivers.
size_t pos = gl_version_string.find_last_not_of("0123456789.");
if (pos != std::string::npos && pos < gl_version_string.length() - 1) {
gpu_info->driver_version = gl_version_string.substr(pos + 1);
return true;
}
return false;
}
} // namespace gpu_info_collector
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string.h>
#include <cassert>
#include <vector>
#include "EGLWindow.h"
#include "OSWindow.h"
#ifdef _WIN32
#include "win32/Win32Timer.h"
#include "win32/Win32Window.h"
#else
#error unsupported OS.
#endif
EGLPlatformParameters::EGLPlatformParameters()
: renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer)
: renderer(renderer),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp)
: renderer(renderer),
majorVersion(majorVersion),
minorVersion(minorVersion),
deviceType(useWarp)
{
}
EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform)
: mSurface(EGL_NO_SURFACE),
mContext(EGL_NO_CONTEXT),
mDisplay(EGL_NO_DISPLAY),
mClientVersion(glesMajorVersion),
mPlatform(platform),
mWidth(width),
mHeight(height),
mRedBits(-1),
mGreenBits(-1),
mBlueBits(-1),
mAlphaBits(-1),
mDepthBits(-1),
mStencilBits(-1),
mMultisample(false),
mSwapInterval(-1)
{
}
EGLWindow::~EGLWindow()
{
destroyGL();
}
void EGLWindow::swap()
{
eglSwapBuffers(mDisplay, mSurface);
}
EGLConfig EGLWindow::getConfig() const
{
return mConfig;
}
EGLDisplay EGLWindow::getDisplay() const
{
return mDisplay;
}
EGLSurface EGLWindow::getSurface() const
{
return mSurface;
}
EGLContext EGLWindow::getContext() const
{
return mContext;
}
bool EGLWindow::initializeGL(OSWindow *osWindow)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
return false;
}
const EGLint displayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, mPlatform.renderer,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, mPlatform.majorVersion,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, mPlatform.minorVersion,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, mPlatform.deviceType,
EGL_NONE,
};
mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes);
if (mDisplay == EGL_NO_DISPLAY)
{
destroyGL();
return false;
}
EGLint majorVersion, minorVersion;
if (!eglInitialize(mDisplay, &majorVersion, &minorVersion))
{
destroyGL();
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE,
EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE,
EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE,
EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0,
EGL_NONE
};
EGLint configCount;
if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1))
{
destroyGL();
return false;
}
eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits);
std::vector<EGLint> surfaceAttributes;
if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr)
{
surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV);
surfaceAttributes.push_back(EGL_TRUE);
}
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
ASSERT(mSurface != EGL_NO_SURFACE);
EGLint contextAttibutes[] =
{
EGL_CONTEXT_CLIENT_VERSION, mClientVersion,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
if (mSwapInterval != -1)
{
eglSwapInterval(mDisplay, mSwapInterval);
}
return true;
}
void EGLWindow::destroyGL()
{
if (mSurface != EGL_NO_SURFACE)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
if (mContext != EGL_NO_CONTEXT)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
}
}
bool EGLWindow::isGLInitialized() const
{
return mSurface != EGL_NO_SURFACE &&
mContext != EGL_NO_CONTEXT &&
mDisplay != EGL_NO_DISPLAY;
}<commit_msg>Add missing trailing newline before EGLWindow.cpp EOF<commit_after>//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string.h>
#include <cassert>
#include <vector>
#include "EGLWindow.h"
#include "OSWindow.h"
#ifdef _WIN32
#include "win32/Win32Timer.h"
#include "win32/Win32Window.h"
#else
#error unsupported OS.
#endif
EGLPlatformParameters::EGLPlatformParameters()
: renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer)
: renderer(renderer),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp)
: renderer(renderer),
majorVersion(majorVersion),
minorVersion(minorVersion),
deviceType(useWarp)
{
}
EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform)
: mSurface(EGL_NO_SURFACE),
mContext(EGL_NO_CONTEXT),
mDisplay(EGL_NO_DISPLAY),
mClientVersion(glesMajorVersion),
mPlatform(platform),
mWidth(width),
mHeight(height),
mRedBits(-1),
mGreenBits(-1),
mBlueBits(-1),
mAlphaBits(-1),
mDepthBits(-1),
mStencilBits(-1),
mMultisample(false),
mSwapInterval(-1)
{
}
EGLWindow::~EGLWindow()
{
destroyGL();
}
void EGLWindow::swap()
{
eglSwapBuffers(mDisplay, mSurface);
}
EGLConfig EGLWindow::getConfig() const
{
return mConfig;
}
EGLDisplay EGLWindow::getDisplay() const
{
return mDisplay;
}
EGLSurface EGLWindow::getSurface() const
{
return mSurface;
}
EGLContext EGLWindow::getContext() const
{
return mContext;
}
bool EGLWindow::initializeGL(OSWindow *osWindow)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
return false;
}
const EGLint displayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, mPlatform.renderer,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, mPlatform.majorVersion,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, mPlatform.minorVersion,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, mPlatform.deviceType,
EGL_NONE,
};
mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes);
if (mDisplay == EGL_NO_DISPLAY)
{
destroyGL();
return false;
}
EGLint majorVersion, minorVersion;
if (!eglInitialize(mDisplay, &majorVersion, &minorVersion))
{
destroyGL();
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE,
EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE,
EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE,
EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0,
EGL_NONE
};
EGLint configCount;
if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1))
{
destroyGL();
return false;
}
eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits);
std::vector<EGLint> surfaceAttributes;
if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr)
{
surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV);
surfaceAttributes.push_back(EGL_TRUE);
}
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
ASSERT(mSurface != EGL_NO_SURFACE);
EGLint contextAttibutes[] =
{
EGL_CONTEXT_CLIENT_VERSION, mClientVersion,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
if (mSwapInterval != -1)
{
eglSwapInterval(mDisplay, mSwapInterval);
}
return true;
}
void EGLWindow::destroyGL()
{
if (mSurface != EGL_NO_SURFACE)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
if (mContext != EGL_NO_CONTEXT)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
}
}
bool EGLWindow::isGLInitialized() const
{
return mSurface != EGL_NO_SURFACE &&
mContext != EGL_NO_CONTEXT &&
mDisplay != EGL_NO_DISPLAY;
}
<|endoftext|> |
<commit_before><commit_msg>coverity#704089 Unchecked return value<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <iterator>
#include <algorithm>
#include <cmath>
namespace cujak {
namespace util {
/** square of L2-norm */
template <class InputIterator>
typename std::iterator_traits<InputIterator>::value_type
square_sum(InputIterator begin, InputIterator end) {
typedef typename std::iterator_traits<InputIterator>::value_type T;
return std::accumulate(begin, end, T(0), [=](T x, T y) { return x + y * y; });
}
/** L2-norm */
template <class InputIterator>
double l2(InputIterator begin, InputIterator end) {
return std::sqrt(square_sum(begin, end));
}
template <class InputIterator>
typename std::iterator_traits<InputIterator>::value_type
l1(InputIterator begin, InputIterator end) {
typedef typename std::iterator_traits<InputIterator>::value_type T;
return std::accumulate(begin, end, T(0), [=](T x, T y) { return x + std::abs(y); });
}
} // namespace util
} // namespace cujak
<commit_msg>Make algorithms inline<commit_after>#pragma once
#include <iterator>
#include <algorithm>
#include <cmath>
namespace cujak {
namespace util {
/** square of L2-norm */
template <class InputIterator>
inline typename std::iterator_traits<InputIterator>::value_type
square_sum(InputIterator begin, InputIterator end) {
typedef typename std::iterator_traits<InputIterator>::value_type T;
return std::accumulate(begin, end, T(0), [=](T x, T y) { return x + y * y; });
}
/** L2-norm */
template <class InputIterator>
inline double l2(InputIterator begin, InputIterator end) {
return std::sqrt(square_sum(begin, end));
}
template <class InputIterator>
inline typename std::iterator_traits<InputIterator>::value_type
l1(InputIterator begin, InputIterator end) {
typedef typename std::iterator_traits<InputIterator>::value_type T;
return std::accumulate(begin, end, T(0), [=](T x, T y) { return x + std::abs(y); });
}
} // namespace util
} // namespace cujak
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dndevdis.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obr $ $Date: 2001-02-20 11:17:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <dndevdis.hxx>
#include <dndlcon.hxx>
#include <vos/mutex.hxx>
#include <svapp.hxx>
using namespace ::osl;
using namespace ::vos;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
//==================================================================================================
// DNDEventDispatcher::DNDEventDispatcher
//==================================================================================================
DNDEventDispatcher::DNDEventDispatcher( Window * pTopWindow ):
m_pTopWindow( pTopWindow ),
m_pCurrentWindow( NULL )
{
}
//==================================================================================================
// DNDEventDispatcher::~DNDEventDispatcher
//==================================================================================================
DNDEventDispatcher::~DNDEventDispatcher()
{
}
//==================================================================================================
// DNDEventDispatcher::drop
//==================================================================================================
void SAL_CALL DNDEventDispatcher::drop( const DropTargetDropEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
aSolarGuard.clear();
// handle the case that drop is in an other vcl window than the last dragOver
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
fireDragEnterEvent( pChildWindow, static_cast < XDropTargetDragContext * > (this),
dtde.DropAction, location, dtde.SourceActions, m_aDataFlavorList );
}
sal_Int32 nListeners = 0;
// send drop event to the child window
nListeners = fireDropEvent( pChildWindow, dtde.Context, dtde.DropAction,
location, dtde.SourceActions, dtde.Transferable );
// reject drop if no listeners found
if( nListeners == 0 ) {
OSL_TRACE( "rejecting drop due to missing listeners." );
dtde.Context->rejectDrop();
}
// this is a drop -> no further drag overs
m_pCurrentWindow = NULL;
m_aDataFlavorList.realloc( 0 );
}
//==================================================================================================
// DNDEventDispatcher::dragEnter
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragEnter( const DropTargetDragEnterEvent& dtdee )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtdee.LocationX, dtdee.LocationY );
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
aSolarGuard.clear();
// assume pointer write operation to be atomic
m_pCurrentWindow = pChildWindow;
m_aDataFlavorList = dtdee.SupportedDataFlavors;
// fire dragEnter on listeners of current window
sal_Int32 nListeners = fireDragEnterEvent( pChildWindow, dtdee.Context, dtdee.DropAction, location,
dtdee.SourceActions, dtdee.SupportedDataFlavors );
// reject drag if no listener found
if( nListeners == 0 ) {
OSL_TRACE( "rejecting drag enter due to missing listeners." );
dtdee.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::dragExit
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragExit( const DropTargetEvent& dte )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
fireDragExitEvent( m_pCurrentWindow );
// reset member values
m_pCurrentWindow = NULL;
m_aDataFlavorList.realloc( 0 );
}
//==================================================================================================
// DNDEventDispatcher::dragOver
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragOver( const DropTargetDragEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
sal_Int32 nListeners;
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
aSolarGuard.clear();
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
// remember new window
m_pCurrentWindow = pChildWindow;
// fire dragEnter on listeners of current window
nListeners = fireDragEnterEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions, m_aDataFlavorList );
}
else
{
// fire dragOver on listeners of current window
nListeners = fireDragOverEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions );
}
// reject drag if no listener found
if( nListeners == 0 )
{
OSL_TRACE( "rejecting drag over due to missing listeners." );
dtde.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::dropActionChanged
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dropActionChanged( const DropTargetDragEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
sal_Int32 nListeners;
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
aSolarGuard.clear();
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
// remember new window
m_pCurrentWindow = pChildWindow;
// fire dragEnter on listeners of current window
nListeners = fireDragEnterEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions, m_aDataFlavorList );
}
else
{
// fire dropActionChanged on listeners of current window
nListeners = fireDropActionChangedEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions );
}
// reject drag if no listener found
if( nListeners == 0 )
{
OSL_TRACE( "rejecting dropActionChanged due to missing listeners." );
dtde.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::disposing
//==================================================================================================
void SAL_CALL DNDEventDispatcher::disposing( const EventObject& eo )
throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::acceptDrag
//==================================================================================================
void SAL_CALL DNDEventDispatcher::acceptDrag( sal_Int8 dropAction ) throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::rejectDrag
//==================================================================================================
void SAL_CALL DNDEventDispatcher::rejectDrag() throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::fireDragEnterEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragEnterEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions, const Sequence< DataFlavor >& aFlavorList
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragEnterEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions, aFlavorList );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDragOverEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragOverEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragOverEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDragExitEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragExitEvent( Window *pWindow ) throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
aGuard.clear();
if( xDropTarget.is() )
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragExitEvent();
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDropActionChangedEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDropActionChangedEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDropActionChangedEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDropEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDropEvent( Window *pWindow,
const Reference< XDropTargetDropContext >& xContext, const sal_Int8 nDropAction, const Point& rLocation,
const sal_Int8 nSourceActions, const Reference< XTransferable >& xTransferable
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDropEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions, xTransferable );
}
}
return n;
}
<commit_msg>fix: #88014# find toplevel window improved<commit_after>/*************************************************************************
*
* $RCSfile: dndevdis.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: pb $ $Date: 2001-06-15 09:25:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <dndevdis.hxx>
#include <dndlcon.hxx>
#include <vos/mutex.hxx>
#include <svapp.hxx>
using namespace ::osl;
using namespace ::vos;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
//==================================================================================================
// DNDEventDispatcher::DNDEventDispatcher
//==================================================================================================
DNDEventDispatcher::DNDEventDispatcher( Window * pTopWindow ):
m_pTopWindow( pTopWindow ),
m_pCurrentWindow( NULL )
{
}
//==================================================================================================
// DNDEventDispatcher::~DNDEventDispatcher
//==================================================================================================
DNDEventDispatcher::~DNDEventDispatcher()
{
}
//==================================================================================================
// DNDEventDispatcher::drop
//==================================================================================================
void SAL_CALL DNDEventDispatcher::drop( const DropTargetDropEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
if( NULL == pChildWindow )
pChildWindow = m_pTopWindow;
while( pChildWindow->ImplGetClientWindow() )
pChildWindow = pChildWindow->ImplGetClientWindow();
aSolarGuard.clear();
// handle the case that drop is in an other vcl window than the last dragOver
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
fireDragEnterEvent( pChildWindow, static_cast < XDropTargetDragContext * > (this),
dtde.DropAction, location, dtde.SourceActions, m_aDataFlavorList );
}
sal_Int32 nListeners = 0;
// send drop event to the child window
nListeners = fireDropEvent( pChildWindow, dtde.Context, dtde.DropAction,
location, dtde.SourceActions, dtde.Transferable );
// reject drop if no listeners found
if( nListeners == 0 ) {
OSL_TRACE( "rejecting drop due to missing listeners." );
dtde.Context->rejectDrop();
}
// this is a drop -> no further drag overs
m_pCurrentWindow = NULL;
m_aDataFlavorList.realloc( 0 );
}
//==================================================================================================
// DNDEventDispatcher::dragEnter
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragEnter( const DropTargetDragEnterEvent& dtdee )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtdee.LocationX, dtdee.LocationY );
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
if( NULL == pChildWindow )
pChildWindow = m_pTopWindow;
while( pChildWindow->ImplGetClientWindow() )
pChildWindow = pChildWindow->ImplGetClientWindow();
aSolarGuard.clear();
// assume pointer write operation to be atomic
m_pCurrentWindow = pChildWindow;
m_aDataFlavorList = dtdee.SupportedDataFlavors;
// fire dragEnter on listeners of current window
sal_Int32 nListeners = fireDragEnterEvent( pChildWindow, dtdee.Context, dtdee.DropAction, location,
dtdee.SourceActions, dtdee.SupportedDataFlavors );
// reject drag if no listener found
if( nListeners == 0 ) {
OSL_TRACE( "rejecting drag enter due to missing listeners." );
dtdee.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::dragExit
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragExit( const DropTargetEvent& dte )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
fireDragExitEvent( m_pCurrentWindow );
// reset member values
m_pCurrentWindow = NULL;
m_aDataFlavorList.realloc( 0 );
}
//==================================================================================================
// DNDEventDispatcher::dragOver
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dragOver( const DropTargetDragEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
sal_Int32 nListeners;
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
if( NULL == pChildWindow )
pChildWindow = m_pTopWindow;
while( pChildWindow->ImplGetClientWindow() )
pChildWindow = pChildWindow->ImplGetClientWindow();
aSolarGuard.clear();
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
// remember new window
m_pCurrentWindow = pChildWindow;
// fire dragEnter on listeners of current window
nListeners = fireDragEnterEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions, m_aDataFlavorList );
}
else
{
// fire dragOver on listeners of current window
nListeners = fireDragOverEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions );
}
// reject drag if no listener found
if( nListeners == 0 )
{
OSL_TRACE( "rejecting drag over due to missing listeners." );
dtde.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::dropActionChanged
//==================================================================================================
void SAL_CALL DNDEventDispatcher::dropActionChanged( const DropTargetDragEvent& dtde )
throw(RuntimeException)
{
MutexGuard aImplGuard( m_aMutex );
Point location( dtde.LocationX, dtde.LocationY );
sal_Int32 nListeners;
// find the window that is toplevel for this coordinates
OClearableGuard aSolarGuard( Application::GetSolarMutex() );
Window * pChildWindow = m_pTopWindow->ImplFindWindow( location );
if( NULL == pChildWindow )
pChildWindow = m_pTopWindow;
while( pChildWindow->ImplGetClientWindow() )
pChildWindow = pChildWindow->ImplGetClientWindow();
aSolarGuard.clear();
if( pChildWindow != m_pCurrentWindow )
{
// fire dragExit on listeners of previous window
fireDragExitEvent( m_pCurrentWindow );
// remember new window
m_pCurrentWindow = pChildWindow;
// fire dragEnter on listeners of current window
nListeners = fireDragEnterEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions, m_aDataFlavorList );
}
else
{
// fire dropActionChanged on listeners of current window
nListeners = fireDropActionChangedEvent( pChildWindow, dtde.Context, dtde.DropAction, location,
dtde.SourceActions );
}
// reject drag if no listener found
if( nListeners == 0 )
{
OSL_TRACE( "rejecting dropActionChanged due to missing listeners." );
dtde.Context->rejectDrag();
}
}
//==================================================================================================
// DNDEventDispatcher::disposing
//==================================================================================================
void SAL_CALL DNDEventDispatcher::disposing( const EventObject& eo )
throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::acceptDrag
//==================================================================================================
void SAL_CALL DNDEventDispatcher::acceptDrag( sal_Int8 dropAction ) throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::rejectDrag
//==================================================================================================
void SAL_CALL DNDEventDispatcher::rejectDrag() throw(RuntimeException)
{
}
//==================================================================================================
// DNDEventDispatcher::fireDragEnterEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragEnterEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions, const Sequence< DataFlavor >& aFlavorList
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragEnterEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions, aFlavorList );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDragOverEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragOverEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragOverEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDragExitEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDragExitEvent( Window *pWindow ) throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
aGuard.clear();
if( xDropTarget.is() )
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDragExitEvent();
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDropActionChangedEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDropActionChangedEvent( Window *pWindow,
const Reference< XDropTargetDragContext >& xContext, const sal_Int8 nDropAction,
const Point& rLocation, const sal_Int8 nSourceActions
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDropActionChangedEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions );
}
}
return n;
}
//==================================================================================================
// DNDEventDispatcher::fireDropEvent
//==================================================================================================
sal_Int32 DNDEventDispatcher::fireDropEvent( Window *pWindow,
const Reference< XDropTargetDropContext >& xContext, const sal_Int8 nDropAction, const Point& rLocation,
const sal_Int8 nSourceActions, const Reference< XTransferable >& xTransferable
)
throw(RuntimeException)
{
sal_Int32 n = 0;
if( pWindow )
{
OClearableGuard aGuard( Application::GetSolarMutex() );
// query DropTarget from window
Reference< XDropTarget > xDropTarget = pWindow->GetDropTarget();
if( xDropTarget.is() )
{
// retrieve relative mouse position
Point relLoc = pWindow->ImplFrameToOutput( rLocation );
aGuard.clear();
n = static_cast < DNDListenerContainer * > ( xDropTarget.get() )->fireDropEvent(
xContext, nDropAction, relLoc.X(), relLoc.Y(), nSourceActions, xTransferable );
}
}
return n;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/circular_buffer.hpp>
#include "latency.hh"
#include <cmath>
#include "core/timer.hh"
#include <iostream>
namespace utils {
/**
* An exponentially-weighted moving average.
*/
class moving_average {
double _alpha = 0;
bool _initialized = false;
latency_counter::duration _tick_interval;
uint64_t _count = 0;
double _rate = 0;
public:
moving_average(latency_counter::duration interval, latency_counter::duration tick_interval) :
_tick_interval(tick_interval) {
_alpha = 1 - std::exp(-std::chrono::duration_cast<std::chrono::nanoseconds>(interval).count()/
static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(tick_interval).count()));
}
void add(uint64_t val = 1) {
_count += val;
}
void update() {
double instant_rate = _count / static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(_tick_interval).count());
if (_initialized) {
_rate += (_alpha * (instant_rate - _rate));
} else {
_rate = instant_rate;
_initialized = true;
}
_count = 0;
}
bool is_initilized() const {
return _initialized;
}
double rate() const {
if (is_initilized()) {
return _rate;
}
return 0;
}
};
class ihistogram {
public:
// count holds all the events
int64_t count;
// total holds only the events we sample
int64_t total;
int64_t min;
int64_t max;
int64_t sum;
int64_t started;
double mean;
double variance;
int64_t sample_mask;
boost::circular_buffer<int64_t> sample;
ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80)
: count(0), total(0), min(0), max(0), sum(0), started(0), mean(0), variance(0),
sample_mask(_sample_mask), sample(
size) {
}
void mark(int64_t value) {
if (total == 0 || value < min) {
min = value;
}
if (total == 0 || value > max) {
max = value;
}
if (total == 0) {
mean = value;
variance = 0;
} else {
double old_m = mean;
double old_s = variance;
mean = ((double)(sum + value)) / (total + 1);
variance = old_s + ((value - old_m) * (value - mean));
}
sum += value;
total++;
count++;
sample.push_back(value);
}
void mark(latency_counter& lc) {
if (lc.is_start()) {
mark(lc.stop().latency_in_nano());
} else {
count++;
}
}
/**
* Return true if the current event should be sample.
* In the typical case, there is no need to use this method
* Call set_latency, that would start a latency object if needed.
*/
bool should_sample() const {
return total == 0 || (started & sample_mask);
}
/**
* Set the latency according to the sample rate.
*/
ihistogram& set_latency(latency_counter& lc) {
if (should_sample()) {
lc.start();
}
started++;
return *this;
}
/**
* Allow to use the histogram as a counter
* Increment the total number of events without
* sampling the value.
*/
ihistogram& inc() {
count++;
return *this;
}
int64_t pending() const {
return started - count;
}
inline double pow2(double a) {
return a * a;
}
ihistogram& operator +=(const ihistogram& o) {
if (count == 0) {
*this = o;
} else if (o.count > 0) {
if (min > o.min) {
min = o.min;
}
if (max < o.max) {
max = o.max;
}
double ncount = count + o.count;
sum += o.sum;
double a = count / ncount;
double b = o.count / ncount;
double m = a * mean + b * o.mean;
variance = (variance + pow2(m - mean)) * a
+ (o.variance + pow2(o.mean - mean)) * b;
mean = m;
count += o.count;
total += o.total;
for (auto i : o.sample) {
sample.push_back(i);
}
}
return *this;
}
friend ihistogram operator +(ihistogram a, const ihistogram& b);
};
inline ihistogram operator +(ihistogram a, const ihistogram& b) {
a += b;
return a;
}
struct rate_moving_average {
uint64_t count = 0;
double rates[3] = {0};
double mean_rate = 0;
rate_moving_average& operator +=(const rate_moving_average& o) {
count += o.count;
mean_rate += o.mean_rate;
for (int i=0; i<3; i++) {
rates[i] += o.rates[i];
}
return *this;
}
friend rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b);
};
inline rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b) {
a += b;
return a;
}
class timed_rate_moving_average {
static constexpr latency_counter::duration tick_interval() {
return std::chrono::seconds(10);
}
moving_average rates[3] = {{tick_interval(), std::chrono::minutes(1)}, {tick_interval(), std::chrono::minutes(5)}, {tick_interval(), std::chrono::minutes(15)}};
latency_counter::time_point start_time;
timer<> _timer;
public:
// _count is public so the collectd will be able to use it.
// for all other cases use the count() method
uint64_t _count = 0;
timed_rate_moving_average() : start_time(latency_counter::now()), _timer([this] {
update();
}) {
_timer.arm_periodic(tick_interval());
}
void mark(uint64_t n = 1) {
_count += n;
for (int i = 0; i < 3; i++) {
rates[i].add(n);
}
}
rate_moving_average rate() const {
rate_moving_average res;
if (_count > 0) {
double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(latency_counter::now() - start_time).count();
res.mean_rate = (_count / elapsed);
}
res.count = _count;
for (int i = 0; i < 3; i++) {
res.rates[i] = rates[i].rate();
}
return res;
}
void update() {
for (int i = 0; i < 3; i++) {
rates[i].update();
}
}
uint64_t count() const {
return _count;
}
};
struct rate_moving_average_and_histogram {
ihistogram hist;
rate_moving_average rate;
rate_moving_average_and_histogram& operator +=(const rate_moving_average_and_histogram& o) {
hist += o.hist;
rate += o.rate;
return *this;
}
friend rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b);
};
inline rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b) {
a += b;
return a;
}
/**
* A timer metric which aggregates timing durations and provides duration statistics, plus
* throughput statistics via meter
*/
class timed_rate_moving_average_and_histogram {
public:
ihistogram hist;
timed_rate_moving_average met;
timed_rate_moving_average_and_histogram() = default;
timed_rate_moving_average_and_histogram(timed_rate_moving_average_and_histogram&&) = default;
timed_rate_moving_average_and_histogram(const timed_rate_moving_average_and_histogram&) = default;
timed_rate_moving_average_and_histogram(size_t size, int64_t _sample_mask = 0x80) : hist(size, _sample_mask) {}
timed_rate_moving_average_and_histogram& operator=(const timed_rate_moving_average_and_histogram&) = default;
void mark(int duration) {
if (duration >= 0) {
hist.mark(duration);
met.mark();
}
}
void mark(latency_counter& lc) {
hist.mark(lc);
met.mark();
}
void set_latency(latency_counter& lc) {
hist.set_latency(lc);
}
rate_moving_average_and_histogram rate() const {
rate_moving_average_and_histogram res;
res.hist = hist;
res.rate = met.rate();
return res;
}
};
}
<commit_msg>histogram: Add an estimated sum method<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/circular_buffer.hpp>
#include "latency.hh"
#include <cmath>
#include "core/timer.hh"
#include <iostream>
namespace utils {
/**
* An exponentially-weighted moving average.
*/
class moving_average {
double _alpha = 0;
bool _initialized = false;
latency_counter::duration _tick_interval;
uint64_t _count = 0;
double _rate = 0;
public:
moving_average(latency_counter::duration interval, latency_counter::duration tick_interval) :
_tick_interval(tick_interval) {
_alpha = 1 - std::exp(-std::chrono::duration_cast<std::chrono::nanoseconds>(interval).count()/
static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(tick_interval).count()));
}
void add(uint64_t val = 1) {
_count += val;
}
void update() {
double instant_rate = _count / static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(_tick_interval).count());
if (_initialized) {
_rate += (_alpha * (instant_rate - _rate));
} else {
_rate = instant_rate;
_initialized = true;
}
_count = 0;
}
bool is_initilized() const {
return _initialized;
}
double rate() const {
if (is_initilized()) {
return _rate;
}
return 0;
}
};
class ihistogram {
public:
// count holds all the events
int64_t count;
// total holds only the events we sample
int64_t total;
int64_t min;
int64_t max;
int64_t sum;
int64_t started;
double mean;
double variance;
int64_t sample_mask;
boost::circular_buffer<int64_t> sample;
ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80)
: count(0), total(0), min(0), max(0), sum(0), started(0), mean(0), variance(0),
sample_mask(_sample_mask), sample(
size) {
}
void mark(int64_t value) {
if (total == 0 || value < min) {
min = value;
}
if (total == 0 || value > max) {
max = value;
}
if (total == 0) {
mean = value;
variance = 0;
} else {
double old_m = mean;
double old_s = variance;
mean = ((double)(sum + value)) / (total + 1);
variance = old_s + ((value - old_m) * (value - mean));
}
sum += value;
total++;
count++;
sample.push_back(value);
}
void mark(latency_counter& lc) {
if (lc.is_start()) {
mark(lc.stop().latency_in_nano());
} else {
count++;
}
}
/**
* Return true if the current event should be sample.
* In the typical case, there is no need to use this method
* Call set_latency, that would start a latency object if needed.
*/
bool should_sample() const {
return total == 0 || (started & sample_mask);
}
/**
* Set the latency according to the sample rate.
*/
ihistogram& set_latency(latency_counter& lc) {
if (should_sample()) {
lc.start();
}
started++;
return *this;
}
/**
* Allow to use the histogram as a counter
* Increment the total number of events without
* sampling the value.
*/
ihistogram& inc() {
count++;
return *this;
}
int64_t pending() const {
return started - count;
}
inline double pow2(double a) {
return a * a;
}
ihistogram& operator +=(const ihistogram& o) {
if (count == 0) {
*this = o;
} else if (o.count > 0) {
if (min > o.min) {
min = o.min;
}
if (max < o.max) {
max = o.max;
}
double ncount = count + o.count;
sum += o.sum;
double a = count / ncount;
double b = o.count / ncount;
double m = a * mean + b * o.mean;
variance = (variance + pow2(m - mean)) * a
+ (o.variance + pow2(o.mean - mean)) * b;
mean = m;
count += o.count;
total += o.total;
for (auto i : o.sample) {
sample.push_back(i);
}
}
return *this;
}
int64_t estimated_sum() const {
return mean * count;
}
friend ihistogram operator +(ihistogram a, const ihistogram& b);
};
inline ihistogram operator +(ihistogram a, const ihistogram& b) {
a += b;
return a;
}
struct rate_moving_average {
uint64_t count = 0;
double rates[3] = {0};
double mean_rate = 0;
rate_moving_average& operator +=(const rate_moving_average& o) {
count += o.count;
mean_rate += o.mean_rate;
for (int i=0; i<3; i++) {
rates[i] += o.rates[i];
}
return *this;
}
friend rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b);
};
inline rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b) {
a += b;
return a;
}
class timed_rate_moving_average {
static constexpr latency_counter::duration tick_interval() {
return std::chrono::seconds(10);
}
moving_average rates[3] = {{tick_interval(), std::chrono::minutes(1)}, {tick_interval(), std::chrono::minutes(5)}, {tick_interval(), std::chrono::minutes(15)}};
latency_counter::time_point start_time;
timer<> _timer;
public:
// _count is public so the collectd will be able to use it.
// for all other cases use the count() method
uint64_t _count = 0;
timed_rate_moving_average() : start_time(latency_counter::now()), _timer([this] {
update();
}) {
_timer.arm_periodic(tick_interval());
}
void mark(uint64_t n = 1) {
_count += n;
for (int i = 0; i < 3; i++) {
rates[i].add(n);
}
}
rate_moving_average rate() const {
rate_moving_average res;
if (_count > 0) {
double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(latency_counter::now() - start_time).count();
res.mean_rate = (_count / elapsed);
}
res.count = _count;
for (int i = 0; i < 3; i++) {
res.rates[i] = rates[i].rate();
}
return res;
}
void update() {
for (int i = 0; i < 3; i++) {
rates[i].update();
}
}
uint64_t count() const {
return _count;
}
};
struct rate_moving_average_and_histogram {
ihistogram hist;
rate_moving_average rate;
rate_moving_average_and_histogram& operator +=(const rate_moving_average_and_histogram& o) {
hist += o.hist;
rate += o.rate;
return *this;
}
friend rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b);
};
inline rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b) {
a += b;
return a;
}
/**
* A timer metric which aggregates timing durations and provides duration statistics, plus
* throughput statistics via meter
*/
class timed_rate_moving_average_and_histogram {
public:
ihistogram hist;
timed_rate_moving_average met;
timed_rate_moving_average_and_histogram() = default;
timed_rate_moving_average_and_histogram(timed_rate_moving_average_and_histogram&&) = default;
timed_rate_moving_average_and_histogram(const timed_rate_moving_average_and_histogram&) = default;
timed_rate_moving_average_and_histogram(size_t size, int64_t _sample_mask = 0x80) : hist(size, _sample_mask) {}
timed_rate_moving_average_and_histogram& operator=(const timed_rate_moving_average_and_histogram&) = default;
void mark(int duration) {
if (duration >= 0) {
hist.mark(duration);
met.mark();
}
}
void mark(latency_counter& lc) {
hist.mark(lc);
met.mark();
}
void set_latency(latency_counter& lc) {
hist.set_latency(lc);
}
rate_moving_average_and_histogram rate() const {
rate_moving_average_and_histogram res;
res.hist = hist;
res.rate = met.rate();
return res;
}
};
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "ngsi10/QueryContextResponse.h"
#include "apiTypesV2/Entities.h"
/* ****************************************************************************
*
* Entities::Entities -
*/
Entities::Entities()
{
errorCode.fill(SccOk);
}
/* ****************************************************************************
*
* Entities::~Entities -
*/
Entities::~Entities()
{
release();
}
/* ****************************************************************************
*
* Entities::render -
*
* If no error reported in errorCode, render the vector of entities.
* Otherwise, render the errorCode.
*/
std::string Entities::render(ConnectionInfo* ciP, RequestType requestType)
{
if ((errorCode.code == SccOk) || (errorCode.code == SccNone))
{
return vec.render(ciP, requestType, false);
}
return errorCode.toJson(true);
}
/* ****************************************************************************
*
* Entities::check -
*
* NOTE
* The 'check' method is normally only used to check that incoming payload is correct.
* For now (at least), the Entities type is only used as outgoing payload ...
*/
std::string Entities::check(ConnectionInfo* ciP, RequestType requestType)
{
return vec.check(ciP, requestType);
}
/* ****************************************************************************
*
* Entities::present -
*/
void Entities::present(const std::string& indent)
{
LM_F(("%s%d Entities:", indent.c_str(), vec.size()));
vec.present(indent + " ");
}
/* ****************************************************************************
*
* Entities::release -
*/
void Entities::release(void)
{
vec.release();
}
/* ****************************************************************************
*
* Entities::fill -
*/
void Entities::fill(QueryContextResponse* qcrsP)
{
if (qcrsP->errorCode.code == SccContextElementNotFound)
{
//
// If no entities are found, we respond with a 200 OK
// and an empty vector of entities ( [] )
//
errorCode.fill(SccOk);
return;
}
else if (qcrsP->errorCode.code != SccOk)
{
//
// If any other error - use the error for the response
//
errorCode.fill(qcrsP->errorCode);
return;
}
for (unsigned int ix = 0; ix < qcrsP->contextElementResponseVector.size(); ++ix)
{
ContextElement* ceP = &qcrsP->contextElementResponseVector[ix]->contextElement;
Entity* eP = new Entity();
eP->id = ceP->entityId.id;
eP->type = ceP->entityId.type;
eP->isPattern = ceP->entityId.isPattern;
eP->attributeVector.fill(&ceP->contextAttributeVector);
vec.push_back(eP);
}
}
<commit_msg>Better comment in the header for Entities::fill<commit_after>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "ngsi10/QueryContextResponse.h"
#include "apiTypesV2/Entities.h"
/* ****************************************************************************
*
* Entities::Entities -
*/
Entities::Entities()
{
errorCode.fill(SccOk);
}
/* ****************************************************************************
*
* Entities::~Entities -
*/
Entities::~Entities()
{
release();
}
/* ****************************************************************************
*
* Entities::render -
*
* If no error reported in errorCode, render the vector of entities.
* Otherwise, render the errorCode.
*/
std::string Entities::render(ConnectionInfo* ciP, RequestType requestType)
{
if ((errorCode.code == SccOk) || (errorCode.code == SccNone))
{
return vec.render(ciP, requestType, false);
}
return errorCode.toJson(true);
}
/* ****************************************************************************
*
* Entities::check -
*
* NOTE
* The 'check' method is normally only used to check that incoming payload is correct.
* For now (at least), the Entities type is only used as outgoing payload ...
*/
std::string Entities::check(ConnectionInfo* ciP, RequestType requestType)
{
return vec.check(ciP, requestType);
}
/* ****************************************************************************
*
* Entities::present -
*/
void Entities::present(const std::string& indent)
{
LM_F(("%s%d Entities:", indent.c_str(), vec.size()));
vec.present(indent + " ");
}
/* ****************************************************************************
*
* Entities::release -
*/
void Entities::release(void)
{
vec.release();
}
/* ****************************************************************************
*
* Entities::fill -
*
* NOTE
* The errorCode field from qcrsP is not used at all if errorCode::code equals SccOk.
* This means that e.g. the "Count:" in errorCode::details (from v1 logic) will not be
* present in the Entities for v2 (that number is in the HTTP header X-Total-Count for v2).
* Other values for "details" are lost as well, if errorCode::code equals SccOk.
*/
void Entities::fill(QueryContextResponse* qcrsP)
{
if (qcrsP->errorCode.code == SccContextElementNotFound)
{
//
// If no entities are found, we respond with a 200 OK
// and an empty vector of entities ( [] )
//
errorCode.fill(SccOk);
return;
}
else if (qcrsP->errorCode.code != SccOk)
{
//
// If any other error - use the error for the response
//
errorCode.fill(qcrsP->errorCode);
return;
}
for (unsigned int ix = 0; ix < qcrsP->contextElementResponseVector.size(); ++ix)
{
ContextElement* ceP = &qcrsP->contextElementResponseVector[ix]->contextElement;
Entity* eP = new Entity();
eP->id = ceP->entityId.id;
eP->type = ceP->entityId.type;
eP->isPattern = ceP->entityId.isPattern;
eP->attributeVector.fill(&ceP->contextAttributeVector);
vec.push_back(eP);
}
}
<|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 "content/shell/shell_content_client.h"
#include "base/string_piece.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return std::string();
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
<commit_msg>Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise.<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 "content/shell/shell_content_client.h"
#include "base/string_piece.h"
#include "webkit/glue/user_agent.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18");
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_morton.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <cmath> // std::pow<>
#include <glm/gtc/vec1.hpp> // glm::?vec1
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/type_trait.hpp> // glm::type<>
// includes, project
#include <glm/gtx/morton.hpp>
#include <hugh/support/io.hpp>
#include <hugh/support/type_info.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
#define HUGH_GLM_GTX_MORTON_VERBOSE
#undef HUGH_GLM_GTX_MORTON_VERBOSE
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
std::array<unsigned long const, 5> const size = {
{
#if 1
1048576, 1024, 102, 32, 16,
#else
unsigned(std::pow(2, 31)) - 1,
unsigned(std::pow(2, 16)) - 1,
unsigned(std::pow(2, 10)) - 1,
unsigned(std::pow(2, 8)) - 1,
unsigned(std::pow(2, 6)) - 1,
#endif
}
};
// functions, internal
template <typename T, unsigned N>
void
print_variant()
{
std::ostringstream ostr;
ostr << std::right
<< std::setw(12) << unsigned(std::pow(size[N-1], N))
<< std::left
<< ": array<" + hugh::support::demangle(typeid(T)) << ',' << N << '>';
BOOST_TEST_MESSAGE(ostr.str());
}
template <template <typename, glm::precision> class V, typename T, glm::precision P>
void
print_variant(V<T,P> const&)
{
static unsigned const N(glm::type<V,T,P>::components);
std::ostringstream ostr;
ostr << std::right
<< std::setw(12) << unsigned(std::pow(size[N-1], N))
<< std::left
<< ": " << hugh::support::demangle(typeid(V<T,P>));
BOOST_TEST_MESSAGE(ostr.str());
}
} // namespace {
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
#if !defined(_MSC_VER) || (defined(_MSC_VER) && (_MSC_VER > 1900))
using array_types = boost::mpl::list<signed, unsigned>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array1, T, array_types)
{
print_variant<T,1>();
for (signed x(size[0]); x >= 0; --x) {
std::array<T,1> const v({T(x)});
T const c(glm::morton::encode<1>(v));
std::array<T,1> const e(glm::morton::decode<1>(c));
BOOST_CHECK(v == e);
using hugh::support::ostream::operator<<;
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(2) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array2, T, array_types)
{
print_variant<T,2>();
for (signed x(size[1]); x >= 0; --x) {
for (signed y(size[1]); y >= 0; --y) {
std::array<T,2> const v({T(x), T(y)});
T const c(glm::morton::encode<2>(v));
std::array<T,2> const e(glm::morton::decode<2>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array3, T, array_types)
{
print_variant<T,3>();
for (signed x(size[2]); x >= 0; --x) {
for (signed y(size[2]); y >= 0; --y) {
for (signed z(size[2]); z >= 0; --z) {
std::array<T,3> const v({T(x), T(y), T(z)});
T const c(glm::morton::encode<3>(v));
std::array<T,3> const e(glm::morton::decode<3>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array4, T, array_types)
{
print_variant<T,4>();
for (signed x(size[3]); x >= 0; --x) {
for (signed y(size[3]); y >= 0; --y) {
for (signed z(size[3]); z >= 0; --z) {
for (signed w(size[3]); w >= 0; --w) {
std::array<T,4> const v({T(x), T(y), T(z), T(w)});
T const c(glm::morton::encode<4>(v));
std::array<T,4> const e(glm::morton::decode<4>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(4) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array5, T, array_types)
{
print_variant<T,5>();
for (signed x(size[4]); x >= 0; --x) {
for (signed y(size[4]); y >= 0; --y) {
for (signed z(size[4]); z >= 0; --z) {
for (signed u(size[4]); u >= 0; --u) {
for (signed w(size[4]); w >= 0; --w) {
std::array<T,5> const v({T(x), T(y), T(z), T(u), T(w)});
T const c(glm::morton::encode<5>(v));
std::array<T,5> const e(glm::morton::decode<5>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(4) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
}
}
#endif // #if !defined(_MSC_VER) || (defined(_MSC_VER) && (_MSC_VER > 1800))
//glm::bvec1,
//glm::dvec1,
//glm::vec1,
using vec1_types = boost::mpl::list<glm::ivec1,glm::uvec1>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec1, T, vec1_types)
{
print_variant(T());
for (signed x(size[0]); x >= 0; --x) {
using V = typename T::value_type;
T const v(x);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(2) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
//glm::bvec2,
//glm::dvec2,
//glm::vec2,
using vec2_types = boost::mpl::list<glm::ivec2,glm::uvec2>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec2, T, vec2_types)
{
print_variant(T());
for (signed x(size[1]); x >= 0; --x) {
for (signed y(size[1]); y >= 0; --y) {
using V = typename T::value_type;
T const v(x, y);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
//glm::bvec3,
//glm::dvec3,
//glm::vec3,
using vec3_types = boost::mpl::list<glm::ivec3,glm::uvec3>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec3, T, vec3_types)
{
print_variant(T());
for (signed x(size[2]); x >= 0; --x) {
for (signed y(size[2]); y >= 0; --y) {
for (signed z(size[2]); z >= 0; --z) {
using V = typename T::value_type;
T const v(x, y, z);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
}
//glm::bvec4,
//glm::dvec4,
//glm::vec4,
using vec4_types = boost::mpl::list<glm::ivec4,glm::uvec4>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec4, T, vec4_types)
{
print_variant(T());
for (signed x(size[3]); x >= 0; --x) {
for (signed y(size[3]); y >= 0; --y) {
for (signed z(size[3]); z >= 0; --z) {
for (signed w(size[3]); w >= 0; --w) {
using V = typename T::value_type;
T const v(x, y, z, w);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
}
}
<commit_msg>fixed: copyright header<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016-2017 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_morton.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <cmath> // std::pow<>
#include <glm/gtc/vec1.hpp> // glm::?vec1
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/type_trait.hpp> // glm::type<>
// includes, project
#include <glm/gtx/morton.hpp>
#include <hugh/support/io.hpp>
#include <hugh/support/type_info.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
#define HUGH_GLM_GTX_MORTON_VERBOSE
#undef HUGH_GLM_GTX_MORTON_VERBOSE
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
std::array<unsigned long const, 5> const size = {
{
#if 1
1048576, 1024, 102, 32, 16,
#else
unsigned(std::pow(2, 31)) - 1,
unsigned(std::pow(2, 16)) - 1,
unsigned(std::pow(2, 10)) - 1,
unsigned(std::pow(2, 8)) - 1,
unsigned(std::pow(2, 6)) - 1,
#endif
}
};
// functions, internal
template <typename T, unsigned N>
void
print_variant()
{
std::ostringstream ostr;
ostr << std::right
<< std::setw(12) << unsigned(std::pow(size[N-1], N))
<< std::left
<< ": array<" + hugh::support::demangle(typeid(T)) << ',' << N << '>';
BOOST_TEST_MESSAGE(ostr.str());
}
template <template <typename, glm::precision> class V, typename T, glm::precision P>
void
print_variant(V<T,P> const&)
{
static unsigned const N(glm::type<V,T,P>::components);
std::ostringstream ostr;
ostr << std::right
<< std::setw(12) << unsigned(std::pow(size[N-1], N))
<< std::left
<< ": " << hugh::support::demangle(typeid(V<T,P>));
BOOST_TEST_MESSAGE(ostr.str());
}
} // namespace {
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
#if !defined(_MSC_VER) || (defined(_MSC_VER) && (_MSC_VER > 1900))
using array_types = boost::mpl::list<signed, unsigned>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array1, T, array_types)
{
print_variant<T,1>();
for (signed x(size[0]); x >= 0; --x) {
std::array<T,1> const v({T(x)});
T const c(glm::morton::encode<1>(v));
std::array<T,1> const e(glm::morton::decode<1>(c));
BOOST_CHECK(v == e);
using hugh::support::ostream::operator<<;
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(2) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array2, T, array_types)
{
print_variant<T,2>();
for (signed x(size[1]); x >= 0; --x) {
for (signed y(size[1]); y >= 0; --y) {
std::array<T,2> const v({T(x), T(y)});
T const c(glm::morton::encode<2>(v));
std::array<T,2> const e(glm::morton::decode<2>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array3, T, array_types)
{
print_variant<T,3>();
for (signed x(size[2]); x >= 0; --x) {
for (signed y(size[2]); y >= 0; --y) {
for (signed z(size[2]); z >= 0; --z) {
std::array<T,3> const v({T(x), T(y), T(z)});
T const c(glm::morton::encode<3>(v));
std::array<T,3> const e(glm::morton::decode<3>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array4, T, array_types)
{
print_variant<T,4>();
for (signed x(size[3]); x >= 0; --x) {
for (signed y(size[3]); y >= 0; --y) {
for (signed z(size[3]); z >= 0; --z) {
for (signed w(size[3]); w >= 0; --w) {
std::array<T,4> const v({T(x), T(y), T(z), T(w)});
T const c(glm::morton::encode<4>(v));
std::array<T,4> const e(glm::morton::decode<4>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(4) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_array5, T, array_types)
{
print_variant<T,5>();
for (signed x(size[4]); x >= 0; --x) {
for (signed y(size[4]); y >= 0; --y) {
for (signed z(size[4]); z >= 0; --z) {
for (signed u(size[4]); u >= 0; --u) {
for (signed w(size[4]); w >= 0; --w) {
std::array<T,5> const v({T(x), T(y), T(z), T(u), T(w)});
T const c(glm::morton::encode<5>(v));
std::array<T,5> const e(glm::morton::decode<5>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
using hugh::support::ostream::operator<<;
std::cout << "v:" << std::setw(2) << v << ", "
<< "c:" << std::setw(4) << c << ", "
<< "e:" << std::setw(2) << e
<< std::endl;
#endif
}
}
}
}
}
}
#endif // #if !defined(_MSC_VER) || (defined(_MSC_VER) && (_MSC_VER > 1800))
//glm::bvec1,
//glm::dvec1,
//glm::vec1,
using vec1_types = boost::mpl::list<glm::ivec1,glm::uvec1>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec1, T, vec1_types)
{
print_variant(T());
for (signed x(size[0]); x >= 0; --x) {
using V = typename T::value_type;
T const v(x);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(2) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
//glm::bvec2,
//glm::dvec2,
//glm::vec2,
using vec2_types = boost::mpl::list<glm::ivec2,glm::uvec2>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec2, T, vec2_types)
{
print_variant(T());
for (signed x(size[1]); x >= 0; --x) {
for (signed y(size[1]); y >= 0; --y) {
using V = typename T::value_type;
T const v(x, y);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
//glm::bvec3,
//glm::dvec3,
//glm::vec3,
using vec3_types = boost::mpl::list<glm::ivec3,glm::uvec3>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec3, T, vec3_types)
{
print_variant(T());
for (signed x(size[2]); x >= 0; --x) {
for (signed y(size[2]); y >= 0; --y) {
for (signed z(size[2]); z >= 0; --z) {
using V = typename T::value_type;
T const v(x, y, z);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
}
//glm::bvec4,
//glm::dvec4,
//glm::vec4,
using vec4_types = boost::mpl::list<glm::ivec4,glm::uvec4>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_morton_vec4, T, vec4_types)
{
print_variant(T());
for (signed x(size[3]); x >= 0; --x) {
for (signed y(size[3]); y >= 0; --y) {
for (signed z(size[3]); z >= 0; --z) {
for (signed w(size[3]); w >= 0; --w) {
using V = typename T::value_type;
T const v(x, y, z, w);
V const c(glm::morton::encode (v));
T const e(glm::morton::decode<T>(c));
BOOST_CHECK(v == e);
#if defined(HUGH_GLM_GTX_MORTON_VERBOSE)
BOOST_TEST_MESSAGE("v:" << glm::io::width(2) << v << ", "
<< "c:" << std::setw(3) << c << ", "
<< "e:" << glm::io::width(2) << e);
#endif
}
}
}
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3219
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3219 to 3220<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3220
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3359
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3359 to 3360<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3360
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3398
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3398 to 3399<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3399
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3321
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3321 to 3322<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3322
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3154
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3154 to 3155<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3155
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdDecorators.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2007-04
*/
//----------------------------------------------------------------------------------
#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
return PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
} else {
return false;
}
}
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::connect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
return PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
} else {
return false;
}
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
QObject* PythonQtStdDecorators::parent(QObject* o) {
return o->parent();
}
void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
o->setParent(parent);
}
const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
return &o->children();
}
bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
return o->setProperty(name, value);
}
QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
return o->property(name);
}
QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
if (!typeName && !meta)
return NULL;
return findChild(parent, typeName, meta, name);
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, name, list);
return list;
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, regExp, list);
return list;
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
const QObjectList &children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return NULL;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj)))
return obj;
}
for (i = 0; i < children.size(); ++i) {
QObject* obj = findChild(children.at(i), typeName, meta, name);
if (obj != NULL)
return obj;
}
return NULL;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, name, list) < 0)
return -1;
}
return 0;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (regExp.indexIn(obj->objectName()) == -1)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, regExp, list) < 0)
return -1;
}
return 0;
}
<commit_msg>added error printing for connect/disconnect<commit_after>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdDecorators.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2007-04
*/
//----------------------------------------------------------------------------------
#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
bool result = false;
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
result = PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
if (!result) {
if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
qWarning("PythonQt: QObject::connect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
}
}
}
return result;
}
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::connect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
bool result = false;
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
result = PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
if (!result) {
if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
qWarning("PythonQt: QObject::disconnect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
}
}
}
return result;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
QObject* PythonQtStdDecorators::parent(QObject* o) {
return o->parent();
}
void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
o->setParent(parent);
}
const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
return &o->children();
}
bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
return o->setProperty(name, value);
}
QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
return o->property(name);
}
QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
if (!typeName && !meta)
return NULL;
return findChild(parent, typeName, meta, name);
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, name, list);
return list;
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, regExp, list);
return list;
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
const QObjectList &children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return NULL;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj)))
return obj;
}
for (i = 0; i < children.size(); ++i) {
QObject* obj = findChild(children.at(i), typeName, meta, name);
if (obj != NULL)
return obj;
}
return NULL;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, name, list) < 0)
return -1;
}
return 0;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (regExp.indexIn(obj->objectName()) == -1)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, regExp, list) < 0)
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>/************************************************************************************
Copyright (C) 2005-2008 Assefaw H. Gebremedhin, Arijit Tarafdar, Duc Nguyen,
Alex Pothen
This file is part of ColPack.
ColPack is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ColPack 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 ColPack. If not, see <http://www.gnu.org/licenses/>.
************************************************************************************/
#include "ColPackHeaders.h"
using namespace std;
namespace ColPack
{
RecoveryCore::RecoveryCore() {
//formatType = "UNKNOWN";
//for ADOL-C Format (AF)
AF_available = false;
i_AF_rowCount = 0;
dp2_AF_Value = NULL;
//for Sparse Solvers Format (SSF)
SSF_available = false;
i_SSF_rowCount = 0;
ip_SSF_RowIndex = NULL;
ip_SSF_ColumnIndex = NULL;
dp_SSF_Value = NULL;
//for Coordinate Format (CF)
CF_available = false;
i_CF_rowCount = 0;
ip_CF_RowIndex = NULL;
ip_CF_ColumnIndex = NULL;
dp_CF_Value = NULL;
}
void RecoveryCore::reset() {
//for ADOL-C Format (AF)
if (AF_available) {
//free_2DMatrix(dp2_AF_Value, i_AF_rowCount);
for( int i=0; i < i_AF_rowCount; i++ ) {
free( dp2_AF_Value[i] );
}
free( dp2_AF_Value );
dp2_AF_Value = NULL;
AF_available = false;
i_AF_rowCount = 0;
}
//for Sparse Solvers Format (SSF)
if (SSF_available) {
//delete[] ip_SSF_RowIndex;
free(ip_SSF_RowIndex);
ip_SSF_RowIndex = NULL;
//delete[] ip_SSF_ColumnIndex;
free(ip_SSF_ColumnIndex);
ip_SSF_ColumnIndex = NULL;
//delete[] dp_SSF_Value;
free(dp_SSF_Value);
dp_SSF_Value = NULL;
SSF_available = false;
i_SSF_rowCount = 0;
}
//for Coordinate Format (CF)
if (CF_available) {
//do something
//delete[] ip_CF_RowIndex;
free(ip_CF_RowIndex);
ip_CF_RowIndex = NULL;
//delete[] ip_CF_ColumnIndex;
free(ip_CF_ColumnIndex);
ip_CF_ColumnIndex = NULL;
//delete[] dp_CF_Value;
free(dp_CF_Value);
dp_CF_Value = NULL;
CF_available = false;
i_CF_rowCount = 0;
}
//formatType = "UNKNOWN";
}
RecoveryCore::~RecoveryCore() {
//for ADOL-C Format (AF)
if (AF_available) {
//do something
//free_2DMatrix(dp2_AF_Value, i_AF_rowCount);
for( int i=0; i < i_AF_rowCount; i++ ) {
free( dp2_AF_Value[i] );
}
free( dp2_AF_Value );
}
//for Sparse Solvers Format (SSF)
if (SSF_available) {
//do something
//delete[] ip_SSF_RowIndex;
free(ip_SSF_RowIndex);
//delete[] ip_SSF_ColumnIndex;
free(ip_SSF_ColumnIndex);
//delete[] dp_SSF_Value;
free(dp_SSF_Value);
}
//for Coordinate Format (CF)
if (CF_available) {
//do something
//delete[] ip_CF_RowIndex;
free(ip_CF_RowIndex);
//delete[] ip_CF_ColumnIndex;
free(ip_CF_ColumnIndex);
//delete[] dp_CF_Value;
free(dp_CF_Value);
}
}
}
<commit_msg>Update RecoveryCore.cpp<commit_after>/*******************************************************************************
This file is part of ColPack, which is under its License protection.
You should have received a copy of the License. If not, see
<https://github.com/CSCsw/ColPack>
*******************************************************************************/
#include "ColPackHeaders.h"
using namespace std;
namespace ColPack
{
RecoveryCore::RecoveryCore() {
//formatType = "UNKNOWN";
//for ADOL-C Format (AF)
AF_available = false;
i_AF_rowCount = 0;
dp2_AF_Value = NULL;
//for Sparse Solvers Format (SSF)
SSF_available = false;
i_SSF_rowCount = 0;
ip_SSF_RowIndex = NULL;
ip_SSF_ColumnIndex = NULL;
dp_SSF_Value = NULL;
//for Coordinate Format (CF)
CF_available = false;
i_CF_rowCount = 0;
ip_CF_RowIndex = NULL;
ip_CF_ColumnIndex = NULL;
dp_CF_Value = NULL;
}
void RecoveryCore::reset() {
//for ADOL-C Format (AF)
if (AF_available) {
//free_2DMatrix(dp2_AF_Value, i_AF_rowCount);
for( int i=0; i < i_AF_rowCount; i++ ) {
free( dp2_AF_Value[i] );
}
free( dp2_AF_Value );
dp2_AF_Value = NULL;
AF_available = false;
i_AF_rowCount = 0;
}
//for Sparse Solvers Format (SSF)
if (SSF_available) {
//delete[] ip_SSF_RowIndex;
free(ip_SSF_RowIndex);
ip_SSF_RowIndex = NULL;
//delete[] ip_SSF_ColumnIndex;
free(ip_SSF_ColumnIndex);
ip_SSF_ColumnIndex = NULL;
//delete[] dp_SSF_Value;
free(dp_SSF_Value);
dp_SSF_Value = NULL;
SSF_available = false;
i_SSF_rowCount = 0;
}
//for Coordinate Format (CF)
if (CF_available) {
//do something
//delete[] ip_CF_RowIndex;
free(ip_CF_RowIndex);
ip_CF_RowIndex = NULL;
//delete[] ip_CF_ColumnIndex;
free(ip_CF_ColumnIndex);
ip_CF_ColumnIndex = NULL;
//delete[] dp_CF_Value;
free(dp_CF_Value);
dp_CF_Value = NULL;
CF_available = false;
i_CF_rowCount = 0;
}
//formatType = "UNKNOWN";
}
RecoveryCore::~RecoveryCore() {
//for ADOL-C Format (AF)
if (AF_available) {
//do something
//free_2DMatrix(dp2_AF_Value, i_AF_rowCount);
for( int i=0; i < i_AF_rowCount; i++ ) {
free( dp2_AF_Value[i] );
}
free( dp2_AF_Value );
}
//for Sparse Solvers Format (SSF)
if (SSF_available) {
//do something
//delete[] ip_SSF_RowIndex;
free(ip_SSF_RowIndex);
//delete[] ip_SSF_ColumnIndex;
free(ip_SSF_ColumnIndex);
//delete[] dp_SSF_Value;
free(dp_SSF_Value);
}
//for Coordinate Format (CF)
if (CF_available) {
//do something
//delete[] ip_CF_RowIndex;
free(ip_CF_RowIndex);
//delete[] ip_CF_ColumnIndex;
free(ip_CF_ColumnIndex);
//delete[] dp_CF_Value;
free(dp_CF_Value);
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix some opcodes<commit_after><|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
//#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
bool isANotMoreThanB(person A, person B) {
char * A_name = A.getName();
char * B_name = B.getName();
for (size_t i = 0; i < A_name.length(); i++) {
char A_char = name[i];
char B_char = (i < B_name_length) ? B_name[i] : ' ';
if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) {
return true;
}
else {
if (A_name[i] != B_name[i]) {
return false;
}
}
}
delete []A_char;
delete []B_char;
return true;
}
SCENARIO("Sort", "[s]") {
size_t n_persons = 200;
//system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604");
size_t RAM_amount = 1;
std::string names_file_name = "F:\\1\\names.txt";
std::string surnames_file_name = "F:\\1\\surnames.txt";
std::string database_file_name = "F:\\1\\8.txt";
std::string output_file_name = "F:\\1\\sorted_database.txt";
//Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
database_sorter.closeDatabase();
std::cout << result << std::endl;
for (size_t i = 0; i < 0; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}
}
<commit_msg>Update init.cpp<commit_after>#include "catch.hpp"
#include <iostream>
//#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"
person readPerson(std::string file_name, size_t index) {
person result;
std::ifstream file(file_name);
for (size_t i = 0; i < index + 1; i++) {
file >> result;
}
file.close();
return result;
}
bool isANotMoreThanB(person A, person B) {
char * A_name = A.getName();
char * B_name = B.getName();
for (size_t i = 0; i < A.name_length; i++) {
char A_char = name[i];
char B_char = (i < B.name_length) ? B_name[i] : ' ';
if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) {
return true;
}
else {
if (A_name[i] != B_name[i]) {
return false;
}
}
}
delete []A_char;
delete []B_char;
return true;
}
SCENARIO("Sort", "[s]") {
size_t n_persons = 200;
//system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604");
size_t RAM_amount = 1;
std::string names_file_name = "F:\\1\\names.txt";
std::string surnames_file_name = "F:\\1\\surnames.txt";
std::string database_file_name = "F:\\1\\8.txt";
std::string output_file_name = "F:\\1\\sorted_database.txt";
//Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
size_t start = clock();
database_sorter.sortDatabase();
size_t result = clock() - start;
database_sorter.closeDatabase();
std::cout << result << std::endl;
for (size_t i = 0; i < 0; i++) {
size_t person1_i = rand() % n_persons;
size_t person2_i = person1_i + rand() % (n_persons - person1_i);
person person1 = readPerson(output_file_name, person1_i);
person person2 = readPerson(output_file_name, person2_i);
REQUIRE(isANotMoreThanB(person1, person2));
}
}
<|endoftext|> |
<commit_before>#include "BinaryTree.сpp"
#include <fstream>
#include <catch.hpp>
SCENARIO("default constructor")
{
Tree<int> node;
REQUIRE(node.root_() == nullptr);
}
SCENARIO("insert")
{
Tree<int> tree;
int newEl;
tree.fIn("Tree.txt");
std::ifstream("newEl.txt") >> newEl;
tree.insert(newEl);
REQUIRE(tree.right_() == 7);
}
SCENARIO("search")
{
Tree<int> tree;
Node<int> * node;
tree.fIn("Tree+newEl.txt");
node = tree.search(5);
REQUIRE(tree.x_() == 5);
REQUIRE(tree.left_() == 3);
REQUIRE(tree.right_() == 7);
}
SCENARIO("fIn")
{
Tree<int> tree;
tree.fIn("Tree.txt");
REQUIRE(tree.x_() == 5);
}
<commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp"
#include <fstream>
#include <catch.hpp>
SCENARIO("default constructor")
{
Tree<int> node;
REQUIRE(node.root_() == nullptr);
}
SCENARIO("insert")
{
Tree<int> tree;
int newEl;
tree.fIn("Tree.txt");
std::ifstream("newEl.txt") >> newEl;
tree.insert(newEl);
REQUIRE(tree.right_() == 7);
}
SCENARIO("search")
{
Tree<int> tree;
Node<int> * node;
tree.fIn("Tree+newEl.txt");
node = tree.search(5);
REQUIRE(tree.x_() == 5);
REQUIRE(tree.left_() == 3);
REQUIRE(tree.right_() == 7);
}
SCENARIO("fIn")
{
Tree<int> tree;
tree.fIn("Tree.txt");
REQUIRE(tree.x_() == 5);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2011 Collabora Ltd <http://www.collabora.co.uk>
* Copyright (C) 2009 Andre Moreira Magalhaes <andrunko@gmail.com>
* Copyright (C) 2010-2011 Dario Freddi <drf@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "presencesource.h"
#include "presenceservice.h"
#include <KDebug>
#include <KTemporaryFile>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
PresenceSource::PresenceSource(const Tp::AccountPtr &account, QObject *parent)
: Plasma::DataContainer(parent),
m_account(account)
{
kDebug() << "PresenceSource created for account:" <<
account->objectPath();
setData("DisplayName", "");
setData("Nickname", "");
setData("AccountAvatar", "");
setData("PresenceType", "");
setData("PresenceTypeID", 0);
setData("PresenceStatus", "");
setData("PresenceStatusMessage", "");
// Set the object name (which will be the name of the source)
setObjectName(m_account->objectPath());
// Make the account become ready with the desired features
connect(m_account->becomeReady(Tp::Account::FeatureProtocolInfo|Tp::Account::FeatureAvatar),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onAccountReady(Tp::PendingOperation*)));
}
PresenceSource::~PresenceSource()
{
}
Plasma::Service *PresenceSource::createService()
{
return new PresenceService(this);
}
Tp::AccountPtr PresenceSource::account() const
{
return m_account;
}
void PresenceSource::onAccountReady(Tp::PendingOperation *op)
{
// Check if the operation succeeded or not
if (op->isError()) {
kWarning() << "PresenceSource::onAccountReady: readying "
"Account failed:" << op->errorName() << ":" << op->errorMessage();
return;
}
// Check that the account is valid
if (!m_account->isValidAccount()) {
// TODO should source be removed?
kWarning() << "Invalid account in source:" << objectName();
return;
}
connect(m_account.data(),
SIGNAL(currentPresenceChanged(Tp::Presence)),
SLOT(onAccountCurrentPresenceChanged(Tp::Presence)));
connect(m_account.data(),
SIGNAL(nicknameChanged(const QString &)),
SLOT(onNicknameChanged(const QString &)));
connect(m_account.data(),
SIGNAL(displayNameChanged(const QString &)),
SLOT(onDisplayNameChanged(const QString &)));
connect(m_account.data(),
SIGNAL(avatarChanged(const Tp::Avatar &)),
SLOT(onAvatarChanged(const Tp::Avatar &)));
// Force initial settings
onAccountCurrentPresenceChanged(m_account->currentPresence());
onNicknameChanged(m_account->nickname());
onDisplayNameChanged(m_account->displayName());
onAvatarChanged(m_account->avatar());
}
void PresenceSource::onAccountCurrentPresenceChanged(
const Tp::Presence &presence)
{
// Update the data of this source
setData("PresenceType", presenceTypeToString(presence.type()));
setData("PresenceTypeID", presenceTypeToID(presence.type()));
setData("PresenceStatus", presence.status());
setData("PresenceStatusMessage", presence.statusMessage());
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onNicknameChanged(
const QString &nickname)
{
// Update the data of this source
setData("Nickname", nickname);
kDebug() << "Nickname changed to " << nickname;
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onDisplayNameChanged(
const QString &displayName)
{
// Update the data of this source
setData("DisplayName", displayName);
kDebug() << "DisplayName changed to " << displayName;
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onAvatarChanged(
const Tp::Avatar &avatar)
{
// Update the data of this source
// Is the data empty?
if (avatar.avatarData.isEmpty()) {
// Set an empty string
setData("AccountAvatar", "");
} else {
// Create a temp file and use it to feed the engine
if (!m_tempAvatar.isNull()) {
m_tempAvatar.data()->deleteLater();
}
m_tempAvatar = new KTemporaryFile();
m_tempAvatar.data()->setAutoRemove(true);
m_tempAvatar.data()->open();
m_tempAvatar.data()->write(avatar.avatarData);
m_tempAvatar.data()->flush();
setData("AccountAvatar", m_tempAvatar.data()->fileName());
}
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
QString PresenceSource::presenceTypeToString(uint type)
{
// This method converts a presence type from a telepathy SimplePresence
// struct to a string representation for data sources.
QString ret;
switch (type) {
case Tp::ConnectionPresenceTypeUnset:
ret = "unset";
break;
case Tp::ConnectionPresenceTypeOffline:
ret = "offline";
break;
case Tp::ConnectionPresenceTypeAvailable:
ret = "available";
break;
case Tp::ConnectionPresenceTypeAway:
case Tp::ConnectionPresenceTypeExtendedAway:
ret = "away";
break;
case Tp::ConnectionPresenceTypeHidden:
ret = "invisible";
break;
case Tp::ConnectionPresenceTypeBusy:
ret = "busy";
break;
case Tp::ConnectionPresenceTypeError:
ret = "error";
break;
default:
ret = "unknown";
break;
}
return ret;
}
uint PresenceSource::presenceTypeToID(uint type)
{
uint ret;
switch (type) {
case Tp::ConnectionPresenceTypeUnset:
ret = 6;
break;
case Tp::ConnectionPresenceTypeOffline:
ret = 5;
break;
case Tp::ConnectionPresenceTypeAvailable:
ret = 1;
break;
case Tp::ConnectionPresenceTypeAway:
case Tp::ConnectionPresenceTypeExtendedAway:
ret = 3;
break;
case Tp::ConnectionPresenceTypeHidden:
ret = 4;
break;
case Tp::ConnectionPresenceTypeBusy:
ret = 2;
break;
case Tp::ConnectionPresenceTypeError:
default:
ret = 99;
break;
}
return ret;
}
#include "presencesource.moc"
<commit_msg>Added "AccountIcon" info to the dataengine<commit_after>/*
* Copyright (C) 2009-2011 Collabora Ltd <http://www.collabora.co.uk>
* Copyright (C) 2009 Andre Moreira Magalhaes <andrunko@gmail.com>
* Copyright (C) 2010-2011 Dario Freddi <drf@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "presencesource.h"
#include "presenceservice.h"
#include <KDebug>
#include <KTemporaryFile>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
PresenceSource::PresenceSource(const Tp::AccountPtr &account, QObject *parent)
: Plasma::DataContainer(parent),
m_account(account)
{
kDebug() << "PresenceSource created for account:" <<
account->objectPath();
setData("DisplayName", "");
setData("Nickname", "");
setData("AccountAvatar", "");
setData("AccountIcon", account->iconName());
setData("PresenceType", "");
setData("PresenceTypeID", 0);
setData("PresenceStatus", "");
setData("PresenceStatusMessage", "");
// Set the object name (which will be the name of the source)
setObjectName(m_account->objectPath());
// Make the account become ready with the desired features
connect(m_account->becomeReady(Tp::Account::FeatureProtocolInfo|Tp::Account::FeatureAvatar),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onAccountReady(Tp::PendingOperation*)));
}
PresenceSource::~PresenceSource()
{
}
Plasma::Service *PresenceSource::createService()
{
return new PresenceService(this);
}
Tp::AccountPtr PresenceSource::account() const
{
return m_account;
}
void PresenceSource::onAccountReady(Tp::PendingOperation *op)
{
// Check if the operation succeeded or not
if (op->isError()) {
kWarning() << "PresenceSource::onAccountReady: readying "
"Account failed:" << op->errorName() << ":" << op->errorMessage();
return;
}
// Check that the account is valid
if (!m_account->isValidAccount()) {
// TODO should source be removed?
kWarning() << "Invalid account in source:" << objectName();
return;
}
connect(m_account.data(),
SIGNAL(currentPresenceChanged(Tp::Presence)),
SLOT(onAccountCurrentPresenceChanged(Tp::Presence)));
connect(m_account.data(),
SIGNAL(nicknameChanged(const QString &)),
SLOT(onNicknameChanged(const QString &)));
connect(m_account.data(),
SIGNAL(displayNameChanged(const QString &)),
SLOT(onDisplayNameChanged(const QString &)));
connect(m_account.data(),
SIGNAL(avatarChanged(const Tp::Avatar &)),
SLOT(onAvatarChanged(const Tp::Avatar &)));
// Force initial settings
onAccountCurrentPresenceChanged(m_account->currentPresence());
onNicknameChanged(m_account->nickname());
onDisplayNameChanged(m_account->displayName());
onAvatarChanged(m_account->avatar());
}
void PresenceSource::onAccountCurrentPresenceChanged(
const Tp::Presence &presence)
{
// Update the data of this source
setData("PresenceType", presenceTypeToString(presence.type()));
setData("PresenceTypeID", presenceTypeToID(presence.type()));
setData("PresenceStatus", presence.status());
setData("PresenceStatusMessage", presence.statusMessage());
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onNicknameChanged(
const QString &nickname)
{
// Update the data of this source
setData("Nickname", nickname);
kDebug() << "Nickname changed to " << nickname;
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onDisplayNameChanged(
const QString &displayName)
{
// Update the data of this source
setData("DisplayName", displayName);
kDebug() << "DisplayName changed to " << displayName;
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
void PresenceSource::onAvatarChanged(
const Tp::Avatar &avatar)
{
// Update the data of this source
// Is the data empty?
if (avatar.avatarData.isEmpty()) {
// Set an empty string
setData("AccountAvatar", "");
} else {
// Create a temp file and use it to feed the engine
if (!m_tempAvatar.isNull()) {
m_tempAvatar.data()->deleteLater();
}
m_tempAvatar = new KTemporaryFile();
m_tempAvatar.data()->setAutoRemove(true);
m_tempAvatar.data()->open();
m_tempAvatar.data()->write(avatar.avatarData);
m_tempAvatar.data()->flush();
setData("AccountAvatar", m_tempAvatar.data()->fileName());
}
// Required to trigger emission of update signal after changing data
checkForUpdate();
}
QString PresenceSource::presenceTypeToString(uint type)
{
// This method converts a presence type from a telepathy SimplePresence
// struct to a string representation for data sources.
QString ret;
switch (type) {
case Tp::ConnectionPresenceTypeUnset:
ret = "unset";
break;
case Tp::ConnectionPresenceTypeOffline:
ret = "offline";
break;
case Tp::ConnectionPresenceTypeAvailable:
ret = "available";
break;
case Tp::ConnectionPresenceTypeAway:
case Tp::ConnectionPresenceTypeExtendedAway:
ret = "away";
break;
case Tp::ConnectionPresenceTypeHidden:
ret = "invisible";
break;
case Tp::ConnectionPresenceTypeBusy:
ret = "busy";
break;
case Tp::ConnectionPresenceTypeError:
ret = "error";
break;
default:
ret = "unknown";
break;
}
return ret;
}
uint PresenceSource::presenceTypeToID(uint type)
{
uint ret;
switch (type) {
case Tp::ConnectionPresenceTypeUnset:
ret = 6;
break;
case Tp::ConnectionPresenceTypeOffline:
ret = 5;
break;
case Tp::ConnectionPresenceTypeAvailable:
ret = 1;
break;
case Tp::ConnectionPresenceTypeAway:
case Tp::ConnectionPresenceTypeExtendedAway:
ret = 3;
break;
case Tp::ConnectionPresenceTypeHidden:
ret = 4;
break;
case Tp::ConnectionPresenceTypeBusy:
ret = 2;
break;
case Tp::ConnectionPresenceTypeError:
default:
ret = 99;
break;
}
return ret;
}
#include "presencesource.moc"
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE test
#include <boost/test/included/unit_test.hpp>
#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/assign/list_of.hpp>
#include <iostream>
#include <algorithm>
#include "util.hpp"
#include "direction.hpp"
#include "state.hpp"
#include "moves.hpp"
BOOST_AUTO_TEST_CASE(partitions) {
using namespace squares;
BOOST_CHECK_EQUAL(files::a, a1 | a2 | a3 | a4 | a5 | a6 | a7 | a8);
BOOST_CHECK_EQUAL(ranks::_8, a8 | b8 | c8 | d8 | e8 | f8 | g8 | h8);
}
BOOST_AUTO_TEST_CASE(initial_moves) {
State state;
std::set<Move> expected_moves;
using namespace directions;
bitboard::for_each_member(ranks::_2, [&expected_moves](squares::Index from) {
expected_moves.emplace(from, from + north, Move::Type::normal);
expected_moves.emplace(from, from + 2*north, Move::Type::double_push);
});
bitboard::for_each_member(squares::b1 | squares::g1, [&expected_moves](squares::Index from) {
expected_moves.emplace(from, from + 2*north + west, Move::Type::normal);
expected_moves.emplace(from, from + 2*north + east, Move::Type::normal);
});
const std::vector<Move> moves = state.moves();
const std::set<Move> actual_moves(moves.begin(), moves.end());
std::set<Move> falsenegatives, falsepositives;
std::set_difference(expected_moves.begin(), expected_moves.end(),
actual_moves.begin(), actual_moves.end(),
std::inserter(falsenegatives, falsenegatives.begin()));
std::set_difference(actual_moves.begin(), actual_moves.end(),
expected_moves.begin(), expected_moves.end(),
std::inserter(falsepositives, falsepositives.begin()));
BOOST_CHECK_MESSAGE(falsenegatives.empty(), "legal moves not generated: " << falsenegatives);
BOOST_CHECK_MESSAGE(falsepositives.empty(), "illegal moves generated: " << falsepositives);
}
BOOST_AUTO_TEST_CASE(various_moves) {
State state("r1b2rk1/pp1P1p1p/q1p2n2/2N2PpB/1NP2bP1/2R1B3/PP2Q2P/R3K3 w Q g6 0 1");
using namespace colors;
using namespace pieces;
using namespace squares;
BOOST_CHECK_EQUAL(state.board[white][pawn], a2 | b2 | c4 | d7 | f5 | g4 | h2);
BOOST_CHECK_EQUAL(state.board[white][knight], b4 | c5);
BOOST_CHECK_EQUAL(state.board[white][bishop], e3 | h5);
BOOST_CHECK_EQUAL(state.board[white][rook], a1 | c3);
BOOST_CHECK_EQUAL(state.board[white][queen], e2.bitboard);
BOOST_CHECK_EQUAL(state.board[white][king], e1.bitboard);
BOOST_CHECK_EQUAL(state.board[black][pawn], a7 | b7 | c6 | f7 | g5 | h7);
BOOST_CHECK_EQUAL(state.board[black][knight], f6.bitboard);
BOOST_CHECK_EQUAL(state.board[black][bishop], c8 | f4);
BOOST_CHECK_EQUAL(state.board[black][rook], a8 | f8);
BOOST_CHECK_EQUAL(state.board[black][queen], a6.bitboard);
BOOST_CHECK_EQUAL(state.board[black][king], g8.bitboard);
BOOST_CHECK_EQUAL(state.en_passant_square, g6.bitboard);
BOOST_CHECK(!state.can_castle_kingside[white]);
BOOST_CHECK(!state.can_castle_kingside[black]);
BOOST_CHECK( state.can_castle_queenside[white]);
BOOST_CHECK(!state.can_castle_queenside[black]);
BOOST_CHECK_EQUAL(state.color_to_move, white);
std::set<Move> expected_moves;
// a1 rook
for (BoardPartition::Part target: {b1, c1, d1})
expected_moves.emplace(Move(a1.index, target.index, Move::Type::normal));
// e1 king
for (BoardPartition::Part target: {d1, f1, d2, f2})
expected_moves.emplace(Move(e1.index, target.index, Move::Type::normal));
expected_moves.emplace(Move(e1.index, c1.index, Move::Type::castle_queenside));
// a2 pawn
expected_moves.emplace(Move(a2.index, a3.index, Move::Type::normal));
expected_moves.emplace(Move(a2.index, a4.index, Move::Type::double_push));
// b2 pawn
expected_moves.emplace(Move(b2.index, b3.index, Move::Type::normal));
// e2 queen
for (BoardPartition::Part target: {f1, f2, g2, f3, d3, d2, c2, d1})
expected_moves.emplace(Move(e2.index, target.index, Move::Type::normal));
// h2 pawn
expected_moves.emplace(Move(h2.index, h3.index, Move::Type::normal));
expected_moves.emplace(Move(h2.index, h4.index, Move::Type::double_push));
// c3 rook
for (BoardPartition::Part target: {c2, c1, d3, b3, a3})
expected_moves.emplace(Move(c3.index, target.index, Move::Type::normal));
// e3 bishop
for (BoardPartition::Part target: {f2, g1, d4, d2, c1})
expected_moves.emplace(Move(e3.index, target.index, Move::Type::normal));
expected_moves.emplace(Move(e3.index, f4.index, Move::Type::capture));
// b4 knight
for (BoardPartition::Part target: {a6, d5, d3, c2})
expected_moves.emplace(Move(b4.index, target.index, Move::Type::normal));
for (BoardPartition::Part target: {a6, c6})
expected_moves.emplace(Move(b4.index, target.index, Move::Type::capture));
// c4 pawn
// g4 pawn
// c5 knight
for (BoardPartition::Part target: {e6, e4, d3, b3, a4})
expected_moves.emplace(Move(c5.index, target.index, Move::Type::normal));
for (BoardPartition::Part target: {a6, b7})
expected_moves.emplace(Move(c5.index, target.index, Move::Type::capture));
// f5 pawn
expected_moves.emplace(Move(f5.index, g6.index, Move::Type::capture));
// h5 bishop
expected_moves.emplace(Move(h5.index, g6.index, Move::Type::normal));
expected_moves.emplace(Move(h5.index, f7.index, Move::Type::capture));
// d7 pawn
for (Move::Type type: {Move::Type::promotion_knight,
Move::Type::promotion_bishop,
Move::Type::promotion_rook,
Move::Type::promotion_queen}) {
expected_moves.emplace(Move(d7.index, d8.index, type));
}
for (Move::Type type: {Move::Type::capturing_promotion_knight,
Move::Type::capturing_promotion_bishop,
Move::Type::capturing_promotion_rook,
Move::Type::capturing_promotion_queen}) {
expected_moves.emplace(Move(d7.index, c8.index, type));
}
const std::vector<Move> moves = state.moves();
const std::set<Move> actual_moves(moves.begin(), moves.end());
std::set<Move> falsenegatives, falsepositives;
std::set_difference(expected_moves.begin(), expected_moves.end(),
actual_moves.begin(), actual_moves.end(),
std::inserter(falsenegatives, falsenegatives.begin()));
std::set_difference(actual_moves.begin(), actual_moves.end(),
expected_moves.begin(), expected_moves.end(),
std::inserter(falsepositives, falsepositives.begin()));
BOOST_CHECK_MESSAGE(falsenegatives.empty(), "legal moves not generated: " << falsenegatives);
BOOST_CHECK_MESSAGE(falsepositives.empty(), "illegal moves generated: " << falsepositives);
}
BOOST_AUTO_TEST_CASE(_moves) {
State state;
state.make_moves("e4 e5 Nf3 Nc6 Bc4 Bc5 b4 Bxb4 c3 Ba5 d4 exd4 0-0 d3 Qb3 Qf6"
"e5 Qg6 Re1 Nge7 Ba3 b5 Qxb5 Rb8 Qa4 Bb6 Nbd2 Bb7 Ne4 Qf5"
"Bxd3 Qh5 Nf6+ gxf6 18.exf6 Rg8 19.Rad1 Qxf3 20.Rxe7+ Nxe7"
"21.Qxd7+ Kxd7 22.Bf5+ Ke8 23.Bd7+ Kf8");
BOOST_CHECK(true);
}
<commit_msg>whoops<commit_after>#define BOOST_TEST_MODULE test
#include <boost/test/included/unit_test.hpp>
#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/assign/list_of.hpp>
#include <iostream>
#include <algorithm>
#include "util.hpp"
#include "direction.hpp"
#include "state.hpp"
#include "moves.hpp"
BOOST_AUTO_TEST_CASE(partitions) {
using namespace squares;
BOOST_CHECK_EQUAL(files::a, a1 | a2 | a3 | a4 | a5 | a6 | a7 | a8);
BOOST_CHECK_EQUAL(ranks::_8, a8 | b8 | c8 | d8 | e8 | f8 | g8 | h8);
}
BOOST_AUTO_TEST_CASE(initial_moves) {
State state;
std::set<Move> expected_moves;
using namespace directions;
bitboard::for_each_member(ranks::_2, [&expected_moves](squares::Index from) {
expected_moves.emplace(from, from + north, Move::Type::normal);
expected_moves.emplace(from, from + 2*north, Move::Type::double_push);
});
bitboard::for_each_member(squares::b1 | squares::g1, [&expected_moves](squares::Index from) {
expected_moves.emplace(from, from + 2*north + west, Move::Type::normal);
expected_moves.emplace(from, from + 2*north + east, Move::Type::normal);
});
const std::vector<Move> moves = state.moves();
const std::set<Move> actual_moves(moves.begin(), moves.end());
std::set<Move> falsenegatives, falsepositives;
std::set_difference(expected_moves.begin(), expected_moves.end(),
actual_moves.begin(), actual_moves.end(),
std::inserter(falsenegatives, falsenegatives.begin()));
std::set_difference(actual_moves.begin(), actual_moves.end(),
expected_moves.begin(), expected_moves.end(),
std::inserter(falsepositives, falsepositives.begin()));
BOOST_CHECK_MESSAGE(falsenegatives.empty(), "legal moves not generated: " << falsenegatives);
BOOST_CHECK_MESSAGE(falsepositives.empty(), "illegal moves generated: " << falsepositives);
}
BOOST_AUTO_TEST_CASE(various_moves) {
State state("r1b2rk1/pp1P1p1p/q1p2n2/2N2PpB/1NP2bP1/2R1B3/PP2Q2P/R3K3 w Q g6 0 1");
using namespace colors;
using namespace pieces;
using namespace squares;
BOOST_CHECK_EQUAL(state.board[white][pawn], a2 | b2 | c4 | d7 | f5 | g4 | h2);
BOOST_CHECK_EQUAL(state.board[white][knight], b4 | c5);
BOOST_CHECK_EQUAL(state.board[white][bishop], e3 | h5);
BOOST_CHECK_EQUAL(state.board[white][rook], a1 | c3);
BOOST_CHECK_EQUAL(state.board[white][queen], e2.bitboard);
BOOST_CHECK_EQUAL(state.board[white][king], e1.bitboard);
BOOST_CHECK_EQUAL(state.board[black][pawn], a7 | b7 | c6 | f7 | g5 | h7);
BOOST_CHECK_EQUAL(state.board[black][knight], f6.bitboard);
BOOST_CHECK_EQUAL(state.board[black][bishop], c8 | f4);
BOOST_CHECK_EQUAL(state.board[black][rook], a8 | f8);
BOOST_CHECK_EQUAL(state.board[black][queen], a6.bitboard);
BOOST_CHECK_EQUAL(state.board[black][king], g8.bitboard);
BOOST_CHECK_EQUAL(state.en_passant_square, g6.bitboard);
BOOST_CHECK(!state.can_castle_kingside[white]);
BOOST_CHECK(!state.can_castle_kingside[black]);
BOOST_CHECK( state.can_castle_queenside[white]);
BOOST_CHECK(!state.can_castle_queenside[black]);
BOOST_CHECK_EQUAL(state.color_to_move, white);
std::set<Move> expected_moves;
// a1 rook
for (BoardPartition::Part target: {b1, c1, d1})
expected_moves.emplace(Move(a1.index, target.index, Move::Type::normal));
// e1 king
for (BoardPartition::Part target: {d1, f1, d2, f2})
expected_moves.emplace(Move(e1.index, target.index, Move::Type::normal));
expected_moves.emplace(Move(e1.index, c1.index, Move::Type::castle_queenside));
// a2 pawn
expected_moves.emplace(Move(a2.index, a3.index, Move::Type::normal));
expected_moves.emplace(Move(a2.index, a4.index, Move::Type::double_push));
// b2 pawn
expected_moves.emplace(Move(b2.index, b3.index, Move::Type::normal));
// e2 queen
for (BoardPartition::Part target: {f1, f2, g2, f3, d3, d2, c2, d1})
expected_moves.emplace(Move(e2.index, target.index, Move::Type::normal));
// h2 pawn
expected_moves.emplace(Move(h2.index, h3.index, Move::Type::normal));
expected_moves.emplace(Move(h2.index, h4.index, Move::Type::double_push));
// c3 rook
for (BoardPartition::Part target: {c2, c1, d3, b3, a3})
expected_moves.emplace(Move(c3.index, target.index, Move::Type::normal));
// e3 bishop
for (BoardPartition::Part target: {f2, g1, d4, d2, c1})
expected_moves.emplace(Move(e3.index, target.index, Move::Type::normal));
expected_moves.emplace(Move(e3.index, f4.index, Move::Type::capture));
// b4 knight
for (BoardPartition::Part target: {d5, d3, c2})
expected_moves.emplace(Move(b4.index, target.index, Move::Type::normal));
for (BoardPartition::Part target: {a6, c6})
expected_moves.emplace(Move(b4.index, target.index, Move::Type::capture));
// c4 pawn
// g4 pawn
// c5 knight
for (BoardPartition::Part target: {e6, e4, d3, b3, a4})
expected_moves.emplace(Move(c5.index, target.index, Move::Type::normal));
for (BoardPartition::Part target: {a6, b7})
expected_moves.emplace(Move(c5.index, target.index, Move::Type::capture));
// f5 pawn
expected_moves.emplace(Move(f5.index, g6.index, Move::Type::capture));
// h5 bishop
expected_moves.emplace(Move(h5.index, g6.index, Move::Type::normal));
expected_moves.emplace(Move(h5.index, f7.index, Move::Type::capture));
// d7 pawn
for (Move::Type type: {Move::Type::promotion_knight,
Move::Type::promotion_bishop,
Move::Type::promotion_rook,
Move::Type::promotion_queen}) {
expected_moves.emplace(Move(d7.index, d8.index, type));
}
for (Move::Type type: {Move::Type::capturing_promotion_knight,
Move::Type::capturing_promotion_bishop,
Move::Type::capturing_promotion_rook,
Move::Type::capturing_promotion_queen}) {
expected_moves.emplace(Move(d7.index, c8.index, type));
}
const std::vector<Move> moves = state.moves();
const std::set<Move> actual_moves(moves.begin(), moves.end());
std::set<Move> falsenegatives, falsepositives;
std::set_difference(expected_moves.begin(), expected_moves.end(),
actual_moves.begin(), actual_moves.end(),
std::inserter(falsenegatives, falsenegatives.begin()));
std::set_difference(actual_moves.begin(), actual_moves.end(),
expected_moves.begin(), expected_moves.end(),
std::inserter(falsepositives, falsepositives.begin()));
BOOST_CHECK_MESSAGE(falsenegatives.empty(), "legal moves not generated: " << falsenegatives);
BOOST_CHECK_MESSAGE(falsepositives.empty(), "illegal moves generated: " << falsepositives);
}
BOOST_AUTO_TEST_CASE(_moves) {
State state;
state.make_moves("e4 e5 Nf3 Nc6 Bc4 Bc5 b4 Bxb4 c3 Ba5 d4 exd4 0-0 d3 Qb3 Qf6"
"e5 Qg6 Re1 Nge7 Ba3 b5 Qxb5 Rb8 Qa4 Bb6 Nbd2 Bb7 Ne4 Qf5"
"Bxd3 Qh5 Nf6+ gxf6 18.exf6 Rg8 19.Rad1 Qxf3 20.Rxe7+ Nxe7"
"21.Qxd7+ Kxd7 22.Bf5+ Ke8 23.Bd7+ Kf8");
BOOST_CHECK(true);
}
<|endoftext|> |
<commit_before>/* Portions copyright (c) 2014 Stanford University and the Authors.
Authors: Chris Dembia, Michael Sherman
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. */
#include "drake/common/nice_type_name.h"
#include <algorithm>
#include <array>
#include <cstdlib>
#include <regex>
#include <string>
using std::string;
// __GNUG__ is defined both for gcc and clang. See:
// https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html
#if defined(__GNUG__)
#include <cxxabi.h>
#include <cstdlib>
#endif
// On gcc and clang typeid(T).name() returns an indecipherable mangled string
// that requires processing to become human readable. Microsoft returns a
// reasonable name directly.
string drake::common::DemangleTypeName(const char* typeid_name) {
#if defined(__GNUG__)
int status=-100; // just in case it doesn't get set
char* ret = abi::__cxa_demangle(typeid_name, NULL, NULL, &status);
const char* const demangled_name = (status == 0) ? ret : typeid_name;
string demangled_string(demangled_name);
if (ret) std::free(ret);
return demangled_string;
#else
// On other platforms, we hope the typeid name is not mangled.
return typeid_name;
#endif
}
// Given a demangled string, attempt to canonicalize it for platform
// indpendence. We'll remove Microsoft's "class ", "struct ", etc.
// designations, and get rid of all unnecessary spaces.
string drake::common::CanonicalizeTypeName(string&& demangled) {
using SPair = std::pair<std::regex,string>;
// These are applied in this order.
static const std::array<SPair,7> subs{
// Remove unwanted keywords and following space.
SPair(std::regex("\\b(class|struct|enum|union) "), ""),
// Tidy up anonymous namespace.
SPair(std::regex("[`(]anonymous namespace[')]"), "(anonymous)"),
// Replace Microsoft __int64 with long long.
SPair(std::regex("\\b__int64\\b"), "long long"),
// Temporarily replace spaces we want to keep with "!". (\w is
// alphanumeric or underscore.)
SPair(std::regex("(\\w) (\\w)"), "$1!$2"),
SPair(std::regex(" "), ""), // Delete unwanted spaces.
// OSX clang throws in extra namespaces like "__1". Delete them.
SPair(std::regex("\\b__[0-9]+::"), ""),
SPair(std::regex("!"), " ") // Restore wanted spaces.
};
string canonical(std::move(demangled));
for (const auto& sp : subs) {
canonical = std::regex_replace(canonical, sp.first, sp.second);
}
return canonical;
}
<commit_msg>Remove unnecessary include.<commit_after>/* Portions copyright (c) 2014 Stanford University and the Authors.
Authors: Chris Dembia, Michael Sherman
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. */
#include "drake/common/nice_type_name.h"
#include <algorithm>
#include <array>
#include <regex>
#include <string>
using std::string;
// __GNUG__ is defined both for gcc and clang. See:
// https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html
#if defined(__GNUG__)
#include <cxxabi.h>
#include <cstdlib>
#endif
// On gcc and clang typeid(T).name() returns an indecipherable mangled string
// that requires processing to become human readable. Microsoft returns a
// reasonable name directly.
string drake::common::DemangleTypeName(const char* typeid_name) {
#if defined(__GNUG__)
int status=-100; // just in case it doesn't get set
char* ret = abi::__cxa_demangle(typeid_name, NULL, NULL, &status);
const char* const demangled_name = (status == 0) ? ret : typeid_name;
string demangled_string(demangled_name);
if (ret) std::free(ret);
return demangled_string;
#else
// On other platforms, we hope the typeid name is not mangled.
return typeid_name;
#endif
}
// Given a demangled string, attempt to canonicalize it for platform
// indpendence. We'll remove Microsoft's "class ", "struct ", etc.
// designations, and get rid of all unnecessary spaces.
string drake::common::CanonicalizeTypeName(string&& demangled) {
using SPair = std::pair<std::regex,string>;
// These are applied in this order.
static const std::array<SPair,7> subs{
// Remove unwanted keywords and following space.
SPair(std::regex("\\b(class|struct|enum|union) "), ""),
// Tidy up anonymous namespace.
SPair(std::regex("[`(]anonymous namespace[')]"), "(anonymous)"),
// Replace Microsoft __int64 with long long.
SPair(std::regex("\\b__int64\\b"), "long long"),
// Temporarily replace spaces we want to keep with "!". (\w is
// alphanumeric or underscore.)
SPair(std::regex("(\\w) (\\w)"), "$1!$2"),
SPair(std::regex(" "), ""), // Delete unwanted spaces.
// OSX clang throws in extra namespaces like "__1". Delete them.
SPair(std::regex("\\b__[0-9]+::"), ""),
SPair(std::regex("!"), " ") // Restore wanted spaces.
};
string canonical(std::move(demangled));
for (const auto& sp : subs) {
canonical = std::regex_replace(canonical, sp.first, sp.second);
}
return canonical;
}
<|endoftext|> |
<commit_before>// Initial version copied from Initial version copied from https://github.com/JetBrains/intellij-community/blob/master/native/WinFsNotifier/fileWatcher3.c
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
#ifdef _WIN32
#include "native.h"
#include "generic.h"
#include "win.h"
JavaVM* jvm = NULL;
typedef struct watch_details {
HANDLE threadHandle;
HANDLE stopEventHandle;
wchar_t drivePath[4];
int watchedPathCount;
wchar_t **watchedPaths;
jobject watcherCallback;
} watch_details_t;
// TODO Find the right size for this
#define EVENT_BUFFER_SIZE (16*1024)
#define CREATE_SHARE (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
#define CREATE_FLAGS (FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED)
#define EVENT_MASK (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \
FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE)
void reportEvent(jint type, wchar_t *changedPath, int changedPathLen, watch_details_t *details) {
JNIEnv* env;
int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
if (getEnvStat == JNI_EDETACHED) {
int attachThreadStat = jvm->AttachCurrentThread((void **) &env, NULL);
if (attachThreadStat != JNI_OK) {
printf("~~~~ Problem with AttachCurrentThread: %d\n", attachThreadStat);
// TODO Error handling
return;
}
} else if (getEnvStat == JNI_EVERSION) {
printf("~~~~ Problem with GetEnv: %d\n", getEnvStat);
// TODO Error handling
return;
}
jobject watcherCallback = details->watcherCallback;
jstring changedPathJava = wchar_to_java(env, changedPath, changedPathLen, NULL);
jclass callback_class = env->GetObjectClass(watcherCallback);
jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V");
// TODO Do we need to add a global reference to the string here?
env->CallVoidMethod(watcherCallback, methodCallback, type, changedPathJava);
}
void handlePathChanged(watch_details_t *details, FILE_NOTIFY_INFORMATION *info) {
int pathLen = info->FileNameLength / sizeof(wchar_t);
wchar_t *changedPath = add_prefix(info->FileName, pathLen, details->drivePath);
int changedPathLen = pathLen + 3;
wprintf(L"~~~~ Changed: 0x%x %ls\n", info->Action, changedPath);
jint type;
if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
type = FILE_EVENT_CREATED;
} else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
type = FILE_EVENT_REMOVED;
} else if (info->Action == FILE_ACTION_MODIFIED) {
type = FILE_EVENT_MODIFIED;
} else {
wprintf(L"~~~~ Unknown event 0x%x for %ls\n", info->Action, changedPath);
type = FILE_EVENT_UNKNOWN;
}
bool watching = false;
for (int i = 0; i < details->watchedPathCount; i++) {
wchar_t* watchedPath = details->watchedPaths[i];
if (wcsncmp(watchedPath, changedPath, wcslen(watchedPath)) == 0) {
watching = true;
break;
}
}
if (!watching) {
wprintf(L"~~~~ Ignoring %ls (root is not watched)\n", changedPath);
return;
}
reportEvent(type, changedPath, changedPathLen, details);
free(changedPath);
}
DWORD WINAPI EventProcessingThread(LPVOID data) {
watch_details_t *details = (watch_details_t*) data;
printf("~~~~ Starting thread\n");
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE hDrive = CreateFileW(details->drivePath, GENERIC_READ, CREATE_SHARE, NULL, OPEN_EXISTING, CREATE_FLAGS, NULL);
char buffer[EVENT_BUFFER_SIZE];
HANDLE handles[2] = {details->stopEventHandle, overlapped.hEvent};
while (true) {
int rcDrive = ReadDirectoryChangesW(hDrive, buffer, sizeof(buffer), TRUE, EVENT_MASK, NULL, &overlapped, NULL);
if (rcDrive == 0) {
// TODO Error handling
printf("~~~~ Couldn't read directory: %d - %d\n", rcDrive, GetLastError());
break;
}
DWORD rc = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
if (rc == WAIT_OBJECT_0) {
break;
}
if (rc == WAIT_OBJECT_0 + 1) {
DWORD dwBytesReturned;
if (!GetOverlappedResult(hDrive, &overlapped, &dwBytesReturned, FALSE)) {
// TODO Error handling
printf("~~~~ Failed to wait\n");
break;
}
if (dwBytesReturned == 0) {
// don't send dirty too much, everything is changed anyway
// TODO Understand what this does
if (WaitForSingleObject(details->stopEventHandle, 500) == WAIT_OBJECT_0)
break;
// Got a buffer overflow => current changes lost => send INVALIDATE on root
reportEvent(FILE_EVENT_INVALIDATE, details->drivePath, 3, details);
} else {
FILE_NOTIFY_INFORMATION *info = (FILE_NOTIFY_INFORMATION *)buffer;
do {
handlePathChanged(details, info);
info = (FILE_NOTIFY_INFORMATION *)((char *)info + info->NextEntryOffset);
} while (info->NextEntryOffset != 0);
}
}
}
printf("~~~~ Stopping thread\n");
CloseHandle(overlapped.hEvent);
CloseHandle(hDrive);
return 0;
}
JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) {
printf("\n~~~~ Configuring...\n");
// TODO Should this be somewhere global?
int jvmStatus = env->GetJavaVM(&jvm);
if (jvmStatus < 0) {
mark_failed_with_errno(env, "Could not store jvm instance.", result);
return NULL;
}
int watchedPathCount = env->GetArrayLength(paths);
if (watchedPathCount == 0) {
mark_failed_with_errno(env, "No paths given to watch.", result);
return NULL;
}
wchar_t **watchedPaths = (wchar_t**)malloc(watchedPathCount * sizeof(wchar_t*));
wchar_t driveLetter = L'\0';
for (int i = 0; i < watchedPathCount; i++) {
jstring path = (jstring) env->GetObjectArrayElement(paths, i);
wchar_t* watchedPath = java_to_wchar_path(env, path, result);
int watchedPathLen = wcslen(watchedPath);
if (watchedPathLen > 240 || watchedPath[0] == L'\\') {
mark_failed_with_errno(env, "Cannot watch long paths for now.", result);
return NULL;
}
if (driveLetter == L'\0') {
driveLetter = watchedPath[0];
} else if (driveLetter != watchedPath[0]) {
mark_failed_with_errno(env, "Cannot watch multiple drives for now.", result);
return NULL;
}
if (watchedPath[watchedPathLen - 1] != L'\\') {
wchar_t* oldWatchedPath = watchedPath;
watchedPath = add_suffix(watchedPath, watchedPathLen, L"\\");
free(oldWatchedPath);
}
wprintf(L"~~~~ Watching %ls\n", watchedPath);
watchedPaths[i] = watchedPath;
}
wchar_t drivePath[4] = {towupper(watchedPaths[0][0]), L':', L'\\', L'\0'};
watch_details_t* details = (watch_details_t*)malloc(sizeof(watch_details_t));
details->watcherCallback = env->NewGlobalRef(javaCallback);
details->stopEventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
details->watchedPathCount = watchedPathCount;
details->watchedPaths = watchedPaths;
wcscpy_s(details->drivePath, 4, drivePath);
details->threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
EventProcessingThread, // thread function name
details, // argument to thread function
0, // use default creation flags
NULL // the thread identifier
);
SetThreadPriority(details->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl");
jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V");
return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(details, sizeof(details)));
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {
watch_details_t* details = (watch_details_t*)env->GetDirectBufferAddress(detailsObj);
SetEvent(details->stopEventHandle);
WaitForSingleObject(details->threadHandle, INFINITE);
CloseHandle(details->threadHandle);
CloseHandle(details->stopEventHandle);
for (int i = 0; i < details->watchedPathCount; i++) {
free(details->watchedPaths[i]);
}
free(details->watchedPaths);
env->DeleteGlobalRef(details->watcherCallback);
free(details);
}
#endif
<commit_msg>Store JNI environment in details (Win)<commit_after>// Initial version copied from Initial version copied from https://github.com/JetBrains/intellij-community/blob/master/native/WinFsNotifier/fileWatcher3.c
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
#ifdef _WIN32
#include "native.h"
#include "generic.h"
#include "win.h"
typedef struct watch_details {
HANDLE threadHandle;
HANDLE stopEventHandle;
JavaVM *jvm;
JNIEnv *env;
wchar_t drivePath[4];
int watchedPathCount;
wchar_t **watchedPaths;
jobject watcherCallback;
} watch_details_t;
// TODO Find the right size for this
#define EVENT_BUFFER_SIZE (16*1024)
#define CREATE_SHARE (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
#define CREATE_FLAGS (FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED)
#define EVENT_MASK (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \
FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE)
void reportEvent(jint type, wchar_t *changedPath, int changedPathLen, watch_details_t *details) {
JNIEnv *env = details->env;
jobject watcherCallback = details->watcherCallback;
jstring changedPathJava = wchar_to_java(env, changedPath, changedPathLen, NULL);
jclass callback_class = env->GetObjectClass(watcherCallback);
jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V");
// TODO Do we need to add a global reference to the string here?
env->CallVoidMethod(watcherCallback, methodCallback, type, changedPathJava);
}
void handlePathChanged(watch_details_t *details, FILE_NOTIFY_INFORMATION *info) {
int pathLen = info->FileNameLength / sizeof(wchar_t);
wchar_t *changedPath = add_prefix(info->FileName, pathLen, details->drivePath);
int changedPathLen = pathLen + 3;
wprintf(L"~~~~ Changed: 0x%x %ls\n", info->Action, changedPath);
jint type;
if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
type = FILE_EVENT_CREATED;
} else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
type = FILE_EVENT_REMOVED;
} else if (info->Action == FILE_ACTION_MODIFIED) {
type = FILE_EVENT_MODIFIED;
} else {
wprintf(L"~~~~ Unknown event 0x%x for %ls\n", info->Action, changedPath);
type = FILE_EVENT_UNKNOWN;
}
bool watching = false;
for (int i = 0; i < details->watchedPathCount; i++) {
wchar_t* watchedPath = details->watchedPaths[i];
if (wcsncmp(watchedPath, changedPath, wcslen(watchedPath)) == 0) {
watching = true;
break;
}
}
if (!watching) {
wprintf(L"~~~~ Ignoring %ls (root is not watched)\n", changedPath);
return;
}
reportEvent(type, changedPath, changedPathLen, details);
free(changedPath);
}
DWORD WINAPI EventProcessingThread(LPVOID data) {
watch_details_t *details = (watch_details_t*) data;
printf("~~~~ Starting thread\n");
// TODO Extract this logic to some shared function
JavaVM* jvm = details->jvm;
jint statAttach = jvm->AttachCurrentThreadAsDaemon((void **) &(details->env), NULL);
if (statAttach != JNI_OK) {
printf("Failed to attach JNI to current thread: %d\n", statAttach);
return 0;
}
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE hDrive = CreateFileW(details->drivePath, GENERIC_READ, CREATE_SHARE, NULL, OPEN_EXISTING, CREATE_FLAGS, NULL);
char buffer[EVENT_BUFFER_SIZE];
HANDLE handles[2] = {details->stopEventHandle, overlapped.hEvent};
while (true) {
int rcDrive = ReadDirectoryChangesW(hDrive, buffer, sizeof(buffer), TRUE, EVENT_MASK, NULL, &overlapped, NULL);
if (rcDrive == 0) {
// TODO Error handling
printf("~~~~ Couldn't read directory: %d - %d\n", rcDrive, GetLastError());
break;
}
DWORD rc = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
if (rc == WAIT_OBJECT_0) {
break;
}
if (rc == WAIT_OBJECT_0 + 1) {
DWORD dwBytesReturned;
if (!GetOverlappedResult(hDrive, &overlapped, &dwBytesReturned, FALSE)) {
// TODO Error handling
printf("~~~~ Failed to wait\n");
break;
}
if (dwBytesReturned == 0) {
// don't send dirty too much, everything is changed anyway
// TODO Understand what this does
if (WaitForSingleObject(details->stopEventHandle, 500) == WAIT_OBJECT_0)
break;
// Got a buffer overflow => current changes lost => send INVALIDATE on root
reportEvent(FILE_EVENT_INVALIDATE, details->drivePath, 3, details);
} else {
FILE_NOTIFY_INFORMATION *info = (FILE_NOTIFY_INFORMATION *)buffer;
do {
handlePathChanged(details, info);
info = (FILE_NOTIFY_INFORMATION *)((char *)info + info->NextEntryOffset);
} while (info->NextEntryOffset != 0);
}
}
}
printf("~~~~ Stopping thread\n");
CloseHandle(overlapped.hEvent);
CloseHandle(hDrive);
// TODO Extract this logic to some shared function
jint statDetach = jvm->DetachCurrentThread();
if (statDetach != JNI_OK) {
printf("Failed to detach JNI from current thread: %d\n", statAttach);
return 0;
}
return 0;
}
JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) {
printf("\n~~~~ Configuring...\n");
JavaVM* jvm;
int jvmStatus = env->GetJavaVM(&jvm);
if (jvmStatus != JNI_OK) {
mark_failed_with_errno(env, "Could not store jvm instance.", result);
return NULL;
}
int watchedPathCount = env->GetArrayLength(paths);
if (watchedPathCount == 0) {
mark_failed_with_errno(env, "No paths given to watch.", result);
return NULL;
}
wchar_t **watchedPaths = (wchar_t**)malloc(watchedPathCount * sizeof(wchar_t*));
wchar_t driveLetter = L'\0';
for (int i = 0; i < watchedPathCount; i++) {
jstring path = (jstring) env->GetObjectArrayElement(paths, i);
wchar_t* watchedPath = java_to_wchar_path(env, path, result);
int watchedPathLen = wcslen(watchedPath);
if (watchedPathLen > 240 || watchedPath[0] == L'\\') {
mark_failed_with_errno(env, "Cannot watch long paths for now.", result);
return NULL;
}
if (driveLetter == L'\0') {
driveLetter = watchedPath[0];
} else if (driveLetter != watchedPath[0]) {
mark_failed_with_errno(env, "Cannot watch multiple drives for now.", result);
return NULL;
}
if (watchedPath[watchedPathLen - 1] != L'\\') {
wchar_t* oldWatchedPath = watchedPath;
watchedPath = add_suffix(watchedPath, watchedPathLen, L"\\");
free(oldWatchedPath);
}
wprintf(L"~~~~ Watching %ls\n", watchedPath);
watchedPaths[i] = watchedPath;
}
wchar_t drivePath[4] = {towupper(watchedPaths[0][0]), L':', L'\\', L'\0'};
watch_details_t* details = (watch_details_t*)malloc(sizeof(watch_details_t));
details->watcherCallback = env->NewGlobalRef(javaCallback);
details->stopEventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
details->jvm = jvm;
details->watchedPathCount = watchedPathCount;
details->watchedPaths = watchedPaths;
wcscpy_s(details->drivePath, 4, drivePath);
details->threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
EventProcessingThread, // thread function name
details, // argument to thread function
0, // use default creation flags
NULL // the thread identifier
);
SetThreadPriority(details->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl");
jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V");
return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(details, sizeof(details)));
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {
watch_details_t* details = (watch_details_t*)env->GetDirectBufferAddress(detailsObj);
SetEvent(details->stopEventHandle);
WaitForSingleObject(details->threadHandle, INFINITE);
CloseHandle(details->threadHandle);
CloseHandle(details->stopEventHandle);
for (int i = 0; i < details->watchedPathCount; i++) {
free(details->watchedPaths[i]);
}
free(details->watchedPaths);
env->DeleteGlobalRef(details->watcherCallback);
free(details);
}
#endif
<|endoftext|> |
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // HAVE_CMAKE_CONFIG
#include <utility>
#include <dune/stuff/test/test_common.hh>
#include <dune/common/float_cmp.hh>
#include <dune/common/typetraits.hh>
#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/la/container/dunedynamic.hh>
#include <dune/pymor/functionals/interfaces.hh>
#include <dune/pymor/functionals/default.hh>
#include <dune/pymor/functionals/affine.hh>
using namespace Dune;
using namespace Dune::Pymor;
typedef testing::Types<
LA::DuneDynamicVector< double >
> VectorTypes;
static const size_t dim = 4;
template< class VectorType >
struct VectorBasedTest
: public ::testing::Test
{
void check() const
{
// static tests
typedef Functionals::VectorBased< VectorType > FunctionalType;
typedef typename FunctionalType::Traits Traits;
// * of the traits
typedef typename Traits::derived_type T_derived_type;
static_assert(std::is_same< FunctionalType, T_derived_type >::value,
"FunctionalType::Traits::derived_type is wrong!");
typedef typename Traits::SourceType T_SourceType;
typedef typename Traits::ScalarType T_ScalarType;
typedef typename Traits::FrozenType T_FrozenType;
// * of the class itself (aka the derived type)
typedef typename FunctionalType::SourceType D_SourceType;
typedef typename FunctionalType::ScalarType D_ScalarType;
typedef typename FunctionalType::ContainerType D_ContainerType;
typedef typename FunctionalType::FrozenType D_FrozenType;
static_assert(std::is_same< D_ContainerType, VectorType >::value,
"FunctionalType::ContainerType is wrong!");
// * of the class as the interface
typedef FunctionalInterface< Traits > InterfaceType;
typedef typename InterfaceType::SourceType I_SourceType;
typedef typename InterfaceType::ScalarType I_ScalarType;
typedef typename InterfaceType::FrozenType I_FrozenType;
// dynamic tests
// * of the class itself (aka the derived type)
const FunctionalType d_from_ptr(new VectorType(dim, D_ScalarType(1)));
FunctionalType d_from_shared_ptr(std::make_shared< VectorType >(dim));
d_from_shared_ptr = d_from_ptr;
FunctionalType DUNE_UNUSED(d_copy_constructor)(d_from_ptr); // <- at this point, all functionals share the same vector!
const bool d_linear = d_from_ptr.linear();
if (!d_linear) DUNE_PYMOR_THROW(PymorException, "");
const unsigned int d_dim_source = d_from_ptr.dim_source();
if (d_dim_source != dim) DUNE_PYMOR_THROW(PymorException, d_dim_source);
const VectorType source(dim, D_ScalarType(1));
const D_ScalarType d_apply = d_from_ptr.apply(source);
if (d_apply != dim) DUNE_PYMOR_THROW(PymorException, d_apply);
// * of the class as the interface
const InterfaceType& i_from_ptr = static_cast< const InterfaceType& >(d_from_ptr);
const bool i_linear = i_from_ptr.linear();
if (!i_linear) DUNE_PYMOR_THROW(PymorException, "");
const unsigned int i_dim_source = i_from_ptr.dim_source();
if (i_dim_source != dim) DUNE_PYMOR_THROW(PymorException, i_dim_source);
const I_ScalarType i_apply = i_from_ptr.apply(source);
if (i_apply != dim) DUNE_PYMOR_THROW(PymorException, i_apply);
}
}; // struct VectorBasedTest
TYPED_TEST_CASE(VectorBasedTest, VectorTypes);
TYPED_TEST(VectorBasedTest, FUNCTIONALS) {
this->check();
}
template< class VectorType >
struct LinearAffinelyDecomposedVectorBasedTest
: public ::testing::Test
{
void check() const
{
// static tests
typedef Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
typedef typename FunctionalType::Traits Traits;
// * of the traits
typedef typename Traits::derived_type T_derived_type;
static_assert(std::is_same< FunctionalType, T_derived_type >::value,
"FunctionalType::Traits::derived_type is wrong!");
typedef typename Traits::ComponentType ComponentType;
// * of the class itself (aka the derived type)
typedef typename FunctionalType::ComponentType D_ComponentType;
typedef typename FunctionalType::FrozenType D_FrozenType;
typedef typename FunctionalType::ScalarType D_ScalarType;
typedef typename FunctionalType::AffinelyDecomposedVectorType D_AffinelyDecomposedVectorType;
// * of the class as the interface
typedef AffinelyDecomposedFunctionalInterface< Traits > InterfaceType;
typedef typename InterfaceType::derived_type I_derived_type;
static_assert(std::is_same< FunctionalType, I_derived_type >::value,
"InterfaceType::derived_type is wrong!");
typedef typename InterfaceType::ComponentType I_ComponentType;
typedef typename InterfaceType::FrozenType I_FrozenType;
typedef typename InterfaceType::ScalarType I_ScalarType;
// dynamic tests
// * of the class itself (aka the derived type)
D_AffinelyDecomposedVectorType affinelyDecomposedVector(new VectorType(dim, 1));
affinelyDecomposedVector.register_component(new VectorType(dim, 1),
new ParameterFunctional("diffusion", 1, "diffusion[0]"));
affinelyDecomposedVector.register_component(new VectorType(dim, 1),
new ParameterFunctional("force", 2, "force[0]"));
const Parameter mu = {{"diffusion", "force"},
{{1.0}, {1.0, 1.0}}};
if (affinelyDecomposedVector.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\naffinelyDecomposedVector.parameter_type() = "
<< affinelyDecomposedVector.parameter_type());
FunctionalType d_functional(affinelyDecomposedVector);
if (!d_functional.parametric()) DUNE_PYMOR_THROW(PymorException, "");
if (d_functional.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\n.parameter_type() = " << d_functional.parameter_type());
const unsigned int d_num_components = d_functional.num_components();
if (d_num_components != 2) DUNE_PYMOR_THROW(PymorException, d_num_components);
for (unsigned int qq = 0; qq < d_num_components; ++qq) {
D_ComponentType component = d_functional.component(qq);
if (component.parametric()) DUNE_PYMOR_THROW(PymorException, "");
ParameterFunctional DUNE_UNUSED(coefficient) = d_functional.coefficient(qq);
}
if (!d_functional.has_affine_part()) DUNE_PYMOR_THROW(PymorException, "");
D_ComponentType d_affine_part = d_functional.affine_part();
if (d_affine_part.parametric()) DUNE_PYMOR_THROW(PymorException, "");
D_FrozenType d_frozen = d_functional.freeze_parameter(mu);
if (d_frozen.parametric()) DUNE_PYMOR_THROW(PymorException, "");
VectorType source(dim, D_ScalarType(1));
D_ScalarType d_apply = d_functional.apply(source, mu);
D_ScalarType d_frozen_apply = d_frozen.apply(source);
if (d_apply != d_frozen_apply)
DUNE_PYMOR_THROW(PymorException, "\nd_apply = " << d_apply << "\nd_frozen_apply = " << d_frozen_apply);
// * of the class as the interface
InterfaceType& i_functional = static_cast< InterfaceType& >(d_functional);
if (!i_functional.parametric()) DUNE_PYMOR_THROW(PymorException, "");
if (i_functional.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\n.parameter_type() = " << i_functional.parameter_type());
const unsigned int i_num_components = i_functional.num_components();
if (i_num_components != 2) DUNE_PYMOR_THROW(PymorException, i_num_components);
for (unsigned int qq = 0; qq < i_num_components; ++qq) {
I_ComponentType component = i_functional.component(qq);
if (component.parametric()) DUNE_PYMOR_THROW(PymorException, "");
ParameterFunctional DUNE_UNUSED(coefficient) = i_functional.coefficient(qq);
}
if (!i_functional.has_affine_part()) DUNE_PYMOR_THROW(PymorException, "");
I_ComponentType i_affine_part = d_functional.affine_part();
if (i_affine_part.parametric()) DUNE_PYMOR_THROW(PymorException, "");
I_FrozenType i_frozen = i_functional.freeze_parameter(mu);
if (i_frozen.parametric()) DUNE_PYMOR_THROW(PymorException, "");
I_ScalarType i_apply = i_functional.apply(source, mu);
I_ScalarType i_frozen_apply = i_frozen.apply(source);
if (i_apply != i_frozen_apply)
DUNE_PYMOR_THROW(PymorException, "\ni_apply = " << i_apply << "\ni_frozen_apply = " << i_frozen_apply);
}
}; // struct LinearAffinelyDecomposedVectorBasedTest
TYPED_TEST_CASE(LinearAffinelyDecomposedVectorBasedTest, VectorTypes);
TYPED_TEST(LinearAffinelyDecomposedVectorBasedTest, FUNCTIONALS) {
this->check();
}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::PymorException &e) {
std::cerr << Dune::Stuff::Common::colorStringRed("dune-pymor reported: ") << e << std::endl;
} catch (Dune::Exception &e) {
std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl;
} catch (...) {
std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl;
}
}
<commit_msg>[test.functionsl] added Eigen container<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // HAVE_CMAKE_CONFIG
#include <utility>
#include <dune/stuff/test/test_common.hh>
#include <dune/common/float_cmp.hh>
#include <dune/common/typetraits.hh>
#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/la/container/dunedynamic.hh>
#include <dune/pymor/la/container/eigen.hh>
#include <dune/pymor/functionals/interfaces.hh>
#include <dune/pymor/functionals/default.hh>
#include <dune/pymor/functionals/affine.hh>
using namespace Dune;
using namespace Dune::Pymor;
typedef testing::Types<
LA::DuneDynamicVector< double >
#if HAVE_EIGEN
, LA::EigenDenseVector< double >
#endif
> VectorTypes;
static const size_t dim = 4;
template< class VectorType >
struct VectorBasedTest
: public ::testing::Test
{
void check() const
{
// static tests
typedef Functionals::VectorBased< VectorType > FunctionalType;
typedef typename FunctionalType::Traits Traits;
// * of the traits
typedef typename Traits::derived_type T_derived_type;
static_assert(std::is_same< FunctionalType, T_derived_type >::value,
"FunctionalType::Traits::derived_type is wrong!");
typedef typename Traits::SourceType T_SourceType;
typedef typename Traits::ScalarType T_ScalarType;
typedef typename Traits::FrozenType T_FrozenType;
// * of the class itself (aka the derived type)
typedef typename FunctionalType::SourceType D_SourceType;
typedef typename FunctionalType::ScalarType D_ScalarType;
typedef typename FunctionalType::ContainerType D_ContainerType;
typedef typename FunctionalType::FrozenType D_FrozenType;
static_assert(std::is_same< D_ContainerType, VectorType >::value,
"FunctionalType::ContainerType is wrong!");
// * of the class as the interface
typedef FunctionalInterface< Traits > InterfaceType;
typedef typename InterfaceType::SourceType I_SourceType;
typedef typename InterfaceType::ScalarType I_ScalarType;
typedef typename InterfaceType::FrozenType I_FrozenType;
// dynamic tests
// * of the class itself (aka the derived type)
const FunctionalType d_from_ptr(new VectorType(dim, D_ScalarType(1)));
FunctionalType d_from_shared_ptr(std::make_shared< VectorType >(dim));
d_from_shared_ptr = d_from_ptr;
FunctionalType DUNE_UNUSED(d_copy_constructor)(d_from_ptr); // <- at this point, all functionals share the same vector!
const bool d_linear = d_from_ptr.linear();
if (!d_linear) DUNE_PYMOR_THROW(PymorException, "");
const unsigned int d_dim_source = d_from_ptr.dim_source();
if (d_dim_source != dim) DUNE_PYMOR_THROW(PymorException, d_dim_source);
const VectorType source(dim, D_ScalarType(1));
const D_ScalarType d_apply = d_from_ptr.apply(source);
if (d_apply != dim) DUNE_PYMOR_THROW(PymorException, d_apply);
// * of the class as the interface
const InterfaceType& i_from_ptr = static_cast< const InterfaceType& >(d_from_ptr);
const bool i_linear = i_from_ptr.linear();
if (!i_linear) DUNE_PYMOR_THROW(PymorException, "");
const unsigned int i_dim_source = i_from_ptr.dim_source();
if (i_dim_source != dim) DUNE_PYMOR_THROW(PymorException, i_dim_source);
const I_ScalarType i_apply = i_from_ptr.apply(source);
if (i_apply != dim) DUNE_PYMOR_THROW(PymorException, i_apply);
}
}; // struct VectorBasedTest
TYPED_TEST_CASE(VectorBasedTest, VectorTypes);
TYPED_TEST(VectorBasedTest, FUNCTIONALS) {
this->check();
}
template< class VectorType >
struct LinearAffinelyDecomposedVectorBasedTest
: public ::testing::Test
{
void check() const
{
// static tests
typedef Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
typedef typename FunctionalType::Traits Traits;
// * of the traits
typedef typename Traits::derived_type T_derived_type;
static_assert(std::is_same< FunctionalType, T_derived_type >::value,
"FunctionalType::Traits::derived_type is wrong!");
typedef typename Traits::ComponentType ComponentType;
// * of the class itself (aka the derived type)
typedef typename FunctionalType::ComponentType D_ComponentType;
typedef typename FunctionalType::FrozenType D_FrozenType;
typedef typename FunctionalType::ScalarType D_ScalarType;
typedef typename FunctionalType::AffinelyDecomposedVectorType D_AffinelyDecomposedVectorType;
// * of the class as the interface
typedef AffinelyDecomposedFunctionalInterface< Traits > InterfaceType;
typedef typename InterfaceType::derived_type I_derived_type;
static_assert(std::is_same< FunctionalType, I_derived_type >::value,
"InterfaceType::derived_type is wrong!");
typedef typename InterfaceType::ComponentType I_ComponentType;
typedef typename InterfaceType::FrozenType I_FrozenType;
typedef typename InterfaceType::ScalarType I_ScalarType;
// dynamic tests
// * of the class itself (aka the derived type)
D_AffinelyDecomposedVectorType affinelyDecomposedVector(new VectorType(dim, 1));
affinelyDecomposedVector.register_component(new VectorType(dim, 1),
new ParameterFunctional("diffusion", 1, "diffusion[0]"));
affinelyDecomposedVector.register_component(new VectorType(dim, 1),
new ParameterFunctional("force", 2, "force[0]"));
const Parameter mu = {{"diffusion", "force"},
{{1.0}, {1.0, 1.0}}};
if (affinelyDecomposedVector.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\naffinelyDecomposedVector.parameter_type() = "
<< affinelyDecomposedVector.parameter_type());
FunctionalType d_functional(affinelyDecomposedVector);
if (!d_functional.parametric()) DUNE_PYMOR_THROW(PymorException, "");
if (d_functional.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\n.parameter_type() = " << d_functional.parameter_type());
const unsigned int d_num_components = d_functional.num_components();
if (d_num_components != 2) DUNE_PYMOR_THROW(PymorException, d_num_components);
for (unsigned int qq = 0; qq < d_num_components; ++qq) {
D_ComponentType component = d_functional.component(qq);
if (component.parametric()) DUNE_PYMOR_THROW(PymorException, "");
ParameterFunctional DUNE_UNUSED(coefficient) = d_functional.coefficient(qq);
}
if (!d_functional.has_affine_part()) DUNE_PYMOR_THROW(PymorException, "");
D_ComponentType d_affine_part = d_functional.affine_part();
if (d_affine_part.parametric()) DUNE_PYMOR_THROW(PymorException, "");
D_FrozenType d_frozen = d_functional.freeze_parameter(mu);
if (d_frozen.parametric()) DUNE_PYMOR_THROW(PymorException, "");
VectorType source(dim, D_ScalarType(1));
D_ScalarType d_apply = d_functional.apply(source, mu);
D_ScalarType d_frozen_apply = d_frozen.apply(source);
if (d_apply != d_frozen_apply)
DUNE_PYMOR_THROW(PymorException, "\nd_apply = " << d_apply << "\nd_frozen_apply = " << d_frozen_apply);
// * of the class as the interface
InterfaceType& i_functional = static_cast< InterfaceType& >(d_functional);
if (!i_functional.parametric()) DUNE_PYMOR_THROW(PymorException, "");
if (i_functional.parameter_type() != mu.type())
DUNE_PYMOR_THROW(PymorException,
"\nmu.type() = " << mu.type()
<< "\n.parameter_type() = " << i_functional.parameter_type());
const unsigned int i_num_components = i_functional.num_components();
if (i_num_components != 2) DUNE_PYMOR_THROW(PymorException, i_num_components);
for (unsigned int qq = 0; qq < i_num_components; ++qq) {
I_ComponentType component = i_functional.component(qq);
if (component.parametric()) DUNE_PYMOR_THROW(PymorException, "");
ParameterFunctional DUNE_UNUSED(coefficient) = i_functional.coefficient(qq);
}
if (!i_functional.has_affine_part()) DUNE_PYMOR_THROW(PymorException, "");
I_ComponentType i_affine_part = d_functional.affine_part();
if (i_affine_part.parametric()) DUNE_PYMOR_THROW(PymorException, "");
I_FrozenType i_frozen = i_functional.freeze_parameter(mu);
if (i_frozen.parametric()) DUNE_PYMOR_THROW(PymorException, "");
I_ScalarType i_apply = i_functional.apply(source, mu);
I_ScalarType i_frozen_apply = i_frozen.apply(source);
if (i_apply != i_frozen_apply)
DUNE_PYMOR_THROW(PymorException, "\ni_apply = " << i_apply << "\ni_frozen_apply = " << i_frozen_apply);
}
}; // struct LinearAffinelyDecomposedVectorBasedTest
TYPED_TEST_CASE(LinearAffinelyDecomposedVectorBasedTest, VectorTypes);
TYPED_TEST(LinearAffinelyDecomposedVectorBasedTest, FUNCTIONALS) {
this->check();
}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::PymorException &e) {
std::cerr << Dune::Stuff::Common::colorStringRed("dune-pymor reported: ") << e << std::endl;
} catch (Dune::Exception &e) {
std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl;
} catch (...) {
std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_DETAIL_POLYFILLS_DISJUNCTION_HPP
#define BOOST_CLBL_TRTS_DETAIL_POLYFILLS_DISJUNCTION_HPP
#undef BOOST_CLBL_TRTS_DISJUNCTION
#define BOOST_CLBL_TRTS_DISJUNCTION(...) \
::boost::callable_traits::detail::disjunction<__VA_ARGS__>
namespace boost { namespace callable_traits { namespace detail {
//polyfill for C++17 std::disjunction
template<typename...>
struct disjunction : std::false_type {};
template<typename T>
struct disjunction<T> : T {};
template<typename T, typename... Ts>
struct disjunction<T, Ts...>
: std::conditional<T::value != false, T, disjunction<Ts...>>::type {};
}}} // namespace boost::callable_traits::detail
#endif // #ifndef BOOST_CLBL_TRTS_DETAIL_POLYFILLS_DISJUNCTION_HPP
<commit_msg>Delete disjunction.hpp<commit_after><|endoftext|> |
<commit_before>/*
Copyright (C) 2015 Niels Ole Salscheider <niels_ole@salscheider-online.de>
Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>
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 "textchannel.hh"
#include "common.hh"
TextChannel::TextChannel(QXmppClient *client, Tp::BaseChannel *baseChannel, uint selfHandle, const QString &selfJid)
: Tp::BaseChannelTextType(baseChannel),
m_client(client),
m_contactHandle(baseChannel->targetHandle()),
m_contactJid(baseChannel->targetID()),
m_selfHandle(selfHandle),
m_selfJid(selfJid)
{
DBG;
QStringList supportedContentTypes = QStringList() << QLatin1String("text/plain");
Tp::UIntList messageTypes = Tp::UIntList() << Tp::ChannelTextMessageTypeNormal
<< Tp::ChannelTextMessageTypeDeliveryReport;
uint messagePartSupportFlags = Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead;
uint deliveryReportingSupport = Tp::DeliveryReportingSupportFlagReceiveSuccesses | Tp::DeliveryReportingSupportFlagReceiveRead;
setMessageAcknowledgedCallback(Tp::memFun(this, &TextChannel::messageAcknowledged));
m_messagesIface = Tp::BaseChannelMessagesInterface::create(this,
supportedContentTypes,
messageTypes,
messagePartSupportFlags,
deliveryReportingSupport);
baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(m_messagesIface));
m_messagesIface->setSendMessageCallback(Tp::memFun(this, &TextChannel::sendMessage));
m_chatStateIface = Tp::BaseChannelChatStateInterface::create();
m_chatStateIface->setSetChatStateCallback(Tp::memFun(this, &TextChannel::setChatState));
baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(m_chatStateIface));
}
TextChannelPtr TextChannel::create(QXmppClient *client, Tp::BaseChannel *baseChannel, uint selfHandle, const QString &selfJid)
{
return TextChannelPtr(new TextChannel(client, baseChannel, selfHandle, selfJid));
}
QString TextChannel::sendMessage(const Tp::MessagePartList &messageParts, uint flags, Tp::DBusError *error)
{
uint outFlags = 0;
QUuid messageToken;
QXmppMessage message;
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
if (flags & (Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead)) {
message.setReceiptRequested(true);
message.setMarkable(true);
outFlags |= Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead;
}
QString content;
for (auto &part : messageParts) {
// TODO handle other parts?
if(part.count(QLatin1String("content-type")) && part.value(QLatin1String("content-type")).variant().toString() == QLatin1String("text/plain") && part.count(QLatin1String("content"))) {
content = part.value(QLatin1String("content")).variant().toString();
break;
}
}
message.setBody(content);
m_messagesIface->messageSent(messageParts, outFlags, messageToken.toString());
m_client->sendPacket(message);
return messageToken.toString();
}
void TextChannel::onMessageReceived(const QXmppMessage &message)
{
Tp::MessagePart header;
header[QLatin1String("message-token")] = QDBusVariant(message.id());
header[QLatin1String("message-sent")] = QDBusVariant(message.stamp());
header[QLatin1String("message-received")] = QDBusVariant(QDateTime::currentMSecsSinceEpoch() / 1000);
header[QLatin1String("message-sender")] = QDBusVariant(m_contactHandle);
header[QLatin1String("message-sender-id")] = QDBusVariant(m_contactJid);
/* Handle chat states */
if (message.state() != QXmppMessage::None) {
Tp::ChannelChatState state = Tp::ChannelChatStateActive;
switch(message.state()) {
case QXmppMessage::Active:
state = Tp::ChannelChatStateActive;
break;
case QXmppMessage::Composing:
state = Tp::ChannelChatStateComposing;
break;
case QXmppMessage::Gone:
state = Tp::ChannelChatStateGone;
break;
case QXmppMessage::Inactive:
state = Tp::ChannelChatStateInactive;
break;
case QXmppMessage::Paused:
state = Tp::ChannelChatStatePaused;
break;
default:
Q_ASSERT(0);
}
m_chatStateIface->chatStateChanged(m_contactHandle, state);
}
/* Handle chat markers */
if (message.marker() != QXmppMessage::NoMarker) {
Tp::MessagePartList partList;
header[QLatin1String("message-type")] = QDBusVariant(Tp::ChannelTextMessageTypeDeliveryReport);
partList << header;
switch (message.marker()) {
case QXmppMessage::Acknowledged:
header[QLatin1String("delivery-status")] = QDBusVariant(Tp::DeliveryStatusRead);
break;
case QXmppMessage::Displayed:
case QXmppMessage::Received:
header[QLatin1String("delivery-status")] = QDBusVariant(Tp::DeliveryStatusDelivered);
break;
default:
Q_ASSERT(0);
}
addReceivedMessage(partList);
}
/* Send receipt */
if (message.isReceiptRequested()) {
QUuid outMessageToken;
QXmppMessage outMessage;
outMessage.setMarker(QXmppMessage::Received);
outMessage.setTo(m_contactJid);
outMessage.setFrom(m_selfJid);
outMessage.setMarkerId(message.id());
outMessage.setId(outMessageToken.toString());
m_client->sendPacket(outMessage);
}
/* Text message */
if (!message.body().isEmpty()) {
Tp::MessagePartList body;
Tp::MessagePart text;
text[QLatin1String("content-type")] = QDBusVariant(QLatin1String("text/plain"));
text[QLatin1String("content")] = QDBusVariant(message.body());
body << text;
Tp::MessagePartList partList;
header[QLatin1String("message-type")] = QDBusVariant(Tp::ChannelTextMessageTypeNormal);
partList << header << body;
addReceivedMessage(partList);
}
}
void TextChannel::messageAcknowledged(const QString &messageId)
{
QUuid messageToken;
QXmppMessage message;
message.setMarker(QXmppMessage::Displayed);
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
message.setMarkerId(messageId);
m_client->sendPacket(message);
}
void TextChannel::setChatState(uint state, Tp::DBusError *error)
{
Q_UNUSED(error);
QUuid messageToken;
QXmppMessage message;
switch (state) {
case Tp::ChannelChatStateActive:
message.setState(QXmppMessage::Active);
break;
case Tp::ChannelChatStateComposing:
message.setState(QXmppMessage::Composing);
break;
case Tp::ChannelChatStateGone:
message.setState(QXmppMessage::Gone);
break;
case Tp::ChannelChatStateInactive:
message.setState(QXmppMessage::Inactive);
break;
case Tp::ChannelChatStatePaused:
message.setState(QXmppMessage::Paused);
break;
default:
Q_ASSERT(0);
}
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
m_client->sendPacket(message);
}
<commit_msg>TextChannel: Removed extra sentMessage call.<commit_after>/*
Copyright (C) 2015 Niels Ole Salscheider <niels_ole@salscheider-online.de>
Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>
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 "textchannel.hh"
#include "common.hh"
TextChannel::TextChannel(QXmppClient *client, Tp::BaseChannel *baseChannel, uint selfHandle, const QString &selfJid)
: Tp::BaseChannelTextType(baseChannel),
m_client(client),
m_contactHandle(baseChannel->targetHandle()),
m_contactJid(baseChannel->targetID()),
m_selfHandle(selfHandle),
m_selfJid(selfJid)
{
DBG;
QStringList supportedContentTypes = QStringList() << QLatin1String("text/plain");
Tp::UIntList messageTypes = Tp::UIntList() << Tp::ChannelTextMessageTypeNormal
<< Tp::ChannelTextMessageTypeDeliveryReport;
uint messagePartSupportFlags = Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead;
uint deliveryReportingSupport = Tp::DeliveryReportingSupportFlagReceiveSuccesses | Tp::DeliveryReportingSupportFlagReceiveRead;
setMessageAcknowledgedCallback(Tp::memFun(this, &TextChannel::messageAcknowledged));
m_messagesIface = Tp::BaseChannelMessagesInterface::create(this,
supportedContentTypes,
messageTypes,
messagePartSupportFlags,
deliveryReportingSupport);
baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(m_messagesIface));
m_messagesIface->setSendMessageCallback(Tp::memFun(this, &TextChannel::sendMessage));
m_chatStateIface = Tp::BaseChannelChatStateInterface::create();
m_chatStateIface->setSetChatStateCallback(Tp::memFun(this, &TextChannel::setChatState));
baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(m_chatStateIface));
}
TextChannelPtr TextChannel::create(QXmppClient *client, Tp::BaseChannel *baseChannel, uint selfHandle, const QString &selfJid)
{
return TextChannelPtr(new TextChannel(client, baseChannel, selfHandle, selfJid));
}
QString TextChannel::sendMessage(const Tp::MessagePartList &messageParts, uint flags, Tp::DBusError *error)
{
uint outFlags = 0;
QUuid messageToken;
QXmppMessage message;
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
if (flags & (Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead)) {
message.setReceiptRequested(true);
message.setMarkable(true);
outFlags |= Tp::MessageSendingFlagReportDelivery | Tp::MessageSendingFlagReportRead;
}
QString content;
for (auto &part : messageParts) {
// TODO handle other parts?
if(part.count(QLatin1String("content-type")) && part.value(QLatin1String("content-type")).variant().toString() == QLatin1String("text/plain") && part.count(QLatin1String("content"))) {
content = part.value(QLatin1String("content")).variant().toString();
break;
}
}
message.setBody(content);
m_client->sendPacket(message);
return messageToken.toString();
}
void TextChannel::onMessageReceived(const QXmppMessage &message)
{
Tp::MessagePart header;
header[QLatin1String("message-token")] = QDBusVariant(message.id());
header[QLatin1String("message-sent")] = QDBusVariant(message.stamp());
header[QLatin1String("message-received")] = QDBusVariant(QDateTime::currentMSecsSinceEpoch() / 1000);
header[QLatin1String("message-sender")] = QDBusVariant(m_contactHandle);
header[QLatin1String("message-sender-id")] = QDBusVariant(m_contactJid);
/* Handle chat states */
if (message.state() != QXmppMessage::None) {
Tp::ChannelChatState state = Tp::ChannelChatStateActive;
switch(message.state()) {
case QXmppMessage::Active:
state = Tp::ChannelChatStateActive;
break;
case QXmppMessage::Composing:
state = Tp::ChannelChatStateComposing;
break;
case QXmppMessage::Gone:
state = Tp::ChannelChatStateGone;
break;
case QXmppMessage::Inactive:
state = Tp::ChannelChatStateInactive;
break;
case QXmppMessage::Paused:
state = Tp::ChannelChatStatePaused;
break;
default:
Q_ASSERT(0);
}
m_chatStateIface->chatStateChanged(m_contactHandle, state);
}
/* Handle chat markers */
if (message.marker() != QXmppMessage::NoMarker) {
Tp::MessagePartList partList;
header[QLatin1String("message-type")] = QDBusVariant(Tp::ChannelTextMessageTypeDeliveryReport);
partList << header;
switch (message.marker()) {
case QXmppMessage::Acknowledged:
header[QLatin1String("delivery-status")] = QDBusVariant(Tp::DeliveryStatusRead);
break;
case QXmppMessage::Displayed:
case QXmppMessage::Received:
header[QLatin1String("delivery-status")] = QDBusVariant(Tp::DeliveryStatusDelivered);
break;
default:
Q_ASSERT(0);
}
addReceivedMessage(partList);
}
/* Send receipt */
if (message.isReceiptRequested()) {
QUuid outMessageToken;
QXmppMessage outMessage;
outMessage.setMarker(QXmppMessage::Received);
outMessage.setTo(m_contactJid);
outMessage.setFrom(m_selfJid);
outMessage.setMarkerId(message.id());
outMessage.setId(outMessageToken.toString());
m_client->sendPacket(outMessage);
}
/* Text message */
if (!message.body().isEmpty()) {
Tp::MessagePartList body;
Tp::MessagePart text;
text[QLatin1String("content-type")] = QDBusVariant(QLatin1String("text/plain"));
text[QLatin1String("content")] = QDBusVariant(message.body());
body << text;
Tp::MessagePartList partList;
header[QLatin1String("message-type")] = QDBusVariant(Tp::ChannelTextMessageTypeNormal);
partList << header << body;
addReceivedMessage(partList);
}
}
void TextChannel::messageAcknowledged(const QString &messageId)
{
QUuid messageToken;
QXmppMessage message;
message.setMarker(QXmppMessage::Displayed);
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
message.setMarkerId(messageId);
m_client->sendPacket(message);
}
void TextChannel::setChatState(uint state, Tp::DBusError *error)
{
Q_UNUSED(error);
QUuid messageToken;
QXmppMessage message;
switch (state) {
case Tp::ChannelChatStateActive:
message.setState(QXmppMessage::Active);
break;
case Tp::ChannelChatStateComposing:
message.setState(QXmppMessage::Composing);
break;
case Tp::ChannelChatStateGone:
message.setState(QXmppMessage::Gone);
break;
case Tp::ChannelChatStateInactive:
message.setState(QXmppMessage::Inactive);
break;
case Tp::ChannelChatStatePaused:
message.setState(QXmppMessage::Paused);
break;
default:
Q_ASSERT(0);
}
message.setTo(m_contactJid);
message.setFrom(m_selfJid);
message.setId(messageToken.toString());
m_client->sendPacket(message);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imestatuswindow.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:40:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "imestatuswindow.hxx"
#include "app.hxx"
#include "sfxsids.hrc"
#include "com/sun/star/beans/PropertyState.hpp"
#include "com/sun/star/beans/PropertyValue.hpp"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/XChangesBatch.hpp"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "vcl/svapp.hxx"
#include "vos/mutex.hxx"
namespace css = com::sun::star;
using sfx2::appl::ImeStatusWindow;
ImeStatusWindow::ImeStatusWindow(
SfxApplication & rApplication,
css::uno::Reference< css::lang::XMultiServiceFactory > const &
rServiceFactory):
m_rApplication(rApplication),
m_xServiceFactory(rServiceFactory),
m_bDisposed(false)
{}
void ImeStatusWindow::init()
{
if (Application::CanToggleImeStatusWindow())
try
{
sal_Bool bShow;
if (getConfig()->getPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"ShowStatusWindow")))
>>= bShow)
Application::ShowImeStatusWindow(bShow);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
// Degrade gracefully and use the VCL-supplied default if no
// configuration is available.
}
}
bool ImeStatusWindow::isShowing()
{
try
{
sal_Bool bShow;
if (getConfig()->getPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")))
>>= bShow)
return bShow;
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
// Degrade gracefully and use the VCL-supplied default if no
// configuration is available.
}
return Application::GetShowImeStatusWindowDefault();
}
void ImeStatusWindow::show(bool bShow)
{
try
{
css::uno::Reference< css::beans::XPropertySet > xConfig(getConfig());
xConfig->setPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
css::uno::makeAny(static_cast< sal_Bool >(bShow)));
css::uno::Reference< css::util::XChangesBatch > xCommit(
xConfig, css::uno::UNO_QUERY);
// Degrade gracefully by not saving the settings permanently:
if (xCommit.is())
xCommit->commitChanges();
// Alternatively, setting the VCL status could be done even if updating
// the configuration failed:
Application::ShowImeStatusWindow(bShow);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
}
}
bool ImeStatusWindow::canToggle() const
{
return Application::CanToggleImeStatusWindow();
}
ImeStatusWindow::~ImeStatusWindow()
{
if (m_xConfig.is())
// We should never get here, but just in case...
try
{
m_xConfig->removePropertyChangeListener(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
this);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.RuntimeException");
}
}
void SAL_CALL ImeStatusWindow::disposing(css::lang::EventObject const & rSource)
throw (css::uno::RuntimeException)
{
osl::MutexGuard aGuard(m_aMutex);
m_xConfig = 0;
m_bDisposed = true;
}
void SAL_CALL
ImeStatusWindow::propertyChange(css::beans::PropertyChangeEvent const & rEvent)
throw (css::uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
m_rApplication.Invalidate(SID_SHOW_IME_STATUS_WINDOW);
}
css::uno::Reference< css::beans::XPropertySet > ImeStatusWindow::getConfig()
{
css::uno::Reference< css::beans::XPropertySet > xConfig;
bool bAdd = false;
{
osl::MutexGuard aGuard(m_aMutex);
if (!m_xConfig.is())
{
if (m_bDisposed)
throw css::lang::DisposedException();
if (!m_xServiceFactory.is())
throw css::uno::RuntimeException(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"null comphelper::getProcessServiceFactory")),
0);
css::uno::Reference< css::lang::XMultiServiceFactory > xProvider(
m_xServiceFactory->createInstance(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.configuration.ConfigurationProvider"))),
css::uno::UNO_QUERY);
if (!xProvider.is())
throw css::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"null com.sun.star.configuration."
"ConfigurationProvider")),
0);
css::beans::PropertyValue aArg(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("nodepath")), -1,
css::uno::makeAny(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"/org.openoffice.Office.Common/I18N/InputMethod"))),
css::beans::PropertyState_DIRECT_VALUE);
css::uno::Sequence< css::uno::Any > aArgs(1);
aArgs[0] <<= aArg;
m_xConfig
= css::uno::Reference< css::beans::XPropertySet >(
xProvider->createInstanceWithArguments(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.configuration.ConfigurationUpdateAccess")),
aArgs),
css::uno::UNO_QUERY);
if (!m_xConfig.is())
throw css::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"null com.sun.star.configuration."
"ConfigurationUpdateAccess")),
0);
bAdd = true;
}
xConfig = m_xConfig;
}
if (bAdd)
// Exceptions here could be handled individually, to support graceful
// degradation (no update notification mechanism in this case---but also
// no dispose notifications):
xConfig->addPropertyChangeListener(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
this);
return xConfig;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.66); FILE MERGED 2005/11/28 16:13:24 cd 1.3.66.1: #i55991# Remove warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imestatuswindow.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:10:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "imestatuswindow.hxx"
#include "app.hxx"
#include "sfxsids.hrc"
#include "com/sun/star/beans/PropertyState.hpp"
#include "com/sun/star/beans/PropertyValue.hpp"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/util/XChangesBatch.hpp"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "vcl/svapp.hxx"
#include "vos/mutex.hxx"
namespace css = com::sun::star;
using sfx2::appl::ImeStatusWindow;
ImeStatusWindow::ImeStatusWindow(
SfxApplication & rApplication,
css::uno::Reference< css::lang::XMultiServiceFactory > const &
rServiceFactory):
m_rApplication(rApplication),
m_xServiceFactory(rServiceFactory),
m_bDisposed(false)
{}
void ImeStatusWindow::init()
{
if (Application::CanToggleImeStatusWindow())
try
{
sal_Bool bShow;
if (getConfig()->getPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"ShowStatusWindow")))
>>= bShow)
Application::ShowImeStatusWindow(bShow);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
// Degrade gracefully and use the VCL-supplied default if no
// configuration is available.
}
}
bool ImeStatusWindow::isShowing()
{
try
{
sal_Bool bShow;
if (getConfig()->getPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")))
>>= bShow)
return bShow;
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
// Degrade gracefully and use the VCL-supplied default if no
// configuration is available.
}
return Application::GetShowImeStatusWindowDefault();
}
void ImeStatusWindow::show(bool bShow)
{
try
{
css::uno::Reference< css::beans::XPropertySet > xConfig(getConfig());
xConfig->setPropertyValue(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
css::uno::makeAny(static_cast< sal_Bool >(bShow)));
css::uno::Reference< css::util::XChangesBatch > xCommit(
xConfig, css::uno::UNO_QUERY);
// Degrade gracefully by not saving the settings permanently:
if (xCommit.is())
xCommit->commitChanges();
// Alternatively, setting the VCL status could be done even if updating
// the configuration failed:
Application::ShowImeStatusWindow(bShow);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.Exception");
}
}
bool ImeStatusWindow::canToggle() const
{
return Application::CanToggleImeStatusWindow();
}
ImeStatusWindow::~ImeStatusWindow()
{
if (m_xConfig.is())
// We should never get here, but just in case...
try
{
m_xConfig->removePropertyChangeListener(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
this);
}
catch (css::uno::Exception &)
{
OSL_ENSURE(false, "com.sun.star.uno.RuntimeException");
}
}
void SAL_CALL ImeStatusWindow::disposing(css::lang::EventObject const & )
throw (css::uno::RuntimeException)
{
osl::MutexGuard aGuard(m_aMutex);
m_xConfig = 0;
m_bDisposed = true;
}
void SAL_CALL
ImeStatusWindow::propertyChange(css::beans::PropertyChangeEvent const & )
throw (css::uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
m_rApplication.Invalidate(SID_SHOW_IME_STATUS_WINDOW);
}
css::uno::Reference< css::beans::XPropertySet > ImeStatusWindow::getConfig()
{
css::uno::Reference< css::beans::XPropertySet > xConfig;
bool bAdd = false;
{
osl::MutexGuard aGuard(m_aMutex);
if (!m_xConfig.is())
{
if (m_bDisposed)
throw css::lang::DisposedException();
if (!m_xServiceFactory.is())
throw css::uno::RuntimeException(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"null comphelper::getProcessServiceFactory")),
0);
css::uno::Reference< css::lang::XMultiServiceFactory > xProvider(
m_xServiceFactory->createInstance(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.configuration.ConfigurationProvider"))),
css::uno::UNO_QUERY);
if (!xProvider.is())
throw css::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"null com.sun.star.configuration."
"ConfigurationProvider")),
0);
css::beans::PropertyValue aArg(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("nodepath")), -1,
css::uno::makeAny(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"/org.openoffice.Office.Common/I18N/InputMethod"))),
css::beans::PropertyState_DIRECT_VALUE);
css::uno::Sequence< css::uno::Any > aArgs(1);
aArgs[0] <<= aArg;
m_xConfig
= css::uno::Reference< css::beans::XPropertySet >(
xProvider->createInstanceWithArguments(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.configuration.ConfigurationUpdateAccess")),
aArgs),
css::uno::UNO_QUERY);
if (!m_xConfig.is())
throw css::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"null com.sun.star.configuration."
"ConfigurationUpdateAccess")),
0);
bAdd = true;
}
xConfig = m_xConfig;
}
if (bAdd)
// Exceptions here could be handled individually, to support graceful
// degradation (no update notification mechanism in this case---but also
// no dispose notifications):
xConfig->addPropertyChangeListener(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ShowStatusWindow")),
this);
return xConfig;
}
<|endoftext|> |
<commit_before>class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
int backPack(int m, vector<int> A) {
// write your code here
}
};<commit_msg>Solved 92<commit_after>class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A: Given n items with size A[i]
* @return: The maximum size
*/
int backPack(int m, vector<int> A) {
// write your code here
sort(A.begin(),A.end());
int n=A.size();
if (A.size()==0 or m==0) return 0;
int i,j,k,max=0;
std::vector<bool> dp_v(m+5,0);
dp_v[0]=1;
for (j=0;j<n;j++){
for (i=m;i>=1;i--){
if (i-A[j]>=0 and dp_v[i-A[j]]) {
dp_v[i]=1;
}
if (dp_v[i] and i>max) max=i;
}
}
return max;
}
};<|endoftext|> |
<commit_before>/* Prototype delcaration
*/
#ifndef AAB_AUDEN_SOUND_CLASS_PROTOTYPE
#define AAB_AUDEN_SOUND_CLASS_PROTOTYPE
namespace aab {
namespace auden {
class Sound;
}
}
#endif
<commit_msg>Delete sound.hh<commit_after><|endoftext|> |
<commit_before>/*=============================================================================
# Filename: gquery.cpp
# Author: Bookug Lobert
# Mail: 1181955272@qq.com
# Last Modified: 2015-10-20 12:23
# Description: query a database, there are several ways to use this program:
1. ./gquery print the help message
2. ./gquery --help simplified as -h, equal to 1
3. ./gquery db_folder query_path load query from given path fro given database
4. ./gquery db_folder load the given database and open console
=============================================================================*/
#include "../Database/Database.h"
#include "../Util/Util.h"
using namespace std;
//WARN:cannot support soft links!
void
help()
{
printf("\
/*=============================================================================\n\
# Filename: gquery.cpp\n\
# Author: Bookug Lobert\n\
# Mail: 1181955272@qq.com\n\
# Last Modified: 2015-10-20 12:23\n\
# Description: query a database, there are several ways to use this program:\n\
1. ./gquery print the help message\n\
2. ./gquery --help simplified as -h, equal to 1\n\
3. ./gquery db_folder query_path load query from given path fro given database\n\
4. ./gquery db_folder load the given database and open console\n\
=============================================================================*/\n");
}
int
main(int argc, char * argv[])
{
//chdir(dirname(argv[0]));
//#ifdef DEBUG
Util util;
//#endif
if (argc == 1 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
{
help();
return 0;
}
cout << "gquery..." << endl;
if (argc < 2)
{
cout << "error: lack of DB_store to be queried" << endl;
return 0;
}
{
cout << "argc: " << argc << "\t";
cout << "DB_store:" << argv[1] << "\t";
cout << endl;
}
string db_folder = string(argv[1]);
int len = db_folder.length();
if(db_folder.substr(len-3, 3) == ".db")
{
cout<<"your database can not end with .db"<<endl;
return -1;
}
//if(db_folder[0] != '/' && db_folder[0] != '~') //using relative path
//{
//db_folder = string("../") + db_folder;
//}
Database _db(db_folder);
_db.load();
cout << "finish loading" << endl;
// read query from file.
if (argc >= 3)
{
// ifstream fin(argv[2]);
// if(!fin)
// {
// cout << "can not open: " << buf << endl;
// return 0;
// }
//
// memset(buf, 0, sizeof(buf));
// stringstream _ss;
// while(!fin.eof()){
// fin.getline(buf, 9999);
// _ss << buf << "\n";
// }
// fin.close();
//
// string query = _ss.str();
string query = string(argv[2]);
//if(query[0] != '/' && query[0] != '~') //using relative path
//{
//query = string("../") + query;
//}
query = Util::getQueryFromFile(query.c_str());
if (query.empty())
{
return 0;
}
printf("query is:\n%s\n\n", query.c_str());
ResultSet _rs;
FILE* ofp = stdout;
if (argc >= 4)
{
ofp = fopen(argv[3], "w");
}
string msg;
shared_ptr<Transaction> ptxn = make_shared<Transaction>(db_folder, 1, 1);
//cout << ptxn << endl;
int ret = _db.query(query, _rs, ofp, true, false, nullptr);
//string query_gstore = "select ?x ?y where {<gStore> ?x ?y.} ";
//_db.query(query_gstore, _rs, ofp, true, false, ptxn);
//ptxn->print_all();
if(argc >= 4)
{
fclose(ofp);
ofp = NULL;
}
//cout<<"gquery ret: "<<ret<<endl;
if (ret <= -100) //select query
{
if(ret == -100)
{
msg = _rs.to_str();
}
else //query error
{
msg = "query failed.";
}
}
else //update query
{
if(ret >= 0)
{
msg = "update num: " + Util::int2string(ret);
}
else //update error
{
msg = "update failed.";
}
}
if(ret != -100)
{
cout << msg <<endl;
}
return 0;
}
// read query file path from terminal.
// BETTER: sighandler ctrl+C/D/Z
string query;
//char resolved_path[PATH_MAX+1];
#ifdef READLINE_ON
char *buf, prompt[] = "gsql>";
//const int commands_num = 3;
//char commands[][20] = {"help", "quit", "sparql"};
printf("Type `help` for information of all commands\n");
printf("Type `help command_t` for detail of command_t\n");
rl_bind_key('\t', rl_complete);
while (true)
{
buf = readline(prompt);
if (buf == NULL)
continue;
else
add_history(buf);
if (strncmp(buf, "help", 4) == 0)
{
if (strcmp(buf, "help") == 0)
{
//print commands message
printf("help - print commands message\n");
printf("quit - quit the console normally\n");
printf("sparql - load query from the second argument\n");
}
else
{
//TODO: help for a given command
}
continue;
}
else if (strcmp(buf, "quit") == 0)
break;
else if (strncmp(buf, "sparql", 6) != 0)
{
printf("unknown commands\n");
continue;
}
//TODO: sparql + string, not only path
string query_file;
//BETTER:build a parser for this console
bool ifredirect = false;
char* rp = buf;
int pos = strlen(buf) - 1;
while (pos > -1)
{
if (*(rp + pos) == '>')
{
ifredirect = true;
break;
}
pos--;
}
rp += pos;
char* p = buf + strlen(buf) - 1;
FILE* fp = stdout; ///default to output on screen
if (ifredirect)
{
char* tp = p;
while (*tp == ' ' || *tp == '\t')
tp--;
*(tp + 1) = '\0';
tp = rp + 1;
while (*tp == ' ' || *tp == '\t')
tp++;
fp = fopen(tp, "w"); //NOTICE:not judge here!
p = rp - 1; //NOTICE: all separated with ' ' or '\t'
}
while (*p == ' ' || *p == '\t') //set the end of path
p--;
*(p + 1) = '\0';
p = buf + 6;
while (*p == ' ' || *p == '\t') //acquire the start of path
p++;
//TODO: support the soft links(or hard links)
//there are also readlink and getcwd functions for help
//http://linux.die.net/man/2/readlink
//NOTICE:getcwd and realpath cannot acquire the real path of file
//in the same directory and the program is executing when the
//system starts running
//NOTICE: use realpath(p, NULL) is ok, but need to free the memory
char* q = realpath(p, NULL); //QUERY:still not work for soft links
#ifdef DEBUG_PRECISE
printf("%s\n", p);
#endif
if (q == NULL)
{
printf("invalid path!\n");
free(q);
free(buf);
continue;
}
else
printf("%s\n", q);
//query = getQueryFromFile(p);
query = Util::getQueryFromFile(q);
if (query.empty())
{
free(q);
//free(resolved_path);
free(buf);
if (ifredirect)
fclose(fp);
continue;
}
printf("query is:\n");
printf("%s\n\n", query.c_str());
ResultSet _rs;
shared_ptr<Transaction> ptxn = make_shared<Transaction>(db_folder, 1, 1);
int ret = _db.query(query, _rs, fp, true, false, nullptr);
//int ret = _db.query(query, _rs, NULL);
string msg;
//cout<<"gquery ret: "<<ret<<endl;
if (ret <= -100) //select query
{
if(ret == -100)
{
msg = "";
}
else //query error
{
msg = "query failed.";
}
}
else //update query
{
if(ret >= 0)
{
msg = "update num: " + Util::int2string(ret);
}
else //update error
{
msg = "update failed.";
}
}
if(ret != -100)
{
cout << msg << endl;
}
//test...
//string answer_file = query_file+".out";
//Util::save_to_file(answer_file.c_str(), _rs.to_str());
free(q);
//free(resolved_path);
free(buf);
if (ifredirect)
fclose(fp);
#ifdef DEBUG_PRECISE
printf("after buf freed!\n");
#endif
}
//#else //DEBUG:this not work!
// while(true)
// {
// cout << "please input query file path:" << endl;
// string query_file;
// cin >> query_file;
// //char* q = realpath(query_file.c_str(), NULL);
// string query = getQueryFromFile(query_file.c_str());
// if(query.empty())
// {
// //free(resolved_path);
// continue;
// }
// cout << "query is:" << endl;
// cout << query << endl << endl;
// ResultSet _rs;
// _db.query(query, _rs, stdout);
// //free(resolved_path);
// }
#endif // READLINE_ON
return 0;
}
<commit_msg>gquery 中的load函数增加true参数,测试高级函数功能<commit_after>/*=============================================================================
# Filename: gquery.cpp
# Author: Bookug Lobert
# Mail: 1181955272@qq.com
# Last Modified: 2015-10-20 12:23
# Description: query a database, there are several ways to use this program:
1. ./gquery print the help message
2. ./gquery --help simplified as -h, equal to 1
3. ./gquery db_folder query_path load query from given path fro given database
4. ./gquery db_folder load the given database and open console
=============================================================================*/
#include "../Database/Database.h"
#include "../Util/Util.h"
using namespace std;
//WARN:cannot support soft links!
void
help()
{
printf("\
/*=============================================================================\n\
# Filename: gquery.cpp\n\
# Author: Bookug Lobert\n\
# Mail: 1181955272@qq.com\n\
# Last Modified: 2015-10-20 12:23\n\
# Description: query a database, there are several ways to use this program:\n\
1. ./gquery print the help message\n\
2. ./gquery --help simplified as -h, equal to 1\n\
3. ./gquery db_folder query_path load query from given path fro given database\n\
4. ./gquery db_folder load the given database and open console\n\
=============================================================================*/\n");
}
int
main(int argc, char * argv[])
{
//chdir(dirname(argv[0]));
//#ifdef DEBUG
Util util;
//#endif
if (argc == 1 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
{
help();
return 0;
}
cout << "gquery..." << endl;
if (argc < 2)
{
cout << "error: lack of DB_store to be queried" << endl;
return 0;
}
{
cout << "argc: " << argc << "\t";
cout << "DB_store:" << argv[1] << "\t";
cout << endl;
}
string db_folder = string(argv[1]);
int len = db_folder.length();
if(db_folder.substr(len-3, 3) == ".db")
{
cout<<"your database can not end with .db"<<endl;
return -1;
}
//if(db_folder[0] != '/' && db_folder[0] != '~') //using relative path
//{
//db_folder = string("../") + db_folder;
//}
Database _db(db_folder);
_db.load(true);
cout << "finish loading" << endl;
// read query from file.
if (argc >= 3)
{
// ifstream fin(argv[2]);
// if(!fin)
// {
// cout << "can not open: " << buf << endl;
// return 0;
// }
//
// memset(buf, 0, sizeof(buf));
// stringstream _ss;
// while(!fin.eof()){
// fin.getline(buf, 9999);
// _ss << buf << "\n";
// }
// fin.close();
//
// string query = _ss.str();
string query = string(argv[2]);
//if(query[0] != '/' && query[0] != '~') //using relative path
//{
//query = string("../") + query;
//}
query = Util::getQueryFromFile(query.c_str());
if (query.empty())
{
return 0;
}
printf("query is:\n%s\n\n", query.c_str());
ResultSet _rs;
FILE* ofp = stdout;
if (argc >= 4)
{
ofp = fopen(argv[3], "w");
}
string msg;
shared_ptr<Transaction> ptxn = make_shared<Transaction>(db_folder, 1, 1);
//cout << ptxn << endl;
int ret = _db.query(query, _rs, ofp, true, false, nullptr);
//string query_gstore = "select ?x ?y where {<gStore> ?x ?y.} ";
//_db.query(query_gstore, _rs, ofp, true, false, ptxn);
//ptxn->print_all();
if(argc >= 4)
{
fclose(ofp);
ofp = NULL;
}
//cout<<"gquery ret: "<<ret<<endl;
if (ret <= -100) //select query
{
if(ret == -100)
{
msg = _rs.to_str();
}
else //query error
{
msg = "query failed.";
}
}
else //update query
{
if(ret >= 0)
{
msg = "update num: " + Util::int2string(ret);
}
else //update error
{
msg = "update failed.";
}
}
if(ret != -100)
{
cout << msg <<endl;
}
return 0;
}
// read query file path from terminal.
// BETTER: sighandler ctrl+C/D/Z
string query;
//char resolved_path[PATH_MAX+1];
#ifdef READLINE_ON
char *buf, prompt[] = "gsql>";
//const int commands_num = 3;
//char commands[][20] = {"help", "quit", "sparql"};
printf("Type `help` for information of all commands\n");
printf("Type `help command_t` for detail of command_t\n");
rl_bind_key('\t', rl_complete);
while (true)
{
buf = readline(prompt);
if (buf == NULL)
continue;
else
add_history(buf);
if (strncmp(buf, "help", 4) == 0)
{
if (strcmp(buf, "help") == 0)
{
//print commands message
printf("help - print commands message\n");
printf("quit - quit the console normally\n");
printf("sparql - load query from the second argument\n");
}
else
{
//TODO: help for a given command
}
continue;
}
else if (strcmp(buf, "quit") == 0)
break;
else if (strncmp(buf, "sparql", 6) != 0)
{
printf("unknown commands\n");
continue;
}
//TODO: sparql + string, not only path
string query_file;
//BETTER:build a parser for this console
bool ifredirect = false;
char* rp = buf;
int pos = strlen(buf) - 1;
while (pos > -1)
{
if (*(rp + pos) == '>')
{
ifredirect = true;
break;
}
pos--;
}
rp += pos;
char* p = buf + strlen(buf) - 1;
FILE* fp = stdout; ///default to output on screen
if (ifredirect)
{
char* tp = p;
while (*tp == ' ' || *tp == '\t')
tp--;
*(tp + 1) = '\0';
tp = rp + 1;
while (*tp == ' ' || *tp == '\t')
tp++;
fp = fopen(tp, "w"); //NOTICE:not judge here!
p = rp - 1; //NOTICE: all separated with ' ' or '\t'
}
while (*p == ' ' || *p == '\t') //set the end of path
p--;
*(p + 1) = '\0';
p = buf + 6;
while (*p == ' ' || *p == '\t') //acquire the start of path
p++;
//TODO: support the soft links(or hard links)
//there are also readlink and getcwd functions for help
//http://linux.die.net/man/2/readlink
//NOTICE:getcwd and realpath cannot acquire the real path of file
//in the same directory and the program is executing when the
//system starts running
//NOTICE: use realpath(p, NULL) is ok, but need to free the memory
char* q = realpath(p, NULL); //QUERY:still not work for soft links
#ifdef DEBUG_PRECISE
printf("%s\n", p);
#endif
if (q == NULL)
{
printf("invalid path!\n");
free(q);
free(buf);
continue;
}
else
printf("%s\n", q);
//query = getQueryFromFile(p);
query = Util::getQueryFromFile(q);
if (query.empty())
{
free(q);
//free(resolved_path);
free(buf);
if (ifredirect)
fclose(fp);
continue;
}
printf("query is:\n");
printf("%s\n\n", query.c_str());
ResultSet _rs;
shared_ptr<Transaction> ptxn = make_shared<Transaction>(db_folder, 1, 1);
int ret = _db.query(query, _rs, fp, true, false, nullptr);
//int ret = _db.query(query, _rs, NULL);
string msg;
//cout<<"gquery ret: "<<ret<<endl;
if (ret <= -100) //select query
{
if(ret == -100)
{
msg = "";
}
else //query error
{
msg = "query failed.";
}
}
else //update query
{
if(ret >= 0)
{
msg = "update num: " + Util::int2string(ret);
}
else //update error
{
msg = "update failed.";
}
}
if(ret != -100)
{
cout << msg << endl;
}
//test...
//string answer_file = query_file+".out";
//Util::save_to_file(answer_file.c_str(), _rs.to_str());
free(q);
//free(resolved_path);
free(buf);
if (ifredirect)
fclose(fp);
#ifdef DEBUG_PRECISE
printf("after buf freed!\n");
#endif
}
//#else //DEBUG:this not work!
// while(true)
// {
// cout << "please input query file path:" << endl;
// string query_file;
// cin >> query_file;
// //char* q = realpath(query_file.c_str(), NULL);
// string query = getQueryFromFile(query_file.c_str());
// if(query.empty())
// {
// //free(resolved_path);
// continue;
// }
// cout << "query is:" << endl;
// cout << query << endl << endl;
// ResultSet _rs;
// _db.query(query, _rs, stdout);
// //free(resolved_path);
// }
#endif // READLINE_ON
return 0;
}
<|endoftext|> |
<commit_before>/**
* Template C++ file.
* Function with references to pointers: func(int *&ptr);
*/
/********************* Header Files ***********************/
/* C++ Headers */
#include <iostream> /* Input/output objects. */
//#include <fstream> /* File operations. */
//#include <sstream> /* String stream. */
#include <string> /* C++ String class. */
//#include <new> /* Defines bad_malloc exception, new functions. */
//#include <typeinfo> /* Casting header. */
//#include <exception> /* Top level exception header. */
//#include <stdexcept> /* Derived exception classes. */
/* STL Headers */
//#include <vector>
//#include <list>
//#include <deque>
//#include <stack>
//#include <queue>
//#include <priority_queue>
//#include <bitset>
//#include <set> // multiset for multiple keys allowed.
//#include <map> // multimap for multiple keys allowed.
//#include <utility> // Has pair for map.
//#include <algorithm>
//#include <numeric>
//#include <functional> // Functional objects.
/* C Headers */
//#include <cstdlib>
//#include <cstddef>
//#include <cctype>
//#include <cstring>
//#include <cstdio>
//#include <climits>
//#include <cassert>
/* Project Headers */
/******************* Constants/Macros *********************/
/**************** Namespace Declarations ******************/
using std::cin;
using std::cout;
using std::endl;
using std::string;
/******************* Type Definitions *********************/
/* For enums: Try to namesapce the common elements.
* typedef enum {
* VAL_,
* } name_e;
*/
/* For structs:
* typedef struct name_s {
* int index;
* } name_t;
*/
/****************** Class Definitions *********************/
/**************** Static Data Definitions *****************/
/****************** Static Functions **********************/
/****************** Global Functions **********************/
/**
* Main loop of the function.
*/
int main(void) {
return 0;
}
<commit_msg>Update.<commit_after>/**
* Template C++ file.
* Function with references to pointers: func(int *&ptr);
*/
/********************* Header Files ***********************/
/* C++ Headers */
#include <iostream> /* Input/output objects. */
//#include <fstream> /* File operations. */
//#include <sstream> /* String stream. */
#include <string> /* C++ String class. */
//#include <new> /* Defines bad_malloc exception, new functions. */
//#include <typeinfo> /* Casting header. */
//#include <exception> /* Top level exception header. */
//#include <stdexcept> /* Derived exception classes. */
/* STL Headers */
//#include <vector>
//#include <list>
//#include <deque>
//#include <stack>
//#include <queue>
//#include <priority_queue>
//#include <bitset>
//#include <set> // multiset for multiple keys allowed.
//#include <map> // multimap for multiple keys allowed.
//#include <utility> // Has pair for map.
//#include <algorithm>
//#include <numeric>
//#include <functional> // Functional objects.
//#include <iterator> // Contains back_inserter function and like.
/* C Headers */
//#include <cstdlib>
//#include <cstddef>
//#include <cctype>
//#include <cstring>
//#include <cstdio>
//#include <climits>
//#include <cassert>
/* Project Headers */
/******************* Constants/Macros *********************/
/**************** Namespace Declarations ******************/
using std::cin;
using std::cout;
using std::endl;
using std::string;
/******************* Type Definitions *********************/
/* For enums: Try to namesapce the common elements.
* typedef enum {
* VAL_,
* } name_e;
*/
/* For structs:
* typedef struct name_s {
* int index;
* } name_t;
*/
/****************** Class Definitions *********************/
/**************** Static Data Definitions *****************/
/****************** Static Functions **********************/
/****************** Global Functions **********************/
/**
* Main loop of the function.
*/
int main(void) {
return 0;
}
<|endoftext|> |
<commit_before>#ifndef VEXCL_FFT_PLAN_HPP
#define VEXCL_FFT_PLAN_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file fft/plan.hpp
* \author Pascal Germroth <pascal@ensieve.org>
* \brief FFT plan, stores kernels and buffers for one configuration.
*/
#include <cmath>
#ifndef M_PI
# define M_PI 3.1415926535897932384626433832795
#endif
#include <vexcl/vector.hpp>
#include <vexcl/fft/kernels.hpp>
#include <boost/lexical_cast.hpp>
namespace vex {
namespace fft {
// for arbitrary x, return smallest y=a^b c^d e^f...>=x where a,c,e are iterated over (assumed to be prime)
template<class Iterator>
inline size_t next_prime_power(Iterator begin, Iterator end, size_t target, size_t n = 1, size_t best = -1) {
const size_t prime = *begin++;
for(; n < target ; n *= prime) {
if(begin != end)
best = next_prime_power(begin, end, target, n, best);
}
return std::min(n, best);
}
struct simple_planner {
const size_t max_size;
simple_planner(size_t s = 25) : max_size(s) {}
// prime factors to use
virtual std::vector<size_t> primes() const {
return {2, 3, 5, 7, 11};
}
// returns the size the data must be padded to.
virtual size_t best_size(size_t n) const {
auto ps = primes();
return next_prime_power(ps.begin(), ps.end(), n);
}
// splits n into a list of powers 2^a 2^b 2^c 3^d 5^e...
virtual std::vector<pow> factor(size_t n) const {
std::vector<pow> fs;
for(auto p : primes())
if(n % p == 0) {
size_t e = 1;
while(n % size_t(std::pow(p, e + 1)) == 0) e += 1;
n /= std::pow(p, e);
// split exponent into reasonable parts.
for(auto q : stages(pow(p, e)))
fs.push_back(q);
}
if(n != 1) throw std::runtime_error("Unsupported FFT size");
return fs;
}
// use largest radixes, i.e. 2^4 2^4 2^1
virtual std::vector<pow> stages(pow p) const {
size_t t = std::log(max_size + 1) / std::log(p.base);
std::vector<pow> fs;
for(size_t e = p.exponent ; ; ) {
if(e > t) {
fs.push_back(pow(p.base, t));
e -= t;
} else if(e <= t) {
fs.push_back(pow(p.base, e));
break;
}
}
return fs;
}
};
struct even_planner : simple_planner {
even_planner(size_t s = 25) : simple_planner(s) {}
// avoid very small radixes, i.e. 2^3 2^3 2^3
virtual std::vector<pow> stages(pow p) const {
size_t t = std::log(max_size + 1) / std::log(p.base);
// number of parts
size_t m = (p.exponent + t - 1) / t;
// two levels.
size_t r = t * m - p.exponent;
size_t u = m * (r / m);
size_t v = t - (r / m);
std::vector<pow> fs;
for(size_t i = 0 ; i < m - r + u ; i++)
fs.push_back(pow(p.base, v));
for(size_t i = 0 ; i < r - u ; i++)
fs.push_back(pow(p.base, v - 1));
return fs;
}
};
typedef even_planner default_planner;
template <class T0, class T1, class Planner = default_planner>
struct plan {
typedef typename cl_scalar_of<T0>::type T0s;
typedef typename cl_scalar_of<T1>::type T1s;
static_assert(boost::is_same<T0s, T1s>::value, "Input and output must have same precision.");
typedef T0s T;
static_assert(boost::is_same<T, cl_float>::value || boost::is_same<T, cl_double>::value,
"Only float and double data supported.");
typedef typename cl_vector_of<T, 2>::type T2;
VEX_FUNCTION(r2c, T2(T), "return (" + type_name<T2>() + ")(prm1, 0);");
VEX_FUNCTION(c2r, T(T2), "return prm1.x;");
const std::vector<cl::CommandQueue> &queues;
Planner planner;
T scale;
std::vector<kernel_call> kernels;
vector<T2> temp[2];
size_t input, output;
// \param sizes
// 1D case: {n}.
// 2D case: {h, w} in row-major format: x + y * w. (like FFTw)
// etc.
plan(const std::vector<cl::CommandQueue> &queues, const std::vector<size_t> sizes, bool inverse, const Planner &planner = Planner())
: queues(queues), planner(planner) {
assert(sizes.size() >= 1);
assert(queues.size() == 1);
auto queue = queues[0];
auto context = qctx(queue);
auto device = qdev(queue);
size_t total_n = std::accumulate(sizes.begin(), sizes.end(), 1, std::multiplies<size_t>());
scale = inverse ? ((T)1 / total_n) : 1;
temp[0] = vector<T2>(queues, total_n);
temp[1] = vector<T2>(queues, total_n);
size_t current = 0, other = 1;
// Build the list of kernels.
input = current;
for(auto d = sizes.rbegin() ; d != sizes.rend() ; d++) {
const size_t w = *d, h = total_n / w;
// 1D, each row.
if(w > 1) {
size_t p = 1;
for(auto radix : planner.factor(w)) {
kernels.push_back(radix_kernel<T>(queue, w, h,
inverse, radix, p, temp[current](0), temp[other](0)));
std::swap(current, other);
p *= radix.value;
}
}
// transpose.
if(w > 1 && h > 1) {
kernels.push_back(transpose_kernel<T>(queue, w, h,
temp[current](0), temp[other](0)));
std::swap(current, other);
}
}
output = current;
}
/// Execute the complete transformation.
/// Converts real-valued input and output, supports multiply-adding to output.
template <class Expr>
void operator()(const Expr &in, vector<T1> &out, bool append, T ex_scale) {
if(std::is_same<T0, T>::value) temp[input] = r2c(in);
else temp[input] = in;
for(auto run = kernels.begin(); run != kernels.end(); ++run)
queues[0].enqueueNDRangeKernel(run->kernel, cl::NullRange,
run->global, run->local);
if(std::is_same<T1, T>::value) {
if(append) out += c2r(temp[output]) * (ex_scale * scale);
else out = c2r(temp[output]) * (ex_scale * scale);
} else {
if(append) out += temp[output] * (ex_scale * scale);
else out = temp[output] * (ex_scale * scale);
}
}
};
template <class T0, class T1, class P>
inline std::ostream &operator<<(std::ostream &o, const plan<T0,T1,P> &p) {
o << "FFT[\n";
for(auto k : p.kernels)
o << " " << k.desc << "\n";
return o << "]";
}
} // namespace fft
} // namespace vex
#endif
<commit_msg>Remove range for<commit_after>#ifndef VEXCL_FFT_PLAN_HPP
#define VEXCL_FFT_PLAN_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file fft/plan.hpp
* \author Pascal Germroth <pascal@ensieve.org>
* \brief FFT plan, stores kernels and buffers for one configuration.
*/
#include <cmath>
#ifndef M_PI
# define M_PI 3.1415926535897932384626433832795
#endif
#include <vexcl/vector.hpp>
#include <vexcl/fft/kernels.hpp>
#include <boost/lexical_cast.hpp>
namespace vex {
namespace fft {
// for arbitrary x, return smallest y=a^b c^d e^f...>=x where a,c,e are iterated over (assumed to be prime)
template<class Iterator>
inline size_t next_prime_power(Iterator begin, Iterator end, size_t target, size_t n = 1, size_t best = -1) {
const size_t prime = *begin++;
for(; n < target ; n *= prime) {
if(begin != end)
best = next_prime_power(begin, end, target, n, best);
}
return std::min(n, best);
}
struct simple_planner {
const size_t max_size;
simple_planner(size_t s = 25) : max_size(s) {}
// prime factors to use
virtual std::vector<size_t> primes() const {
return {2, 3, 5, 7, 11};
}
// returns the size the data must be padded to.
virtual size_t best_size(size_t n) const {
auto ps = primes();
return next_prime_power(ps.begin(), ps.end(), n);
}
// splits n into a list of powers 2^a 2^b 2^c 3^d 5^e...
virtual std::vector<pow> factor(size_t n) const {
std::vector<pow> fs;
auto ps = primes();
for(auto p = ps.begin() ; p != ps.end() ; p++)
if(n % *p == 0) {
size_t e = 1;
while(n % size_t(std::pow(*p, e + 1)) == 0) e += 1;
n /= std::pow(*p, e);
// split exponent into reasonable parts.
auto qs = stages(pow(*p, e));
std::copy(qs.begin(), qs.end(), std::back_inserter(fs));
}
if(n != 1) throw std::runtime_error("Unsupported FFT size");
return fs;
}
// use largest radixes, i.e. 2^4 2^4 2^1
virtual std::vector<pow> stages(pow p) const {
size_t t = std::log(max_size + 1) / std::log(p.base);
std::vector<pow> fs;
for(size_t e = p.exponent ; ; ) {
if(e > t) {
fs.push_back(pow(p.base, t));
e -= t;
} else if(e <= t) {
fs.push_back(pow(p.base, e));
break;
}
}
return fs;
}
};
struct even_planner : simple_planner {
even_planner(size_t s = 25) : simple_planner(s) {}
// avoid very small radixes, i.e. 2^3 2^3 2^3
virtual std::vector<pow> stages(pow p) const {
size_t t = std::log(max_size + 1) / std::log(p.base);
// number of parts
size_t m = (p.exponent + t - 1) / t;
// two levels.
size_t r = t * m - p.exponent;
size_t u = m * (r / m);
size_t v = t - (r / m);
std::vector<pow> fs;
for(size_t i = 0 ; i < m - r + u ; i++)
fs.push_back(pow(p.base, v));
for(size_t i = 0 ; i < r - u ; i++)
fs.push_back(pow(p.base, v - 1));
return fs;
}
};
typedef even_planner default_planner;
template <class T0, class T1, class Planner = default_planner>
struct plan {
typedef typename cl_scalar_of<T0>::type T0s;
typedef typename cl_scalar_of<T1>::type T1s;
static_assert(boost::is_same<T0s, T1s>::value, "Input and output must have same precision.");
typedef T0s T;
static_assert(boost::is_same<T, cl_float>::value || boost::is_same<T, cl_double>::value,
"Only float and double data supported.");
typedef typename cl_vector_of<T, 2>::type T2;
VEX_FUNCTION(r2c, T2(T), "return (" + type_name<T2>() + ")(prm1, 0);");
VEX_FUNCTION(c2r, T(T2), "return prm1.x;");
const std::vector<cl::CommandQueue> &queues;
Planner planner;
T scale;
std::vector<kernel_call> kernels;
vector<T2> temp[2];
size_t input, output;
// \param sizes
// 1D case: {n}.
// 2D case: {h, w} in row-major format: x + y * w. (like FFTw)
// etc.
plan(const std::vector<cl::CommandQueue> &queues, const std::vector<size_t> sizes, bool inverse, const Planner &planner = Planner())
: queues(queues), planner(planner) {
assert(sizes.size() >= 1);
assert(queues.size() == 1);
auto queue = queues[0];
auto context = qctx(queue);
auto device = qdev(queue);
size_t total_n = std::accumulate(sizes.begin(), sizes.end(), 1, std::multiplies<size_t>());
scale = inverse ? ((T)1 / total_n) : 1;
temp[0] = vector<T2>(queues, total_n);
temp[1] = vector<T2>(queues, total_n);
size_t current = 0, other = 1;
// Build the list of kernels.
input = current;
for(auto d = sizes.rbegin() ; d != sizes.rend() ; d++) {
const size_t w = *d, h = total_n / w;
// 1D, each row.
if(w > 1) {
size_t p = 1;
auto rs = planner.factor(w);
for(auto r = rs.begin() ; r != rs.end() ; r++) {
kernels.push_back(radix_kernel<T>(queue, w, h,
inverse, *r, p, temp[current](0), temp[other](0)));
std::swap(current, other);
p *= r->value;
}
}
// transpose.
if(w > 1 && h > 1) {
kernels.push_back(transpose_kernel<T>(queue, w, h,
temp[current](0), temp[other](0)));
std::swap(current, other);
}
}
output = current;
}
/// Execute the complete transformation.
/// Converts real-valued input and output, supports multiply-adding to output.
template <class Expr>
void operator()(const Expr &in, vector<T1> &out, bool append, T ex_scale) {
if(std::is_same<T0, T>::value) temp[input] = r2c(in);
else temp[input] = in;
for(auto run = kernels.begin(); run != kernels.end(); ++run)
queues[0].enqueueNDRangeKernel(run->kernel, cl::NullRange,
run->global, run->local);
if(std::is_same<T1, T>::value) {
if(append) out += c2r(temp[output]) * (ex_scale * scale);
else out = c2r(temp[output]) * (ex_scale * scale);
} else {
if(append) out += temp[output] * (ex_scale * scale);
else out = temp[output] * (ex_scale * scale);
}
}
};
template <class T0, class T1, class P>
inline std::ostream &operator<<(std::ostream &o, const plan<T0,T1,P> &p) {
o << "FFT[\n";
for(auto k = p.kernels.begin() ; k != p.kernels.end() ; k++)
o << " " << k->desc << "\n";
return o << "]";
}
} // namespace fft
} // namespace vex
#endif
<|endoftext|> |
<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma managed(on)
#include "LLDBDebugger.h"
#include "lldb/API/SBEvent.h"
#include "lldb/API/SBListener.h"
#include "lldb/API/SBProcess.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBStructuredData.h"
#include "lldb/API/SBTarget.h"
#include <msclr\marshal_cppstd.h>
#include "LLDBCommandInterpreter.h"
#include "LLDBPlatform.h"
#include "LLDBTarget.h"
#using < system.dll >
namespace YetiVSI {
namespace DebugEngine {
namespace {
void Log(System::String ^ message) {
System::String ^ tagged_message =
System::String::Format("LLDB: {0}", message);
System::Diagnostics::Trace::WriteLine(tagged_message);
}
void LoggingCallback(const char* message, void*) {
Log(gcnew System::String(message));
}
} // namespace
LLDBDebugger::LLDBDebugger(bool sourceInitFiles) {
// Make sure LLDB is initialized before creating the debugger.
// Calling initialize multiple times has no side effects.
lldb::SBDebugger::Initialize();
// We can't store a non-managed class (aka LLDB objects) as members of a
// managed class, and LLDB only provides a way to create an SBDebugger
// object on the stack. So create the object on the stack, and then create
// a new object on the heap from a copy of the object on the stack.
debugger_ = MakeUniquePtr<lldb::SBDebugger>(
lldb::SBDebugger::Create(sourceInitFiles, LoggingCallback, nullptr));
}
void LLDBDebugger::SetAsync(bool async) { debugger_->SetAsync(async); }
void LLDBDebugger::SkipLLDBInitFiles(bool skip) {
debugger_->SkipLLDBInitFiles(skip);
}
SbCommandInterpreter ^ LLDBDebugger::GetCommandInterpreter() {
lldb::SBCommandInterpreter interpreter = debugger_->GetCommandInterpreter();
if (!interpreter.IsValid()) {
return nullptr;
}
return gcnew LLDBCommandInterpreter(interpreter);
}
SbTarget ^ LLDBDebugger::CreateTarget(System::String ^ filename) {
auto name = msclr::interop::marshal_as<std::string>(filename);
lldb::SBTarget target = debugger_->CreateTarget(name.c_str());
if (!target.IsValid()) {
return nullptr;
}
return gcnew LLDBTarget(target);
}
bool LLDBDebugger::DeleteTarget(SbTarget ^ target) {
LLDBTarget ^ lldbTarget = safe_cast<LLDBTarget ^>(target);
lldb::SBTarget sbTarget = lldbTarget->GetNativeObject();
return debugger_->DeleteTarget(sbTarget);
}
void LLDBDebugger::SetSelectedPlatform(SbPlatform ^ platform) {
LLDBPlatform ^ lldbPlatform = safe_cast<LLDBPlatform ^>(platform);
lldb::SBPlatform sbPlatform = lldbPlatform->GetNativeObject();
debugger_->SetSelectedPlatform(sbPlatform);
}
SbPlatform ^ LLDBDebugger::GetSelectedPlatform() {
lldb::SBPlatform platform = debugger_->GetSelectedPlatform();
if (!platform.IsValid()) {
return nullptr;
}
return gcnew LLDBPlatform(platform);
}
bool LLDBDebugger::EnableLog(
System::String ^ channel,
System::Collections::Generic::List<System::String ^> ^ types) {
auto stdChannel = msclr::interop::marshal_as<std::string>(channel);
// Convert types to a vector of std::string to store the c strings locally.
std::vector<std::string> stdTypes;
for each (auto type in types) {
auto stdType = msclr::interop::marshal_as<std::string>(type);
stdTypes.push_back(stdType);
}
// Build the raw char* array that LLDB expects.
std::unique_ptr<const char* []> rawTypes(new const char*[stdTypes.size() + 1]);
for (size_t i = 0; i < stdTypes.size(); i++) {
rawTypes[i] = stdTypes[i].c_str();
}
rawTypes[stdTypes.size()] = nullptr;
return debugger_->EnableLog(stdChannel.c_str(), rawTypes.get());
}
bool LLDBDebugger::IsPlatformAvailable(System::String ^ platformName) {
auto name = msclr::interop::marshal_as<std::string>(platformName);
uint32_t platformsCount = debugger_->GetNumAvailablePlatforms();
std::string currentPlatformName;
for (uint32_t i = 0; i < platformsCount; ++i) {
lldb::SBStructuredData platform =
debugger_->GetAvailablePlatformInfoAtIndex(i);
lldb::SBStructuredData nameData = platform.GetValueForKey("name");
// +1 below is needed because GetStringValue explicitly writes the null terminator.
size_t size = nameData.GetStringValue(nullptr, 0) + 1;
currentPlatformName.resize(size);
nameData.GetStringValue(const_cast<char*>(currentPlatformName.data()), size);
if (name.compare(currentPlatformName.c_str()) == 0) {
return true;
}
}
return false;
}
} // namespace DebugEngine
} // namespace YetiVSI
<commit_msg>[debugger] Call `PrintStackTraceOnError` during init<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma managed(on)
#include "LLDBDebugger.h"
#include <msclr\marshal_cppstd.h>
#include <mutex>
#include "LLDBCommandInterpreter.h"
#include "LLDBPlatform.h"
#include "LLDBTarget.h"
#include "lldb/API/SBEvent.h"
#include "lldb/API/SBListener.h"
#include "lldb/API/SBProcess.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBStructuredData.h"
#include "lldb/API/SBTarget.h"
namespace YetiVSI {
namespace DebugEngine {
namespace {
std::once_flag debugger_init_flag;
void SbDebuggerInit() {
lldb::SBDebugger::Initialize();
lldb::SBDebugger::PrintStackTraceOnError();
}
void Log(System::String ^ message) {
System::String ^ tagged_message =
System::String::Format("LLDB: {0}", message);
System::Diagnostics::Trace::WriteLine(tagged_message);
}
void LoggingCallback(const char* message, void*) {
Log(gcnew System::String(message));
}
} // namespace
LLDBDebugger::LLDBDebugger(bool sourceInitFiles) {
// Make sure LLDB is initialized before creating the debugger.
std::call_once(debugger_init_flag, SbDebuggerInit);
// We can't store a non-managed class (aka LLDB objects) as members of a
// managed class, and LLDB only provides a way to create an SBDebugger
// object on the stack. So create the object on the stack, and then create
// a new object on the heap from a copy of the object on the stack.
debugger_ = MakeUniquePtr<lldb::SBDebugger>(
lldb::SBDebugger::Create(sourceInitFiles, LoggingCallback, nullptr));
}
void LLDBDebugger::SetAsync(bool async) { debugger_->SetAsync(async); }
void LLDBDebugger::SkipLLDBInitFiles(bool skip) {
debugger_->SkipLLDBInitFiles(skip);
}
SbCommandInterpreter ^ LLDBDebugger::GetCommandInterpreter() {
lldb::SBCommandInterpreter interpreter = debugger_->GetCommandInterpreter();
if (!interpreter.IsValid()) {
return nullptr;
}
return gcnew LLDBCommandInterpreter(interpreter);
}
SbTarget ^ LLDBDebugger::CreateTarget(System::String ^ filename) {
auto name = msclr::interop::marshal_as<std::string>(filename);
lldb::SBTarget target = debugger_->CreateTarget(name.c_str());
if (!target.IsValid()) {
return nullptr;
}
return gcnew LLDBTarget(target);
}
bool LLDBDebugger::DeleteTarget(SbTarget ^ target) {
LLDBTarget ^ lldbTarget = safe_cast<LLDBTarget ^>(target);
lldb::SBTarget sbTarget = lldbTarget->GetNativeObject();
return debugger_->DeleteTarget(sbTarget);
}
void LLDBDebugger::SetSelectedPlatform(SbPlatform ^ platform) {
LLDBPlatform ^ lldbPlatform = safe_cast<LLDBPlatform ^>(platform);
lldb::SBPlatform sbPlatform = lldbPlatform->GetNativeObject();
debugger_->SetSelectedPlatform(sbPlatform);
}
SbPlatform ^ LLDBDebugger::GetSelectedPlatform() {
lldb::SBPlatform platform = debugger_->GetSelectedPlatform();
if (!platform.IsValid()) {
return nullptr;
}
return gcnew LLDBPlatform(platform);
}
bool LLDBDebugger::EnableLog(
System::String ^ channel,
System::Collections::Generic::List<System::String ^> ^ types) {
auto stdChannel = msclr::interop::marshal_as<std::string>(channel);
// Convert types to a vector of std::string to store the c strings locally.
std::vector<std::string> stdTypes;
for each (auto type in types) {
auto stdType = msclr::interop::marshal_as<std::string>(type);
stdTypes.push_back(stdType);
}
// Build the raw char* array that LLDB expects.
std::unique_ptr<const char* []> rawTypes(new const char*[stdTypes.size() + 1]);
for (size_t i = 0; i < stdTypes.size(); i++) {
rawTypes[i] = stdTypes[i].c_str();
}
rawTypes[stdTypes.size()] = nullptr;
return debugger_->EnableLog(stdChannel.c_str(), rawTypes.get());
}
bool LLDBDebugger::IsPlatformAvailable(System::String ^ platformName) {
auto name = msclr::interop::marshal_as<std::string>(platformName);
uint32_t platformsCount = debugger_->GetNumAvailablePlatforms();
std::string currentPlatformName;
for (uint32_t i = 0; i < platformsCount; ++i) {
lldb::SBStructuredData platform =
debugger_->GetAvailablePlatformInfoAtIndex(i);
lldb::SBStructuredData nameData = platform.GetValueForKey("name");
// +1 below is needed because GetStringValue explicitly writes the null terminator.
size_t size = nameData.GetStringValue(nullptr, 0) + 1;
currentPlatformName.resize(size);
nameData.GetStringValue(const_cast<char*>(currentPlatformName.data()), size);
if (name.compare(currentPlatformName.c_str()) == 0) {
return true;
}
}
return false;
}
} // namespace DebugEngine
} // namespace YetiVSI
<|endoftext|> |
<commit_before>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx_vulkan.h"
#include "stdafx.h"
#define HALTON_SAMPLE_COUNT 1024
namespace Intrinsic
{
namespace Renderer
{
namespace Vulkan
{
namespace RenderProcess
{
// Uniform data decl.
namespace
{
struct UniformDataSource
{
glm::mat4 inverseProjectionMatrix;
glm::mat4 inverseViewProjectionMatrix;
glm::vec4 cameraWorldPosition;
glm::ivec4 haltonSamples;
} _uniformDataSource;
glm::vec2 _haltonSamples[HALTON_SAMPLE_COUNT];
_INTR_INLINE void initStaticUniformData()
{
// Generate Halton Samples
{
for (uint32_t i = 0u; i < HALTON_SAMPLE_COUNT; ++i)
{
_haltonSamples[i] = glm::vec2(Math::calcHaltonSequence(i, 2u),
Math::calcHaltonSequence(i, 3u));
}
}
}
}
namespace
{
struct UniformDataRef
{
UniformDataRef() { memset(this, 0x00u, sizeof(UniformDataRef)); }
UniformDataRef(const void* p_Ptr, uint32_t p_Size)
{
const uint64_t address = (uint64_t)p_Ptr;
offset = (uint16_t)(address - (uint64_t)&_uniformDataSource);
size = (uint16_t)p_Size;
}
uint16_t offset;
uint16_t size;
};
struct UniformBuffer
{
UniformBuffer() { memset(this, 0x00u, sizeof(UniformBuffer)); }
UniformDataRef refs[32u];
uint8_t refCount;
uint32_t dataSize;
void* data;
};
_INTR_HASH_MAP(Name, UniformDataRef)
_uniformOffsetMapping = {
{"InverseProjectionMatrix",
UniformDataRef(&_uniformDataSource.inverseProjectionMatrix,
sizeof(glm::mat4))},
{"InverseViewProjectionMatrix",
UniformDataRef(&_uniformDataSource.inverseViewProjectionMatrix,
sizeof(glm::mat4))},
{"CameraWorldPosition",
UniformDataRef(&_uniformDataSource.cameraWorldPosition,
sizeof(glm::vec4))},
{"HaltonSamples",
UniformDataRef(&_uniformDataSource.haltonSamples, sizeof(glm::ivec4))}};
_INTR_HASH_MAP(Name, UniformBuffer) _uniformBuffers;
uint8_t* _uniformBufferMemory = nullptr;
LinearOffsetAllocator _uniformBufferMemoryAllocator;
const uint32_t _uniformBufferMemorySizeInBytes = 2u * 1024u * 1024u;
}
// <-
void UniformManager::load(const rapidjson::Value& p_UniformBuffers)
{
if (_uniformBufferMemory)
{
free(_uniformBufferMemory);
_uniformBufferMemory = nullptr;
}
_uniformBufferMemory = (uint8_t*)malloc(_uniformBufferMemorySizeInBytes);
_uniformBufferMemoryAllocator.init(_uniformBufferMemorySizeInBytes);
_uniformBuffers.clear();
for (uint32_t bufferIdx = 0u; bufferIdx < p_UniformBuffers.Size();
++bufferIdx)
{
const rapidjson::Value& uniformBufferDesc = p_UniformBuffers[bufferIdx];
const rapidjson::Value& entryDescs = uniformBufferDesc["entries"];
UniformBuffer uniformBuffer;
for (uint32_t entryIdx = 0u; entryIdx < entryDescs.Size(); ++entryIdx)
{
const rapidjson::Value& entryDesc = entryDescs[entryIdx];
UniformDataRef entry = _uniformOffsetMapping[entryDesc.GetString()];
uniformBuffer.refs[uniformBuffer.refCount] = entry;
++uniformBuffer.refCount;
uniformBuffer.dataSize += entry.size;
}
_uniformBuffers[uniformBufferDesc["name"].GetString()] = uniformBuffer;
}
initStaticUniformData();
}
// <-
void UniformManager::updatePerFrameUniformBufferData(Dod::Ref p_Camera)
{
_uniformDataSource.inverseProjectionMatrix =
Components::CameraManager::_inverseProjectionMatrix(p_Camera);
_uniformDataSource.inverseViewProjectionMatrix =
Components::CameraManager::_inverseViewProjectionMatrix(p_Camera);
_uniformDataSource.cameraWorldPosition =
glm::vec4(Components::NodeManager::_worldPosition(p_Camera), 0.0f);
_uniformDataSource.haltonSamples = glm::ivec4(
(int32_t)(
_haltonSamples[TaskManager::_frameCounter % HALTON_SAMPLE_COUNT].x *
255),
(int32_t)(
_haltonSamples[TaskManager::_frameCounter % HALTON_SAMPLE_COUNT].y *
255),
0, 0);
}
// <-
void UniformManager::updateUniformBuffers()
{
for (auto it = _uniformBuffers.begin(); it != _uniformBuffers.end(); ++it)
{
UniformBuffer& uniformBuffer = it->second;
uint32_t currentOffset = 0u;
uint8_t* bufferData =
(uint8_t*)_uniformBufferMemory +
_uniformBufferMemoryAllocator.allocate(uniformBuffer.dataSize, 8u);
for (uint32_t refIdx = 0u; refIdx < uniformBuffer.refCount; ++refIdx)
{
const UniformDataRef dataRef = uniformBuffer.refs[refIdx];
memcpy(bufferData + currentOffset,
((uint8_t*)&_uniformDataSource) + dataRef.offset, dataRef.size);
currentOffset += dataRef.size;
}
uniformBuffer.data = bufferData;
}
}
// <-
void UniformManager::resetAllocator() { _uniformBufferMemoryAllocator.reset(); }
// <-
UniformBufferDataEntry
UniformManager::requestUniformBufferData(const Name& p_Name)
{
const UniformBuffer& buffer = _uniformBuffers[p_Name];
return UniformBufferDataEntry(buffer.data, buffer.dataSize);
}
}
}
}
}
<commit_msg>Wrong camera world position passed to uniform buffers<commit_after>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx_vulkan.h"
#include "stdafx.h"
#define HALTON_SAMPLE_COUNT 1024
namespace Intrinsic
{
namespace Renderer
{
namespace Vulkan
{
namespace RenderProcess
{
// Uniform data decl.
namespace
{
struct UniformDataSource
{
glm::mat4 inverseProjectionMatrix;
glm::mat4 inverseViewProjectionMatrix;
glm::vec4 cameraWorldPosition;
glm::ivec4 haltonSamples;
} _uniformDataSource;
glm::vec2 _haltonSamples[HALTON_SAMPLE_COUNT];
_INTR_INLINE void initStaticUniformData()
{
// Generate Halton Samples
{
for (uint32_t i = 0u; i < HALTON_SAMPLE_COUNT; ++i)
{
_haltonSamples[i] = glm::vec2(Math::calcHaltonSequence(i, 2u),
Math::calcHaltonSequence(i, 3u));
}
}
}
}
namespace
{
struct UniformDataRef
{
UniformDataRef() { memset(this, 0x00u, sizeof(UniformDataRef)); }
UniformDataRef(const void* p_Ptr, uint32_t p_Size)
{
const uint64_t address = (uint64_t)p_Ptr;
offset = (uint16_t)(address - (uint64_t)&_uniformDataSource);
size = (uint16_t)p_Size;
}
uint16_t offset;
uint16_t size;
};
struct UniformBuffer
{
UniformBuffer() { memset(this, 0x00u, sizeof(UniformBuffer)); }
UniformDataRef refs[32u];
uint8_t refCount;
uint32_t dataSize;
void* data;
};
_INTR_HASH_MAP(Name, UniformDataRef)
_uniformOffsetMapping = {
{"InverseProjectionMatrix",
UniformDataRef(&_uniformDataSource.inverseProjectionMatrix,
sizeof(glm::mat4))},
{"InverseViewProjectionMatrix",
UniformDataRef(&_uniformDataSource.inverseViewProjectionMatrix,
sizeof(glm::mat4))},
{"CameraWorldPosition",
UniformDataRef(&_uniformDataSource.cameraWorldPosition,
sizeof(glm::vec4))},
{"HaltonSamples",
UniformDataRef(&_uniformDataSource.haltonSamples, sizeof(glm::ivec4))}};
_INTR_HASH_MAP(Name, UniformBuffer) _uniformBuffers;
uint8_t* _uniformBufferMemory = nullptr;
LinearOffsetAllocator _uniformBufferMemoryAllocator;
const uint32_t _uniformBufferMemorySizeInBytes = 2u * 1024u * 1024u;
}
// <-
void UniformManager::load(const rapidjson::Value& p_UniformBuffers)
{
if (_uniformBufferMemory)
{
free(_uniformBufferMemory);
_uniformBufferMemory = nullptr;
}
_uniformBufferMemory = (uint8_t*)malloc(_uniformBufferMemorySizeInBytes);
_uniformBufferMemoryAllocator.init(_uniformBufferMemorySizeInBytes);
_uniformBuffers.clear();
for (uint32_t bufferIdx = 0u; bufferIdx < p_UniformBuffers.Size();
++bufferIdx)
{
const rapidjson::Value& uniformBufferDesc = p_UniformBuffers[bufferIdx];
const rapidjson::Value& entryDescs = uniformBufferDesc["entries"];
UniformBuffer uniformBuffer;
for (uint32_t entryIdx = 0u; entryIdx < entryDescs.Size(); ++entryIdx)
{
const rapidjson::Value& entryDesc = entryDescs[entryIdx];
UniformDataRef entry = _uniformOffsetMapping[entryDesc.GetString()];
uniformBuffer.refs[uniformBuffer.refCount] = entry;
++uniformBuffer.refCount;
uniformBuffer.dataSize += entry.size;
}
_uniformBuffers[uniformBufferDesc["name"].GetString()] = uniformBuffer;
}
initStaticUniformData();
}
// <-
void UniformManager::updatePerFrameUniformBufferData(Dod::Ref p_Camera)
{
_uniformDataSource.inverseProjectionMatrix =
Components::CameraManager::_inverseProjectionMatrix(p_Camera);
_uniformDataSource.inverseViewProjectionMatrix =
Components::CameraManager::_inverseViewProjectionMatrix(p_Camera);
Components::NodeRef cameraNode =
Components::NodeManager::getComponentForEntity(
Components::CameraManager::_entity(p_Camera));
_uniformDataSource.cameraWorldPosition =
glm::vec4(Components::NodeManager::_worldPosition(cameraNode), 0.0f);
_uniformDataSource.haltonSamples = glm::ivec4(
(int32_t)(
_haltonSamples[TaskManager::_frameCounter % HALTON_SAMPLE_COUNT].x *
255),
(int32_t)(
_haltonSamples[TaskManager::_frameCounter % HALTON_SAMPLE_COUNT].y *
255),
0, 0);
}
// <-
void UniformManager::updateUniformBuffers()
{
for (auto it = _uniformBuffers.begin(); it != _uniformBuffers.end(); ++it)
{
UniformBuffer& uniformBuffer = it->second;
uint32_t currentOffset = 0u;
uint8_t* bufferData =
(uint8_t*)_uniformBufferMemory +
_uniformBufferMemoryAllocator.allocate(uniformBuffer.dataSize, 8u);
for (uint32_t refIdx = 0u; refIdx < uniformBuffer.refCount; ++refIdx)
{
const UniformDataRef dataRef = uniformBuffer.refs[refIdx];
memcpy(bufferData + currentOffset,
((uint8_t*)&_uniformDataSource) + dataRef.offset, dataRef.size);
currentOffset += dataRef.size;
}
uniformBuffer.data = bufferData;
}
}
// <-
void UniformManager::resetAllocator() { _uniformBufferMemoryAllocator.reset(); }
// <-
UniformBufferDataEntry
UniformManager::requestUniformBufferData(const Name& p_Name)
{
const UniformBuffer& buffer = _uniformBuffers[p_Name];
return UniformBufferDataEntry(buffer.data, buffer.dataSize);
}
}
}
}
}
<|endoftext|> |
<commit_before>//--------------------------------------------
// WHIRL PROGRAMMING LANGUAGE
// by: BigZaphod sean@fifthace.com
// http://www.bigzaphod.org/whirl/
//
// License: Public Domain
//--------------------------------------------
#include <vector>
#include <stdio.h>
#include <stdlib.h>
typedef std::vector<int> mem_t;
typedef std::vector<bool> prog_t;
mem_t memory;
prog_t program;
mem_t::iterator mem_pos;
prog_t::iterator prog_pos;
typedef enum
{
cw,
ccw
} direction_t;
class ring
{
public:
direction_t dir;
short pos;
int value;
ring() : dir(cw), pos(0), value(0) {}
void switch_dir()
{
(dir == cw)? dir = ccw: dir = cw;
}
void rotate()
{
if( dir == cw )
{
pos++;
if( pos == 12 ) pos = 0;
}
else
{
pos--;
if( pos == -1 ) pos = 11;
}
}
virtual bool execute() = 0;
};
class op_ring : public ring
{
public:
bool execute();
};
class math_ring : public ring
{
public:
bool execute();
};
op_ring ops;
math_ring math;
ring* cur = &ops;
bool next_instruction = true; // lame
bool op_ring::execute()
{
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("Cmd (%d) Executing operations cmd %d ", (int) (prog_pos - program.begin()), pos);
}
#endif
if( pos != 0 ) switch( pos )
{
// One
case 2:
value=1;
break;
// Zero
case 3:
value=0;
break;
// Load
case 4:
value=*mem_pos;
break;
// Store
case 5:
*mem_pos = value;
break;
// DAdd
case 7:
{
int t = mem_pos - memory.begin();
t += value;
if( t < 0 )
return false; // out of bounds!
if( t < (int) memory.size() )
mem_pos = memory.begin() + t;
else
{
while( (int) memory.size() <= t )
memory.push_back(0);
mem_pos = memory.begin() + t;
}
}
break;
// Logic
case 8:
if( *mem_pos != 0 )
value = value && 1;
else
value = 0;
break;
// If
case 9:
if( *mem_pos == 0 )
break;
// else fall through!
// PAdd
case 6:
{
int t = prog_pos - program.begin();
t += value;
if( t < 0 || t >= (int) program.size() )
return false; // out of bounds!
prog_pos = program.begin() + t;
next_instruction = false;
}
break;
// IntIO
case 10:
if( value == 0 )
{
// read integer
char buf[100];
int c = 0;
while( c < (int) sizeof(buf)-1 )
{
buf[c] = getchar();
c++;
buf[c] = 0;
if( buf[c-1] == '\n' )
break;
}
// swallow, just in case.
if( c == sizeof(buf) )
while( getchar() != '\n' );
(*mem_pos) = atoi( buf );
}
else
printf( "%d", *mem_pos );
break;
// AscIO
case 11:
if( value == 0 )
{
// read character
(*mem_pos) = getchar();
// The default behavior of the whirl interpreter for some reason
// is to only take the first ascii character per line. This does
// not work the way ELVM expects input to work, so this next line
// is commented out.
// while ( getchar() != '\n' )
}
else
printf( "%c", *mem_pos );
break;
// Exit
case 1:
default:
return false;
}
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("(val is %d, mem[%d] is %d)\n",
value, (int)(mem_pos - memory.begin()), *mem_pos);
}
#endif
return true;
}
bool math_ring::execute()
{
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("Cmd (%d) Executing math cmd %d ", (int) (prog_pos - program.begin()), pos);
}
#endif
if( pos != 0 ) switch( pos )
{
// Load
case 1:
value = *mem_pos;
break;
// Store
case 2:
*mem_pos = value;
break;
// Add
case 3:
value += *mem_pos;
break;
// Mult
case 4:
value *= *mem_pos;
break;
// Div
case 5:
value /= *mem_pos;
break;
// Zero
case 6:
value = 0;
break;
// <
case 7:
value < *mem_pos? value = 1: value = 0;
break;
// >
case 8:
value > *mem_pos? value = 1: value = 0;
break;
// =
case 9:
value == *mem_pos? value = 1: value = 0;
break;
// Not
case 10:
value != 0? value = 0: value = 1;
break;
// Neg
case 11:
value *= -1;
break;
// error...
default:
return false;
}
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("(val is %d, mem[%d] is %d)\n",
value, (int)(mem_pos - memory.begin()), *mem_pos);
}
#endif
return true;
}
int main( int argc, char** argv )
{
if( argc < 2 )
{
printf( "Usage: %s program.wrl\n\n", argv[0] );
exit( 1 );
}
FILE* f = fopen( argv[1], "rb" );
if( f == NULL )
{
printf( "Cannot open source file [%s].\n", argv[1] );
exit( 1 );
}
while( !feof(f) )
{
char buf = fgetc( f );
if( buf == '1' )
program.push_back( true );
else if( buf == '0' )
program.push_back( false );
}
fclose( f );
// init main memory.
memory.push_back( 0 );
mem_pos = memory.begin();
prog_pos = program.begin();
bool execute = false;
while( prog_pos != program.end() )
{
next_instruction = true;
if( *prog_pos )
{
#ifdef WHIRL_DEBUG
printf("1");
#endif
cur->rotate();
execute = false;
}
else
{
cur->switch_dir();
if( execute )
{
#ifdef WHIRL_DEBUG
printf("0\n");
#endif
if( !cur->execute() )
return 0;
(cur == &ops)? cur = &math: cur = &ops;
execute = false;
}
else {
#ifdef WHIRL_DEBUG
printf("0");
#endif
execute = true;
}
}
if( next_instruction )
prog_pos++;
}
printf( "\n" );
return 0;
}
<commit_msg>Fix warning in whirl interpreter<commit_after>//--------------------------------------------
// WHIRL PROGRAMMING LANGUAGE
// by: BigZaphod sean@fifthace.com
// http://www.bigzaphod.org/whirl/
//
// License: Public Domain
//--------------------------------------------
#include <vector>
#include <stdio.h>
#include <stdlib.h>
typedef std::vector<int> mem_t;
typedef std::vector<bool> prog_t;
mem_t memory;
prog_t program;
mem_t::iterator mem_pos;
prog_t::iterator prog_pos;
typedef enum
{
cw,
ccw
} direction_t;
class ring
{
public:
direction_t dir;
short pos;
int value;
ring() : dir(cw), pos(0), value(0) {}
void switch_dir()
{
(dir == cw)? dir = ccw: dir = cw;
}
void rotate()
{
if( dir == cw )
{
pos++;
if( pos == 12 ) pos = 0;
}
else
{
pos--;
if( pos == -1 ) pos = 11;
}
}
virtual bool execute() = 0;
};
class op_ring : public ring
{
public:
bool execute();
};
class math_ring : public ring
{
public:
bool execute();
};
op_ring ops;
math_ring math;
ring* cur = &ops;
bool next_instruction = true; // lame
bool op_ring::execute()
{
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("Cmd (%d) Executing operations cmd %d ", (int) (prog_pos - program.begin()), pos);
}
#endif
if( pos != 0 ) switch( pos )
{
// One
case 2:
value=1;
break;
// Zero
case 3:
value=0;
break;
// Load
case 4:
value=*mem_pos;
break;
// Store
case 5:
*mem_pos = value;
break;
// DAdd
case 7:
{
int t = mem_pos - memory.begin();
t += value;
if( t < 0 )
return false; // out of bounds!
if( t < (int) memory.size() )
mem_pos = memory.begin() + t;
else
{
while( (int) memory.size() <= t )
memory.push_back(0);
mem_pos = memory.begin() + t;
}
}
break;
// Logic
case 8:
if( *mem_pos != 0 )
value = (value ? 1 : 0);
else
value = 0;
break;
// If
case 9:
if( *mem_pos == 0 )
break;
// else fall through!
// PAdd
case 6:
{
int t = prog_pos - program.begin();
t += value;
if( t < 0 || t >= (int) program.size() )
return false; // out of bounds!
prog_pos = program.begin() + t;
next_instruction = false;
}
break;
// IntIO
case 10:
if( value == 0 )
{
// read integer
char buf[100];
int c = 0;
while( c < (int) sizeof(buf)-1 )
{
buf[c] = getchar();
c++;
buf[c] = 0;
if( buf[c-1] == '\n' )
break;
}
// swallow, just in case.
if( c == sizeof(buf) )
while( getchar() != '\n' );
(*mem_pos) = atoi( buf );
}
else
printf( "%d", *mem_pos );
break;
// AscIO
case 11:
if( value == 0 )
{
// read character
(*mem_pos) = getchar();
// The default behavior of the whirl interpreter for some reason
// is to only take the first ascii character per line. This does
// not work the way ELVM expects input to work, so this next line
// is commented out.
// while ( getchar() != '\n' )
}
else
printf( "%c", *mem_pos );
break;
// Exit
case 1:
default:
return false;
}
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("(val is %d, mem[%d] is %d)\n",
value, (int)(mem_pos - memory.begin()), *mem_pos);
}
#endif
return true;
}
bool math_ring::execute()
{
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("Cmd (%d) Executing math cmd %d ", (int) (prog_pos - program.begin()), pos);
}
#endif
if( pos != 0 ) switch( pos )
{
// Load
case 1:
value = *mem_pos;
break;
// Store
case 2:
*mem_pos = value;
break;
// Add
case 3:
value += *mem_pos;
break;
// Mult
case 4:
value *= *mem_pos;
break;
// Div
case 5:
value /= *mem_pos;
break;
// Zero
case 6:
value = 0;
break;
// <
case 7:
value < *mem_pos? value = 1: value = 0;
break;
// >
case 8:
value > *mem_pos? value = 1: value = 0;
break;
// =
case 9:
value == *mem_pos? value = 1: value = 0;
break;
// Not
case 10:
value != 0? value = 0: value = 1;
break;
// Neg
case 11:
value *= -1;
break;
// error...
default:
return false;
}
#ifdef WHIRL_DEBUG
if (pos != 0) {
printf("(val is %d, mem[%d] is %d)\n",
value, (int)(mem_pos - memory.begin()), *mem_pos);
}
#endif
return true;
}
int main( int argc, char** argv )
{
if( argc < 2 )
{
printf( "Usage: %s program.wrl\n\n", argv[0] );
exit( 1 );
}
FILE* f = fopen( argv[1], "rb" );
if( f == NULL )
{
printf( "Cannot open source file [%s].\n", argv[1] );
exit( 1 );
}
while( !feof(f) )
{
char buf = fgetc( f );
if( buf == '1' )
program.push_back( true );
else if( buf == '0' )
program.push_back( false );
}
fclose( f );
// init main memory.
memory.push_back( 0 );
mem_pos = memory.begin();
prog_pos = program.begin();
bool execute = false;
while( prog_pos != program.end() )
{
next_instruction = true;
if( *prog_pos )
{
#ifdef WHIRL_DEBUG
printf("1");
#endif
cur->rotate();
execute = false;
}
else
{
cur->switch_dir();
if( execute )
{
#ifdef WHIRL_DEBUG
printf("0\n");
#endif
if( !cur->execute() )
return 0;
(cur == &ops)? cur = &math: cur = &ops;
execute = false;
}
else {
#ifdef WHIRL_DEBUG
printf("0");
#endif
execute = true;
}
}
if( next_instruction )
prog_pos++;
}
printf( "\n" );
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "sstables/sstables.hh"
#include "sstables/shared_sstable.hh"
#include "sstables/index_reader.hh"
#include "sstables/binary_search.hh"
#include "sstables/writer.hh"
#include "memtable-sstable.hh"
#include "dht/i_partitioner.hh"
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/map.hpp>
#include "test/lib/test_services.hh"
#include "test/lib/sstable_test_env.hh"
#include "test/lib/reader_permit.hh"
#include "gc_clock.hh"
using namespace sstables;
using namespace std::chrono_literals;
struct local_shard_only_tag { };
using local_shard_only = bool_class<local_shard_only_tag>;
sstables::shared_sstable make_sstable_containing(std::function<sstables::shared_sstable()> sst_factory, std::vector<mutation> muts);
inline future<> write_memtable_to_sstable_for_test(memtable& mt, sstables::shared_sstable sst) {
return write_memtable_to_sstable(mt, sst, test_sstables_manager.configure_writer());
}
//
// Make set of keys sorted by token for current or remote shard.
//
std::vector<sstring> do_make_keys(unsigned n, const schema_ptr& s, size_t min_key_size, std::optional<shard_id> shard);
std::vector<sstring> do_make_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1, local_shard_only lso = local_shard_only::yes);
inline std::vector<sstring> make_keys_for_shard(shard_id shard, unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, shard);
}
inline sstring make_key_for_shard(shard_id shard, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(1, s, min_key_size, shard).front();
}
inline std::vector<sstring> make_local_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, local_shard_only::yes);
}
inline sstring make_local_key(const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(1, s, min_key_size, local_shard_only::yes).front();
}
inline std::vector<sstring> make_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, local_shard_only::no);
}
shared_sstable make_sstable(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations,
sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now());
std::vector<std::pair<sstring, dht::token>>
token_generation_for_shard(unsigned tokens_to_generate, unsigned shard,
unsigned ignore_msb = 0, unsigned smp_count = smp::count);
std::vector<std::pair<sstring, dht::token>>
token_generation_for_current_shard(unsigned tokens_to_generate);
namespace sstables {
using sstable_ptr = shared_sstable;
class test {
sstable_ptr _sst;
public:
test(sstable_ptr s) : _sst(s) {}
summary& _summary() {
return _sst->_components->summary;
}
future<temporary_buffer<char>> data_read(uint64_t pos, size_t len) {
return _sst->data_read(pos, len, default_priority_class(), tests::make_permit());
}
future<index_list> read_indexes() {
auto l = make_lw_shared<index_list>();
return do_with(std::make_unique<index_reader>(_sst, tests::make_permit(), default_priority_class(), tracing::trace_state_ptr()),
[this, l] (std::unique_ptr<index_reader>& ir) {
return ir->read_partition_data().then([&, l] {
l->push_back(std::move(ir->current_partition_entry()));
}).then([&, l] {
return repeat([&, l] {
return ir->advance_to_next_partition().then([&, l] {
if (ir->eof()) {
return stop_iteration::yes;
}
l->push_back(std::move(ir->current_partition_entry()));
return stop_iteration::no;
});
});
});
}).then([l] {
return std::move(*l);
});
}
future<> read_statistics() {
return _sst->read_statistics(default_priority_class());
}
statistics& get_statistics() {
return _sst->_components->statistics;
}
future<> read_summary() noexcept {
return _sst->read_summary(default_priority_class());
}
future<summary_entry&> read_summary_entry(size_t i) {
return _sst->read_summary_entry(i);
}
summary& get_summary() {
return _sst->_components->summary;
}
summary move_summary() {
return std::move(_sst->_components->summary);
}
future<> read_toc() noexcept {
return _sst->read_toc();
}
auto& get_components() {
return _sst->_recognized_components;
}
template <typename T>
int binary_search(const dht::i_partitioner& p, const T& entries, const key& sk) {
return sstables::binary_search(p, entries, sk);
}
void change_generation_number(int64_t generation) {
_sst->_generation = generation;
}
void change_dir(sstring dir) {
_sst->_dir = dir;
}
void set_data_file_size(uint64_t size) {
_sst->_data_file_size = size;
}
void set_data_file_write_time(db_clock::time_point wtime) {
_sst->_data_file_write_time = wtime;
}
void set_run_identifier(utils::UUID identifier) {
_sst->_run_identifier = identifier;
}
future<> store() {
_sst->_recognized_components.erase(component_type::Index);
_sst->_recognized_components.erase(component_type::Data);
return seastar::async([sst = _sst] {
sst->write_toc(default_priority_class());
sst->write_statistics(default_priority_class());
sst->write_compression(default_priority_class());
sst->write_filter(default_priority_class());
sst->write_summary(default_priority_class());
sst->seal_sstable().get();
});
}
// Used to create synthetic sstables for testing leveled compaction strategy.
void set_values_for_leveled_strategy(uint64_t fake_data_size, uint32_t sstable_level, int64_t max_timestamp, sstring first_key, sstring last_key) {
_sst->_data_file_size = fake_data_size;
// Create a synthetic stats metadata
stats_metadata stats = {};
// leveled strategy sorts sstables by age using max_timestamp, let's set it to 0.
stats.max_timestamp = max_timestamp;
stats.sstable_level = sstable_level;
_sst->_components->statistics.contents[metadata_type::Stats] = std::make_unique<stats_metadata>(std::move(stats));
_sst->_components->summary.first_key.value = bytes(reinterpret_cast<const signed char*>(first_key.c_str()), first_key.size());
_sst->_components->summary.last_key.value = bytes(reinterpret_cast<const signed char*>(last_key.c_str()), last_key.size());
_sst->set_first_and_last_keys();
_sst->_run_identifier = utils::make_random_uuid();
}
void set_values(sstring first_key, sstring last_key, stats_metadata stats) {
// scylla component must be present for a sstable to be considered fully expired.
_sst->_recognized_components.insert(component_type::Scylla);
_sst->_components->statistics.contents[metadata_type::Stats] = std::make_unique<stats_metadata>(std::move(stats));
_sst->_components->summary.first_key.value = bytes(reinterpret_cast<const signed char*>(first_key.c_str()), first_key.size());
_sst->_components->summary.last_key.value = bytes(reinterpret_cast<const signed char*>(last_key.c_str()), last_key.size());
_sst->set_first_and_last_keys();
_sst->_components->statistics.contents[metadata_type::Compaction] = std::make_unique<compaction_metadata>();
_sst->_run_identifier = utils::make_random_uuid();
}
void rewrite_toc_without_scylla_component() {
_sst->_recognized_components.erase(component_type::Scylla);
remove_file(_sst->filename(component_type::TOC)).get();
_sst->write_toc(default_priority_class());
_sst->seal_sstable().get();
}
future<> remove_component(component_type c) {
return remove_file(_sst->filename(c));
}
const sstring filename(component_type c) const {
return _sst->filename(c);
}
void set_shards(std::vector<unsigned> shards) {
_sst->_shards = std::move(shards);
}
};
inline auto replacer_fn_no_op() {
return [](sstables::compaction_completion_desc desc) -> void {};
}
template<typename AsyncAction>
requires requires (AsyncAction aa, sstables::sstable::version_types& c) { { aa(c) } -> std::same_as<future<>>; }
inline
future<> for_each_sstable_version(AsyncAction action) {
return seastar::do_for_each(all_sstable_versions, std::move(action));
}
class test_setup {
file _f;
std::function<future<> (directory_entry de)> _walker;
sstring _path;
future<> _listing_done;
static sstring& path() {
static sstring _p = "test/resource/sstables/tests-temporary";
return _p;
};
public:
test_setup(file f, sstring path)
: _f(std::move(f))
, _path(path)
, _listing_done(_f.list_directory([this] (directory_entry de) { return _remove(de); }).done()) {
}
~test_setup() {
// FIXME: discarded future.
(void)_f.close().finally([save = _f] {});
}
protected:
future<> _create_directory(sstring name) {
return make_directory(name);
}
future<> _remove(directory_entry de) {
sstring t = _path + "/" + de.name;
return file_type(t).then([t] (std::optional<directory_entry_type> det) {
auto f = make_ready_future<>();
if (!det) {
throw std::runtime_error("Can't determine file type\n");
} else if (det == directory_entry_type::directory) {
f = empty_test_dir(t);
}
return f.then([t] {
return remove_file(t);
});
});
}
future<> done() { return std::move(_listing_done); }
static future<> empty_test_dir(sstring p = path()) {
return open_directory(p).then([p] (file f) {
auto l = make_lw_shared<test_setup>(std::move(f), p);
return l->done().then([l] { });
});
}
public:
static future<> create_empty_test_dir(sstring p = path()) {
return make_directory(p).then_wrapped([p] (future<> f) {
try {
f.get();
// it's fine if the directory exists, just shut down the exceptional future message
} catch (std::exception& e) {}
return empty_test_dir(p);
});
}
static future<> do_with_tmp_directory(std::function<future<> (test_env&, sstring tmpdir_path)>&& fut) {
return seastar::async([fut = std::move(fut)] {
storage_service_for_tests ssft;
auto tmp = tmpdir();
test_env env;
fut(env, tmp.path().string()).get();
});
}
static future<> do_with_cloned_tmp_directory(sstring src, std::function<future<> (test_env&, sstring srcdir_path, sstring destdir_path)>&& fut) {
return seastar::async([fut = std::move(fut), src = std::move(src)] {
storage_service_for_tests ssft;
auto src_dir = tmpdir();
auto dest_dir = tmpdir();
for (const auto& entry : std::filesystem::directory_iterator(src.c_str())) {
std::filesystem::copy(entry.path(), src_dir.path() / entry.path().filename());
}
auto dest_path = dest_dir.path() / src.c_str();
std::filesystem::create_directories(dest_path);
test_env env;
fut(env, src_dir.path().string(), dest_path.string()).get();
});
}
};
} // namespace sstables
future<compaction_info> compact_sstables(sstables::compaction_descriptor descriptor, column_family& cf,
std::function<shared_sstable()> creator, sstables::compaction_sstable_replacer_fn replacer = sstables::replacer_fn_no_op());
<commit_msg>test: lib: sstable_utils: stop using test_sstables_manager<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "sstables/sstables.hh"
#include "sstables/shared_sstable.hh"
#include "sstables/index_reader.hh"
#include "sstables/binary_search.hh"
#include "sstables/writer.hh"
#include "memtable-sstable.hh"
#include "dht/i_partitioner.hh"
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/map.hpp>
#include "test/lib/test_services.hh"
#include "test/lib/sstable_test_env.hh"
#include "test/lib/reader_permit.hh"
#include "gc_clock.hh"
using namespace sstables;
using namespace std::chrono_literals;
struct local_shard_only_tag { };
using local_shard_only = bool_class<local_shard_only_tag>;
sstables::shared_sstable make_sstable_containing(std::function<sstables::shared_sstable()> sst_factory, std::vector<mutation> muts);
inline future<> write_memtable_to_sstable_for_test(memtable& mt, sstables::shared_sstable sst) {
return write_memtable_to_sstable(mt, sst, sst->manager().configure_writer());
}
//
// Make set of keys sorted by token for current or remote shard.
//
std::vector<sstring> do_make_keys(unsigned n, const schema_ptr& s, size_t min_key_size, std::optional<shard_id> shard);
std::vector<sstring> do_make_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1, local_shard_only lso = local_shard_only::yes);
inline std::vector<sstring> make_keys_for_shard(shard_id shard, unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, shard);
}
inline sstring make_key_for_shard(shard_id shard, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(1, s, min_key_size, shard).front();
}
inline std::vector<sstring> make_local_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, local_shard_only::yes);
}
inline sstring make_local_key(const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(1, s, min_key_size, local_shard_only::yes).front();
}
inline std::vector<sstring> make_keys(unsigned n, const schema_ptr& s, size_t min_key_size = 1) {
return do_make_keys(n, s, min_key_size, local_shard_only::no);
}
shared_sstable make_sstable(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations,
sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now());
std::vector<std::pair<sstring, dht::token>>
token_generation_for_shard(unsigned tokens_to_generate, unsigned shard,
unsigned ignore_msb = 0, unsigned smp_count = smp::count);
std::vector<std::pair<sstring, dht::token>>
token_generation_for_current_shard(unsigned tokens_to_generate);
namespace sstables {
using sstable_ptr = shared_sstable;
class test {
sstable_ptr _sst;
public:
test(sstable_ptr s) : _sst(s) {}
summary& _summary() {
return _sst->_components->summary;
}
future<temporary_buffer<char>> data_read(uint64_t pos, size_t len) {
return _sst->data_read(pos, len, default_priority_class(), tests::make_permit());
}
future<index_list> read_indexes() {
auto l = make_lw_shared<index_list>();
return do_with(std::make_unique<index_reader>(_sst, tests::make_permit(), default_priority_class(), tracing::trace_state_ptr()),
[this, l] (std::unique_ptr<index_reader>& ir) {
return ir->read_partition_data().then([&, l] {
l->push_back(std::move(ir->current_partition_entry()));
}).then([&, l] {
return repeat([&, l] {
return ir->advance_to_next_partition().then([&, l] {
if (ir->eof()) {
return stop_iteration::yes;
}
l->push_back(std::move(ir->current_partition_entry()));
return stop_iteration::no;
});
});
});
}).then([l] {
return std::move(*l);
});
}
future<> read_statistics() {
return _sst->read_statistics(default_priority_class());
}
statistics& get_statistics() {
return _sst->_components->statistics;
}
future<> read_summary() noexcept {
return _sst->read_summary(default_priority_class());
}
future<summary_entry&> read_summary_entry(size_t i) {
return _sst->read_summary_entry(i);
}
summary& get_summary() {
return _sst->_components->summary;
}
summary move_summary() {
return std::move(_sst->_components->summary);
}
future<> read_toc() noexcept {
return _sst->read_toc();
}
auto& get_components() {
return _sst->_recognized_components;
}
template <typename T>
int binary_search(const dht::i_partitioner& p, const T& entries, const key& sk) {
return sstables::binary_search(p, entries, sk);
}
void change_generation_number(int64_t generation) {
_sst->_generation = generation;
}
void change_dir(sstring dir) {
_sst->_dir = dir;
}
void set_data_file_size(uint64_t size) {
_sst->_data_file_size = size;
}
void set_data_file_write_time(db_clock::time_point wtime) {
_sst->_data_file_write_time = wtime;
}
void set_run_identifier(utils::UUID identifier) {
_sst->_run_identifier = identifier;
}
future<> store() {
_sst->_recognized_components.erase(component_type::Index);
_sst->_recognized_components.erase(component_type::Data);
return seastar::async([sst = _sst] {
sst->write_toc(default_priority_class());
sst->write_statistics(default_priority_class());
sst->write_compression(default_priority_class());
sst->write_filter(default_priority_class());
sst->write_summary(default_priority_class());
sst->seal_sstable().get();
});
}
// Used to create synthetic sstables for testing leveled compaction strategy.
void set_values_for_leveled_strategy(uint64_t fake_data_size, uint32_t sstable_level, int64_t max_timestamp, sstring first_key, sstring last_key) {
_sst->_data_file_size = fake_data_size;
// Create a synthetic stats metadata
stats_metadata stats = {};
// leveled strategy sorts sstables by age using max_timestamp, let's set it to 0.
stats.max_timestamp = max_timestamp;
stats.sstable_level = sstable_level;
_sst->_components->statistics.contents[metadata_type::Stats] = std::make_unique<stats_metadata>(std::move(stats));
_sst->_components->summary.first_key.value = bytes(reinterpret_cast<const signed char*>(first_key.c_str()), first_key.size());
_sst->_components->summary.last_key.value = bytes(reinterpret_cast<const signed char*>(last_key.c_str()), last_key.size());
_sst->set_first_and_last_keys();
_sst->_run_identifier = utils::make_random_uuid();
}
void set_values(sstring first_key, sstring last_key, stats_metadata stats) {
// scylla component must be present for a sstable to be considered fully expired.
_sst->_recognized_components.insert(component_type::Scylla);
_sst->_components->statistics.contents[metadata_type::Stats] = std::make_unique<stats_metadata>(std::move(stats));
_sst->_components->summary.first_key.value = bytes(reinterpret_cast<const signed char*>(first_key.c_str()), first_key.size());
_sst->_components->summary.last_key.value = bytes(reinterpret_cast<const signed char*>(last_key.c_str()), last_key.size());
_sst->set_first_and_last_keys();
_sst->_components->statistics.contents[metadata_type::Compaction] = std::make_unique<compaction_metadata>();
_sst->_run_identifier = utils::make_random_uuid();
}
void rewrite_toc_without_scylla_component() {
_sst->_recognized_components.erase(component_type::Scylla);
remove_file(_sst->filename(component_type::TOC)).get();
_sst->write_toc(default_priority_class());
_sst->seal_sstable().get();
}
future<> remove_component(component_type c) {
return remove_file(_sst->filename(c));
}
const sstring filename(component_type c) const {
return _sst->filename(c);
}
void set_shards(std::vector<unsigned> shards) {
_sst->_shards = std::move(shards);
}
};
inline auto replacer_fn_no_op() {
return [](sstables::compaction_completion_desc desc) -> void {};
}
template<typename AsyncAction>
requires requires (AsyncAction aa, sstables::sstable::version_types& c) { { aa(c) } -> std::same_as<future<>>; }
inline
future<> for_each_sstable_version(AsyncAction action) {
return seastar::do_for_each(all_sstable_versions, std::move(action));
}
class test_setup {
file _f;
std::function<future<> (directory_entry de)> _walker;
sstring _path;
future<> _listing_done;
static sstring& path() {
static sstring _p = "test/resource/sstables/tests-temporary";
return _p;
};
public:
test_setup(file f, sstring path)
: _f(std::move(f))
, _path(path)
, _listing_done(_f.list_directory([this] (directory_entry de) { return _remove(de); }).done()) {
}
~test_setup() {
// FIXME: discarded future.
(void)_f.close().finally([save = _f] {});
}
protected:
future<> _create_directory(sstring name) {
return make_directory(name);
}
future<> _remove(directory_entry de) {
sstring t = _path + "/" + de.name;
return file_type(t).then([t] (std::optional<directory_entry_type> det) {
auto f = make_ready_future<>();
if (!det) {
throw std::runtime_error("Can't determine file type\n");
} else if (det == directory_entry_type::directory) {
f = empty_test_dir(t);
}
return f.then([t] {
return remove_file(t);
});
});
}
future<> done() { return std::move(_listing_done); }
static future<> empty_test_dir(sstring p = path()) {
return open_directory(p).then([p] (file f) {
auto l = make_lw_shared<test_setup>(std::move(f), p);
return l->done().then([l] { });
});
}
public:
static future<> create_empty_test_dir(sstring p = path()) {
return make_directory(p).then_wrapped([p] (future<> f) {
try {
f.get();
// it's fine if the directory exists, just shut down the exceptional future message
} catch (std::exception& e) {}
return empty_test_dir(p);
});
}
static future<> do_with_tmp_directory(std::function<future<> (test_env&, sstring tmpdir_path)>&& fut) {
return seastar::async([fut = std::move(fut)] {
storage_service_for_tests ssft;
auto tmp = tmpdir();
test_env env;
fut(env, tmp.path().string()).get();
});
}
static future<> do_with_cloned_tmp_directory(sstring src, std::function<future<> (test_env&, sstring srcdir_path, sstring destdir_path)>&& fut) {
return seastar::async([fut = std::move(fut), src = std::move(src)] {
storage_service_for_tests ssft;
auto src_dir = tmpdir();
auto dest_dir = tmpdir();
for (const auto& entry : std::filesystem::directory_iterator(src.c_str())) {
std::filesystem::copy(entry.path(), src_dir.path() / entry.path().filename());
}
auto dest_path = dest_dir.path() / src.c_str();
std::filesystem::create_directories(dest_path);
test_env env;
fut(env, src_dir.path().string(), dest_path.string()).get();
});
}
};
} // namespace sstables
future<compaction_info> compact_sstables(sstables::compaction_descriptor descriptor, column_family& cf,
std::function<shared_sstable()> creator, sstables::compaction_sstable_replacer_fn replacer = sstables::replacer_fn_no_op());
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLPropertySet.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: hbrinkm $ $Date: 2007-02-21 12:26:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_OOXML_PROPERTY_SET_HXX
#define INCLUDED_OOXML_PROPERTY_SET_HXX
#include <doctok/WW8ResourceModel.hxx>
namespace ooxml
{
using namespace doctok;
class OOXMLProperty : public Sprm
{
public:
typedef boost::shared_ptr<OOXMLProperty> Pointer_t;
virtual sal_uInt32 getId() const = 0;
virtual Value::Pointer_t getValue() = 0;
virtual doctok::Reference<BinaryObj>::Pointer_t getBinary() = 0;
virtual doctok::Reference<Stream>::Pointer_t getStream() = 0;
virtual doctok::Reference<Properties>::Pointer_t getProps() = 0;
virtual string getName() const = 0;
virtual string toString() const = 0;
virtual Sprm * clone() = 0;
};
class OOXMLPropertySet : public doctok::Reference<Properties>
{
public:
virtual ~OOXMLPropertySet() {}
virtual void resolve(Properties & rHandler) = 0;
virtual string getType() const = 0;
virtual void add(OOXMLProperty::Pointer_t pProperty) = 0;
};
}
#endif // INCLUDED_OOXML_PROPERTY_SET_HXX
<commit_msg>OOXMLProperty::resolve OOXMLPropertySet::clone<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLPropertySet.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hbrinkm $ $Date: 2007-03-05 16:25:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_OOXML_PROPERTY_SET_HXX
#define INCLUDED_OOXML_PROPERTY_SET_HXX
#include <doctok/WW8ResourceModel.hxx>
namespace ooxml
{
using namespace doctok;
class OOXMLProperty : public Sprm
{
public:
typedef boost::shared_ptr<OOXMLProperty> Pointer_t;
virtual sal_uInt32 getId() const = 0;
virtual Value::Pointer_t getValue() = 0;
virtual doctok::Reference<BinaryObj>::Pointer_t getBinary() = 0;
virtual doctok::Reference<Stream>::Pointer_t getStream() = 0;
virtual doctok::Reference<Properties>::Pointer_t getProps() = 0;
virtual string getName() const = 0;
virtual string toString() const = 0;
virtual void resolve(doctok::Properties & rProperties) = 0;
virtual Sprm * clone() = 0;
};
class OOXMLPropertySet : public doctok::Reference<Properties>
{
public:
typedef boost::shared_ptr<OOXMLPropertySet> Pointer_t;
virtual ~OOXMLPropertySet() {}
virtual void resolve(Properties & rHandler) = 0;
virtual string getType() const = 0;
virtual void add(OOXMLProperty::Pointer_t pProperty) = 0;
virtual OOXMLPropertySet * clone() const = 0;
};
}
#endif // INCLUDED_OOXML_PROPERTY_SET_HXX
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <ubiquity_motor/motor_serial.h>
#include <ubiquity_motor/motor_message.h>
#include <ros/ros.h>
#include <string>
#if defined(__linux__)
#include <pty.h>
#else
#include <util.h>
#endif
class MotorSerialTests : public ::testing::Test {
protected:
virtual void SetUp() {
if (openpty(&master_fd, &slave_fd, name, NULL, NULL) == -1) {
perror("openpty");
exit(127);
}
ASSERT_TRUE(master_fd > 0);
ASSERT_TRUE(slave_fd > 0);
ASSERT_TRUE(std::string(name).length() > 0);
ros::Time::init();
motors = new MotorSerial(std::string(name), 9600, 1000);
}
virtual void TearDown() {
delete motors;
}
MotorSerial * motors;
int master_fd;
int slave_fd;
char name[100];
};
TEST_F(MotorSerialTests, readWorks){
uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 9);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, writeWorks) {
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motors->transmitCommand(version);
uint8_t arr[9];
read(master_fd, arr, 9);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
ASSERT_EQ(input, version.serialize());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Add fail test to motor_serial_test<commit_after>#include <gtest/gtest.h>
#include <ubiquity_motor/motor_serial.h>
#include <ubiquity_motor/motor_message.h>
#include <ros/ros.h>
#include <string>
#if defined(__linux__)
#include <pty.h>
#else
#include <util.h>
#endif
class MotorSerialTests : public ::testing::Test {
protected:
virtual void SetUp() {
if (openpty(&master_fd, &slave_fd, name, NULL, NULL) == -1) {
perror("openpty");
exit(127);
}
ASSERT_TRUE(master_fd > 0);
ASSERT_TRUE(slave_fd > 0);
ASSERT_TRUE(std::string(name).length() > 0);
ros::Time::init();
motors = new MotorSerial(std::string(name), 9600, 1000);
}
virtual void TearDown() {
delete motors;
}
MotorSerial * motors;
int master_fd;
int slave_fd;
char name[100];
};
TEST_F(MotorSerialTests, goodreadWorks){
uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 9);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, badreadFails){
uint8_t test[]= {0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
write(master_fd, test, 9);
ros::Rate loop(10);
int times = 0;
while(!motors->commandAvailable()) {
loop.sleep();
times++;
if(times >= 20) {
break;
}
}
if(times > 10) {
SUCCEED();
}
else {
FAIL();
}
}
TEST_F(MotorSerialTests, writeWorks) {
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motors->transmitCommand(version);
uint8_t arr[9];
read(master_fd, arr, 9);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
ASSERT_EQ(input, version.serialize());
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Ensure that gtest is the first header otherwise Windows raises an error
#include <gtest/gtest.h>
// Keep this comment to keep gtest.h above. (clang-format off/on is not working here!)
#include "device_model/data_item.hpp"
#include "observation/observation.hpp"
#include "test_utilities.hpp"
#include <list>
using namespace std;
using namespace mtconnect;
using namespace mtconnect::adapter;
using namespace mtconnect::entity;
using namespace mtconnect::observation;
using namespace std::literals;
using namespace date::literals;
class ObservationTest : public testing::Test
{
protected:
void SetUp() override
{
std::map<string, string> attributes1, attributes2;
attributes1["id"] = "1";
attributes1["name"] = "DataItemTest1";
attributes1["type"] = "PROGRAM";
attributes1["category"] = "EVENT";
m_dataItem1 = make_unique<DataItem>(attributes1);
attributes2["id"] = "3";
attributes2["name"] = "DataItemTest2";
attributes2["type"] = "POSITION";
attributes2["nativeUnits"] = "MILLIMETER";
attributes2["subType"] = "ACTUAL";
attributes2["category"] = "SAMPLE";
m_dataItem2 = make_unique<DataItem>(attributes2);
m_time = Timestamp(date::sys_days(2021_y / jan / 19_d)) + 10h + 1min;
ErrorList errors;
m_compEventA = Observation::make(m_dataItem1.get(), {{ "VALUE", "Test"s }}, m_time, errors);
m_compEventA->setSequence(2);
m_compEventB = Observation::make(m_dataItem2.get(), {{ "VALUE", 1.1231 }}, m_time + 10min, errors);
m_compEventB->setSequence(4);
}
void TearDown() override
{
m_compEventA.reset();
m_compEventB.reset();
m_dataItem1.reset();
m_dataItem2.reset();
}
ObservationPtr m_compEventA;
ObservationPtr m_compEventB;
std::unique_ptr<DataItem> m_dataItem1;
std::unique_ptr<DataItem> m_dataItem2;
Timestamp m_time;
// Helper to test values
void testValueHelper(std::map<std::string, std::string> &attributes,
const std::string &nativeUnits, float expected, const double value,
const char *file, int line)
{
attributes["nativeUnits"] = nativeUnits;
DataItem dataItem(attributes);
ErrorList errors;
ObservationPtr sample = Observation::make(&dataItem, {{"VALUE", value}}, m_time, errors);
stringstream message;
double diff = abs(expected - sample->getValue<double>());
message << "Unit conversion for " << nativeUnits << " failed, expected: " << expected
<< " and actual " << sample->getValue<double>() << " differ (" << diff << ") by more than 0.001";
failIf(diff > 0.001, message.str(), __FILE__, __LINE__);
}
};
inline ConditionPtr Cond(ObservationPtr ptr)
{
return dynamic_pointer_cast<Condition>(ptr);
}
#define TEST_VALUE(attributes, nativeUnits, expected, value) \
testValueHelper(attributes, nativeUnits, expected, value, __FILE__, __LINE__)
TEST_F(ObservationTest, GetAttributes)
{
ASSERT_EQ("1", m_compEventA->get<string>("dataItemId"));
ASSERT_EQ(m_time, m_compEventA->get<Timestamp>("timestamp"));
ASSERT_FALSE(m_compEventA->hasProperty("subType"));
ASSERT_EQ("DataItemTest1", m_compEventA->get<string>("name"));
ASSERT_EQ(2, m_compEventA->get<int64_t>("sequence"));
ASSERT_EQ("Test", m_compEventA->getValue<string>());
ASSERT_EQ("3", m_compEventB->get<string>("dataItemId"));
ASSERT_EQ(m_time + 10min, m_compEventB->get<Timestamp>("timestamp"));
ASSERT_EQ("ACTUAL", m_compEventB->get<string>("subType"));
ASSERT_EQ("DataItemTest2", m_compEventB->get<string>("name"));
ASSERT_EQ(4, m_compEventB->get<int64_t>("sequence"));
}
TEST_F(ObservationTest, Getters)
{
ASSERT_TRUE(m_dataItem1.get() == m_compEventA->getDataItem());
ASSERT_TRUE(m_dataItem2.get() == m_compEventB->getDataItem());
ASSERT_EQ("Test", m_compEventA->getValue<string>());
ASSERT_EQ(1.1231, m_compEventB->getValue<double>());
}
TEST_F(ObservationTest, ConditionEventChaining)
{
DataItem dataItem({{"id", "c1"}, {"category", "CONDITION"},
{"type","TEMPERATURE"}
});
ErrorList errors;
ConditionPtr event1 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ConditionPtr event2 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ConditionPtr event3 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ASSERT_TRUE(event1 == event1->getFirst());
event1->appendTo(event2);
ASSERT_TRUE(event1->getFirst() == event2);
event2->appendTo(event3);
ASSERT_TRUE(event1->getFirst() == event3);
ASSERT_EQ(1, event1.use_count());
ASSERT_EQ(2, event2.use_count());
ASSERT_EQ(2, event3.use_count());
ConditionList list;
event1->getConditionList(list);
ASSERT_EQ(3, list.size());
ASSERT_TRUE(list.front() == event3);
ASSERT_TRUE(list.back() == event1);
ConditionList list2;
event2->getConditionList(list2);
ASSERT_EQ(2, list2.size());
ASSERT_TRUE(list2.front() == event3);
ASSERT_TRUE(list2.back() == event2);
}
#if 0
TEST_F(ObservationTest, ConvertValue)
{
std::map<string, string> attributes;
attributes["id"] = "1";
attributes["name"] = "DataItemTest1";
attributes["type"] = "ACCELERATION";
attributes["category"] = "SAMPLE";
TEST_VALUE(attributes, "REVOLUTION/MINUTE", 2.0f, 2.0);
TEST_VALUE(attributes, "REVOLUTION/SECOND", 2.0f * 60.0f, 2.0);
TEST_VALUE(attributes, "GRAM/INCH", (2.0f / 1000.0f) / 25.4f, 2.0);
TEST_VALUE(attributes, "MILLIMETER/MINUTE^3", (2.0f) / (60.0f * 60.0f * 60.0f), 2.0);
attributes["nativeScale"] = "0.5";
TEST_VALUE(attributes, "MILLIMETER/MINUTE^3", (2.0f) / (60.0f * 60.0f * 60.0f * 0.5f), 2.0);
}
TEST_F(ObservationTest, ConvertSimpleUnits)
{
std::map<string, string> attributes;
attributes["id"] = "1";
attributes["name"] = "DataItemTest";
attributes["type"] = "ACCELERATION";
attributes["category"] = "SAMPLE";
TEST_VALUE(attributes, "INCH", 2.0f * 25.4f, 2.0);
TEST_VALUE(attributes, "FOOT", 2.0f * 304.8f, 2.0);
TEST_VALUE(attributes, "CENTIMETER", 2.0f * 10.0f, 2.0);
TEST_VALUE(attributes, "DECIMETER", 2.0f * 100.0f, 2.0);
TEST_VALUE(attributes, "METER", 2.0f * 1000.0f, 2.0);
TEST_VALUE(attributes, "FAHRENHEIT", (2.0f - 32.0f) * (5.0f / 9.0f), 2.0);
TEST_VALUE(attributes, "POUND", 2.0f * 0.45359237f, 2.0);
TEST_VALUE(attributes, "GRAM", 2.0f / 1000.0f, 2.0);
TEST_VALUE(attributes, "RADIAN", 2.0f * 57.2957795f, 2.0);
TEST_VALUE(attributes, "MINUTE", 2.0f * 60.0f, 2.0);
TEST_VALUE(attributes, "HOUR", 2.0f * 3600.0f, 2.0);
TEST_VALUE(attributes, "MILLIMETER", 2.0f, 2.0);
TEST_VALUE(attributes, "PERCENT", 2.0f, 2.0);
}
TEST_F(ObservationTest, Condition)
{
DataItem d({{"id", "c1"}, {"category", "CONDITION"},
{"type","TEMPERATURE"}, {"name", "DataItemTest1"}
});
ObservationPtr event1(new Observation(*d, time, (string) "FAULT|4321|1|HIGH|Overtemp", 123),
true);
ASSERT_EQ(Observation::FAULT, event1->getLevel());
ASSERT_EQ((string) "Overtemp", event1->getValue());
const auto &attr_list1 = event1->getAttributes();
map<string, string> attrs1;
for (const auto &attr : attr_list1)
attrs1[attr.first] = attr.second;
ASSERT_EQ((string) "TEMPERATURE", attrs1["type"]);
ASSERT_EQ((string) "123", attrs1["sequence"]);
ASSERT_EQ((string) "4321", attrs1["nativeCode"]);
ASSERT_EQ((string) "HIGH", attrs1["qualifier"]);
ASSERT_EQ((string) "1", attrs1["nativeSeverity"]);
ASSERT_EQ((string) "Fault", event1->getLevelString());
ObservationPtr event2(new Observation(*d, time, (string) "fault|4322|2|LOW|Overtemp", 123), true);
ASSERT_EQ(Observation::FAULT, event2->getLevel());
ASSERT_EQ((string) "Overtemp", event2->getValue());
const auto &attr_list2 = event2->getAttributes();
map<string, string> attrs2;
for (const auto &attr : attr_list2)
attrs2[attr.first] = attr.second;
ASSERT_EQ((string) "TEMPERATURE", attrs2["type"]);
ASSERT_EQ((string) "123", attrs2["sequence"]);
ASSERT_EQ((string) "4322", attrs2["nativeCode"]);
ASSERT_EQ((string) "LOW", attrs2["qualifier"]);
ASSERT_EQ((string) "2", attrs2["nativeSeverity"]);
ASSERT_EQ((string) "Fault", event2->getLevelString());
d.reset();
}
TEST_F(ObservationTest, TimeSeries)
{
string time("NOW");
std::map<string, string> attributes1;
attributes1["id"] = "1";
attributes1["name"] = "test";
attributes1["type"] = "TEMPERATURE";
attributes1["category"] = "SAMPLE";
attributes1["representation"] = "TIME_SERIES";
auto d = make_unique<DataItem>(attributes1);
ASSERT_TRUE(d->isTimeSeries());
ObservationPtr event1(new Observation(*d, time, (string) "6||1 2 3 4 5 6 ", 123), true);
const auto &attr_list1 = event1->getAttributes();
map<string, string> attrs1;
for (const auto &attr : attr_list1)
attrs1[attr.first] = attr.second;
ASSERT_TRUE(event1->isTimeSeries());
ASSERT_EQ(6, event1->getSampleCount());
auto values = event1->getTimeSeries();
for (auto i = 0; i < event1->getSampleCount(); i++)
{
ASSERT_EQ((float)(i + 1), values[i]);
}
ASSERT_EQ((string) "", event1->getValue());
ASSERT_EQ(0, (int)attrs1.count("sampleRate"));
ObservationPtr event2(new Observation(*d, time, (string) "7|42000|10 20 30 40 50 60 70 ", 123),
true);
const auto &attr_list2 = event2->getAttributes();
map<string, string> attrs2;
for (const auto &attr : attr_list2)
attrs2[attr.first] = attr.second;
ASSERT_TRUE(event2->isTimeSeries());
ASSERT_EQ(7, event2->getSampleCount());
ASSERT_EQ((string) "", event2->getValue());
ASSERT_EQ((string) "42000", attrs2["sampleRate"]);
values = event2->getTimeSeries();
for (auto i = 0; i < event1->getSampleCount(); i++)
{
ASSERT_EQ((float)((i + 1) * 10), values[i]);
}
d.reset();
}
TEST_F(ObservationTest, Duration)
{
string time("2011-02-18T15:52:41Z@200.1232");
std::map<string, string> attributes1;
attributes1["id"] = "1";
attributes1["name"] = "test";
attributes1["type"] = "TEMPERATURE";
attributes1["category"] = "SAMPLE";
attributes1["statistic"] = "AVERAGE";
auto d = make_unique<DataItem>(attributes1);
ObservationPtr event1(new Observation(*d, time, (string) "11.0", 123), true);
const auto &attr_list = event1->getAttributes();
map<string, string> attrs1;
for (const auto &attr : attr_list)
attrs1[attr.first] = attr.second;
ASSERT_EQ((string) "AVERAGE", attrs1["statistic"]);
ASSERT_EQ((string) "2011-02-18T15:52:41Z", attrs1["timestamp"]);
ASSERT_EQ((string) "200.1232", attrs1["duration"]);
d.reset();
}
TEST_F(ObservationTest, AssetChanged)
{
string time("2011-02-18T15:52:41Z@200.1232");
std::map<string, string> attributes1;
attributes1["id"] = "1";
attributes1["name"] = "ac";
attributes1["type"] = "ASSET_CHANGED";
attributes1["category"] = "EVENT";
auto d = make_unique<DataItem>(attributes1);
ASSERT_TRUE(d->isAssetChanged());
ObservationPtr event1(new Observation(*d, time, (string) "CuttingTool|123", 123), true);
const auto &attr_list = event1->getAttributes();
map<string, string> attrs1;
for (const auto &attr : attr_list)
attrs1[attr.first] = attr.second;
ASSERT_EQ((string) "CuttingTool", attrs1["assetType"]);
ASSERT_EQ((string) "123", event1->getValue());
d.reset();
}
#endif
<commit_msg>Moved unit tests to under appropriate tests<commit_after>//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Ensure that gtest is the first header otherwise Windows raises an error
#include <gtest/gtest.h>
// Keep this comment to keep gtest.h above. (clang-format off/on is not working here!)
#include "device_model/data_item.hpp"
#include "observation/observation.hpp"
#include "test_utilities.hpp"
#include <list>
using namespace std;
using namespace mtconnect;
using namespace mtconnect::adapter;
using namespace mtconnect::entity;
using namespace mtconnect::observation;
using namespace std::literals;
using namespace date::literals;
class ObservationTest : public testing::Test
{
protected:
void SetUp() override
{
std::map<string, string> attributes1, attributes2;
attributes1["id"] = "1";
attributes1["name"] = "DataItemTest1";
attributes1["type"] = "PROGRAM";
attributes1["category"] = "EVENT";
m_dataItem1 = make_unique<DataItem>(attributes1);
attributes2["id"] = "3";
attributes2["name"] = "DataItemTest2";
attributes2["type"] = "POSITION";
attributes2["nativeUnits"] = "MILLIMETER";
attributes2["subType"] = "ACTUAL";
attributes2["category"] = "SAMPLE";
m_dataItem2 = make_unique<DataItem>(attributes2);
m_time = Timestamp(date::sys_days(2021_y / jan / 19_d)) + 10h + 1min;
ErrorList errors;
m_compEventA = Observation::make(m_dataItem1.get(), {{ "VALUE", "Test"s }}, m_time, errors);
m_compEventA->setSequence(2);
m_compEventB = Observation::make(m_dataItem2.get(), {{ "VALUE", 1.1231 }}, m_time + 10min, errors);
m_compEventB->setSequence(4);
}
void TearDown() override
{
m_compEventA.reset();
m_compEventB.reset();
m_dataItem1.reset();
m_dataItem2.reset();
}
ObservationPtr m_compEventA;
ObservationPtr m_compEventB;
std::unique_ptr<DataItem> m_dataItem1;
std::unique_ptr<DataItem> m_dataItem2;
Timestamp m_time;
};
inline ConditionPtr Cond(ObservationPtr ptr)
{
return dynamic_pointer_cast<Condition>(ptr);
}
TEST_F(ObservationTest, GetAttributes)
{
ASSERT_EQ("1", m_compEventA->get<string>("dataItemId"));
ASSERT_EQ(m_time, m_compEventA->get<Timestamp>("timestamp"));
ASSERT_FALSE(m_compEventA->hasProperty("subType"));
ASSERT_EQ("DataItemTest1", m_compEventA->get<string>("name"));
ASSERT_EQ(2, m_compEventA->get<int64_t>("sequence"));
ASSERT_EQ("Test", m_compEventA->getValue<string>());
ASSERT_EQ("3", m_compEventB->get<string>("dataItemId"));
ASSERT_EQ(m_time + 10min, m_compEventB->get<Timestamp>("timestamp"));
ASSERT_EQ("ACTUAL", m_compEventB->get<string>("subType"));
ASSERT_EQ("DataItemTest2", m_compEventB->get<string>("name"));
ASSERT_EQ(4, m_compEventB->get<int64_t>("sequence"));
}
TEST_F(ObservationTest, Getters)
{
ASSERT_TRUE(m_dataItem1.get() == m_compEventA->getDataItem());
ASSERT_TRUE(m_dataItem2.get() == m_compEventB->getDataItem());
ASSERT_EQ("Test", m_compEventA->getValue<string>());
ASSERT_EQ(1.1231, m_compEventB->getValue<double>());
}
TEST_F(ObservationTest, ConditionEventChaining)
{
DataItem dataItem({{"id", "c1"}, {"category", "CONDITION"},
{"type","TEMPERATURE"}
});
ErrorList errors;
ConditionPtr event1 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ConditionPtr event2 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ConditionPtr event3 = Cond(Observation::make(&dataItem, {{"level", "FAULT"s}}, m_time, errors));
ASSERT_TRUE(event1 == event1->getFirst());
event1->appendTo(event2);
ASSERT_TRUE(event1->getFirst() == event2);
event2->appendTo(event3);
ASSERT_TRUE(event1->getFirst() == event3);
ASSERT_EQ(1, event1.use_count());
ASSERT_EQ(2, event2.use_count());
ASSERT_EQ(2, event3.use_count());
ConditionList list;
event1->getConditionList(list);
ASSERT_EQ(3, list.size());
ASSERT_TRUE(list.front() == event3);
ASSERT_TRUE(list.back() == event1);
ConditionList list2;
event2->getConditionList(list2);
ASSERT_EQ(2, list2.size());
ASSERT_TRUE(list2.front() == event3);
ASSERT_TRUE(list2.back() == event2);
}
<|endoftext|> |
<commit_before>#include "CNNBallDetector.h"
#include "Tools/CameraGeometry.h"
#include "Tools/PatchWork.h"
#include "Tools/BlackSpotExtractor.h"
#include "Classifier/Model1.h"
#include "Classifier/Fy1500_Conf.h"
#include "Classifier/FrugallyDeep.h"
using namespace std;
CNNBallDetector::CNNBallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPoints", "draw key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidates", "draw ball candidates", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:refinePatches", "draw refined ball key points", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPercepts", "draw ball percepts", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:extractPatches", "generate YUVC patches", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPointsBlack", "draw black key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false);
theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true);
getDebugParameterList().add(¶ms);
cnnMap = createCNNMap();
// initialize classifier selection
setClassifier(params.classifier, params.classifierClose);
}
CNNBallDetector::~CNNBallDetector()
{
getDebugParameterList().remove(¶ms);
}
void CNNBallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallCandidates().reset();
best.clear();
// update parameter
theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector);
theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID);
//theBallKeyPointExtractor->getModuleT()->calculateKeyPoints(best);
theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(best);
addPatchByLastBall();
if(best.size() > 0) {
calculateCandidates();
}
DEBUG_REQUEST("Vision:CNNBallDetector:refinePatches",
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
//BestPatchList::Patch p = theBallKeyPointExtractor->getModuleT()->refineKeyPoint(*i);
RECT_PX(ColorClasses::red, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPercepts",
for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) {
if((*iter).cameraId == cameraID) {
CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5));
}
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:extractPatches",
extractPatches();
);
if(params.providePatches)
{
providePatches();
}
else if(params.numberOfExportBestPatches > 0)
{
extractPatches();
}
DEBUG_REQUEST("Vision:CNNBallDetector:keyPointsBlack",
BestPatchList bbest;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
bbest.clear();
BlackSpotExtractor::calculateKeyPointsBlackBetter(getBallDetectorIntegralImage(), bbest, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
int idx = 0;
for(BestPatchList::reverse_iterator j = bbest.rbegin(); j != bbest.rend(); ++j) {
RECT_PX(ColorClasses::red, (*j).min.x, (*j).min.y, (*j).max.x, (*j).max.y);
if(++idx > 3) {
break;
}
}
}
);
}
std::map<string, std::shared_ptr<AbstractCNNFinder> > CNNBallDetector::createCNNMap()
{
std::map<string, std::shared_ptr<AbstractCNNFinder> > result;
// register classifiers
result.insert({ "fy1500_conf", std::make_shared<Fy1500_Conf>() });
result.insert({ "model1", std::make_shared<Model1>() });
#ifndef WIN32
result.insert({ "fdeep_fy1300", std::make_shared<FrugallyDeep>("fy1300.json")});
result.insert({ "fdeep_fy1500", std::make_shared<FrugallyDeep>("fy1500.json")});
#endif
return result;
}
void CNNBallDetector::setClassifier(const std::string& name, const std::string& nameClose)
{
auto location = cnnMap.find(name);
if(location != cnnMap.end()){
currentCNN = location->second;
}
location = cnnMap.find(nameClose);
if(location != cnnMap.end()){
currentCNNClose = location->second;
}
}
void CNNBallDetector::calculateCandidates()
{
// the used patch size
const int patch_size = 16;
// NOTE: patches are sorted in the ascending order, so start from the end to get the best patches
int index = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max))
{
// limit the max amount of evaluated keys
if(index > params.maxNumberOfKeys) {
break;
}
static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size);
patch.min = (*i).min;
patch.max = (*i).max;
if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) {
continue;
}
//
// add an additional border as post-processing
int postBorder = (int)(patch.radius()*params.postBorderFactorFar);
double selectedCNNThreshold = params.cnn.threshold;
if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away
{
postBorder = (int)(patch.radius()*params.postBorderFactorClose);
selectedCNNThreshold = params.cnn.thresholdClose;
}
// resize the patch if possible
if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) {
patch.min -= postBorder;
patch.max += postBorder;
}
// extract the pixels
PatchWork::subsampling(getImage(), getFieldColorPercept(), patch);
// (5) check contrast
if(params.checkContrast)
{
//double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size);
double stddev = PatchWork::calculateContrastIterative2nd(patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchContrast",
CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom"));
PEN("FF0000", 1); // red
Vector2i c = patch.center();
CIRCLE( c.x, c.y, stddev / 5.0);
);
// skip this patch, if contrast doesn't fullfill minimum
double selectedContrastMinimum = params.contrastMinimum;
if(patch.width() >= params.postMaxCloseSize) {
selectedContrastMinimum = params.contrastMinimumClose;
}
if(stddev <= selectedContrastMinimum) {
continue;
}
}
PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ?
params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchInImage",
unsigned int offsetX = patch.min.x;
unsigned int offsetY = patch.min.y;
unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5);
for(unsigned int x = 0; x < patch.size(); x++) {
for(unsigned int y = 0; y < patch.size(); y++)
{
unsigned char pixelY = patch.data[x*patch_size + y].pixel.y;
// draw each image pixel this patch pixel occupies
for(unsigned int px=0; px < pixelWidth; px++) {
for(unsigned int py=0; py < pixelWidth; py++) {
getDebugImageDrawings().drawPointToImage(pixelY, 128, 128,
static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py);
}
}
}
}
);
// run CNN
stopwatch.start();
std::shared_ptr<AbstractCNNFinder> cnn = currentCNN;
if(patch.width() >= params.postMaxCloseSize) {
cnn = currentCNNClose;
}
STOPWATCH_START("CNNBallDetector:predict");
cnn->predict(patch, params.cnn.meanBrightnessOffset);
STOPWATCH_STOP("CNNBallDetector:predict");
bool found = false;
double radius = cnn->getRadius();
Vector2d pos = cnn->getCenter();
if(cnn->getBallConfidence() >= selectedCNNThreshold && pos.x >= 0.0 && pos.y >= 0.0) {
found = true;
}
stopwatch.stop();
stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001);
if (found) {
// adjust the center and radius of the patch
Vector2d ballCenterInPatch(pos.x * patch.width(), pos.y*patch.width());
addBallPercept(ballCenterInPatch + patch.min, radius*patch.width());
}
DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates",
// original patch
RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
// possibly revised patch
RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y);
);
index++;
} // end if in field
} // end for
} // end calculateCandidates
/**
* Extract at most numberOfExportBestPatches for the logfile (and add it to the blackboard).
*
* WARNING: This will include the border around the patch. The resulting patch is 24x24 pixel in size
* (currently internal patches size is 16x16).
* To reconstruct the original patch, remove the border again.
*/
void CNNBallDetector::extractPatches()
{
int idx = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(idx >= params.numberOfExportBestPatches) {
break;
}
int offset = ((*i).max.x - (*i).min.x)/4;
Vector2i min = (*i).min - offset;
Vector2i max = (*i).max + offset;
if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max))
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = min;
q.max = max;
q.setSize(24);
PatchWork::subsampling(getImage(), getFieldColorPercept(), q);
idx++;
}
}
}
/** Provides all the internally generated patches in the representation */
void CNNBallDetector::providePatches()
{
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = (*i).min;
q.max = (*i).max;
q.setSize(16);
}
}
void CNNBallDetector::addBallPercept(const Vector2d& center, double radius)
{
const double ballRadius = 50.0;
MultiBallPercept::BallPercept ballPercept;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
ballRadius,
ballPercept.positionOnField))
{
ballPercept.cameraId = cameraID;
ballPercept.centerInImage = center;
ballPercept.radiusInImage = radius;
getMultiBallPercept().add(ballPercept);
getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
}
}
void CNNBallDetector::addPatchByLastBall()
{
if (getBallModel().valid)
{
Vector3d ballInField;
ballInField.x = getBallModel().positionPreview.x;
ballInField.y = getBallModel().positionPreview.y;
ballInField.z = getFieldInfo().ballRadius;
Vector2i ballInImage;
if (CameraGeometry::relativePointToImage(getCameraMatrix(), getImage().cameraInfo, ballInField, ballInImage))
{
double estimatedRadius = CameraGeometry::estimatedBallRadius(
getCameraMatrix(), getImage().cameraInfo, getFieldInfo().ballRadius,
ballInImage.x, ballInImage.y);
int border = static_cast<int>((estimatedRadius * 1.1) + 0.5);
Vector2i start = ballInImage - border;
Vector2i end = ballInImage + border;
if (start.y >= 0 && end.y < static_cast<int>(getImage().height()) && start.x >= 0 && end.x < static_cast<int>(getImage().width()))
{
DEBUG_REQUEST("Vision:CNNBallDetector:draw_projected_ball",
RECT_PX(ColorClasses::pink, start.x, start.y, end.x, end.y);
CIRCLE_PX(ColorClasses::pink, ballInImage.x, ballInImage.y, static_cast<int>(estimatedRadius));
);
best.add(
start.x,
start.y,
end.x,
end.y,
-1.0);
}
}
}
}<commit_msg>Forgot to register debug request<commit_after>#include "CNNBallDetector.h"
#include "Tools/CameraGeometry.h"
#include "Tools/PatchWork.h"
#include "Tools/BlackSpotExtractor.h"
#include "Classifier/Model1.h"
#include "Classifier/Fy1500_Conf.h"
#include "Classifier/FrugallyDeep.h"
using namespace std;
CNNBallDetector::CNNBallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPoints", "draw key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidates", "draw ball candidates", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:refinePatches", "draw refined ball key points", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPercepts", "draw ball percepts", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:draw_projected_ball","", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:extractPatches", "generate YUVC patches", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPointsBlack", "draw black key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false);
theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true);
getDebugParameterList().add(¶ms);
cnnMap = createCNNMap();
// initialize classifier selection
setClassifier(params.classifier, params.classifierClose);
}
CNNBallDetector::~CNNBallDetector()
{
getDebugParameterList().remove(¶ms);
}
void CNNBallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallCandidates().reset();
best.clear();
// update parameter
theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector);
theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID);
//theBallKeyPointExtractor->getModuleT()->calculateKeyPoints(best);
theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(best);
addPatchByLastBall();
if(best.size() > 0) {
calculateCandidates();
}
DEBUG_REQUEST("Vision:CNNBallDetector:refinePatches",
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
//BestPatchList::Patch p = theBallKeyPointExtractor->getModuleT()->refineKeyPoint(*i);
RECT_PX(ColorClasses::red, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPercepts",
for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) {
if((*iter).cameraId == cameraID) {
CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5));
}
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:extractPatches",
extractPatches();
);
if(params.providePatches)
{
providePatches();
}
else if(params.numberOfExportBestPatches > 0)
{
extractPatches();
}
DEBUG_REQUEST("Vision:CNNBallDetector:keyPointsBlack",
BestPatchList bbest;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
bbest.clear();
BlackSpotExtractor::calculateKeyPointsBlackBetter(getBallDetectorIntegralImage(), bbest, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
int idx = 0;
for(BestPatchList::reverse_iterator j = bbest.rbegin(); j != bbest.rend(); ++j) {
RECT_PX(ColorClasses::red, (*j).min.x, (*j).min.y, (*j).max.x, (*j).max.y);
if(++idx > 3) {
break;
}
}
}
);
}
std::map<string, std::shared_ptr<AbstractCNNFinder> > CNNBallDetector::createCNNMap()
{
std::map<string, std::shared_ptr<AbstractCNNFinder> > result;
// register classifiers
result.insert({ "fy1500_conf", std::make_shared<Fy1500_Conf>() });
result.insert({ "model1", std::make_shared<Model1>() });
#ifndef WIN32
result.insert({ "fdeep_fy1300", std::make_shared<FrugallyDeep>("fy1300.json")});
result.insert({ "fdeep_fy1500", std::make_shared<FrugallyDeep>("fy1500.json")});
#endif
return result;
}
void CNNBallDetector::setClassifier(const std::string& name, const std::string& nameClose)
{
auto location = cnnMap.find(name);
if(location != cnnMap.end()){
currentCNN = location->second;
}
location = cnnMap.find(nameClose);
if(location != cnnMap.end()){
currentCNNClose = location->second;
}
}
void CNNBallDetector::calculateCandidates()
{
// the used patch size
const int patch_size = 16;
// NOTE: patches are sorted in the ascending order, so start from the end to get the best patches
int index = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max))
{
// limit the max amount of evaluated keys
if(index > params.maxNumberOfKeys) {
break;
}
static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size);
patch.min = (*i).min;
patch.max = (*i).max;
if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) {
continue;
}
//
// add an additional border as post-processing
int postBorder = (int)(patch.radius()*params.postBorderFactorFar);
double selectedCNNThreshold = params.cnn.threshold;
if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away
{
postBorder = (int)(patch.radius()*params.postBorderFactorClose);
selectedCNNThreshold = params.cnn.thresholdClose;
}
// resize the patch if possible
if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) {
patch.min -= postBorder;
patch.max += postBorder;
}
// extract the pixels
PatchWork::subsampling(getImage(), getFieldColorPercept(), patch);
// (5) check contrast
if(params.checkContrast)
{
//double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size);
double stddev = PatchWork::calculateContrastIterative2nd(patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchContrast",
CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom"));
PEN("FF0000", 1); // red
Vector2i c = patch.center();
CIRCLE( c.x, c.y, stddev / 5.0);
);
// skip this patch, if contrast doesn't fullfill minimum
double selectedContrastMinimum = params.contrastMinimum;
if(patch.width() >= params.postMaxCloseSize) {
selectedContrastMinimum = params.contrastMinimumClose;
}
if(stddev <= selectedContrastMinimum) {
continue;
}
}
PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ?
params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchInImage",
unsigned int offsetX = patch.min.x;
unsigned int offsetY = patch.min.y;
unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5);
for(unsigned int x = 0; x < patch.size(); x++) {
for(unsigned int y = 0; y < patch.size(); y++)
{
unsigned char pixelY = patch.data[x*patch_size + y].pixel.y;
// draw each image pixel this patch pixel occupies
for(unsigned int px=0; px < pixelWidth; px++) {
for(unsigned int py=0; py < pixelWidth; py++) {
getDebugImageDrawings().drawPointToImage(pixelY, 128, 128,
static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py);
}
}
}
}
);
// run CNN
stopwatch.start();
std::shared_ptr<AbstractCNNFinder> cnn = currentCNN;
if(patch.width() >= params.postMaxCloseSize) {
cnn = currentCNNClose;
}
STOPWATCH_START("CNNBallDetector:predict");
cnn->predict(patch, params.cnn.meanBrightnessOffset);
STOPWATCH_STOP("CNNBallDetector:predict");
bool found = false;
double radius = cnn->getRadius();
Vector2d pos = cnn->getCenter();
if(cnn->getBallConfidence() >= selectedCNNThreshold && pos.x >= 0.0 && pos.y >= 0.0) {
found = true;
}
stopwatch.stop();
stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001);
if (found) {
// adjust the center and radius of the patch
Vector2d ballCenterInPatch(pos.x * patch.width(), pos.y*patch.width());
addBallPercept(ballCenterInPatch + patch.min, radius*patch.width());
}
DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates",
// original patch
RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
// possibly revised patch
RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y);
);
index++;
} // end if in field
} // end for
} // end calculateCandidates
/**
* Extract at most numberOfExportBestPatches for the logfile (and add it to the blackboard).
*
* WARNING: This will include the border around the patch. The resulting patch is 24x24 pixel in size
* (currently internal patches size is 16x16).
* To reconstruct the original patch, remove the border again.
*/
void CNNBallDetector::extractPatches()
{
int idx = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(idx >= params.numberOfExportBestPatches) {
break;
}
int offset = ((*i).max.x - (*i).min.x)/4;
Vector2i min = (*i).min - offset;
Vector2i max = (*i).max + offset;
if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max))
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = min;
q.max = max;
q.setSize(24);
PatchWork::subsampling(getImage(), getFieldColorPercept(), q);
idx++;
}
}
}
/** Provides all the internally generated patches in the representation */
void CNNBallDetector::providePatches()
{
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = (*i).min;
q.max = (*i).max;
q.setSize(16);
}
}
void CNNBallDetector::addBallPercept(const Vector2d& center, double radius)
{
const double ballRadius = 50.0;
MultiBallPercept::BallPercept ballPercept;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
ballRadius,
ballPercept.positionOnField))
{
ballPercept.cameraId = cameraID;
ballPercept.centerInImage = center;
ballPercept.radiusInImage = radius;
getMultiBallPercept().add(ballPercept);
getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
}
}
void CNNBallDetector::addPatchByLastBall()
{
if (getBallModel().valid)
{
Vector3d ballInField;
ballInField.x = getBallModel().positionPreview.x;
ballInField.y = getBallModel().positionPreview.y;
ballInField.z = getFieldInfo().ballRadius;
Vector2i ballInImage;
if (CameraGeometry::relativePointToImage(getCameraMatrix(), getImage().cameraInfo, ballInField, ballInImage))
{
double estimatedRadius = CameraGeometry::estimatedBallRadius(
getCameraMatrix(), getImage().cameraInfo, getFieldInfo().ballRadius,
ballInImage.x, ballInImage.y);
int border = static_cast<int>((estimatedRadius * 1.1) + 0.5);
Vector2i start = ballInImage - border;
Vector2i end = ballInImage + border;
if (start.y >= 0 && end.y < static_cast<int>(getImage().height()) && start.x >= 0 && end.x < static_cast<int>(getImage().width()))
{
DEBUG_REQUEST("Vision:CNNBallDetector:draw_projected_ball",
RECT_PX(ColorClasses::pink, start.x, start.y, end.x, end.y);
CIRCLE_PX(ColorClasses::pink, ballInImage.x, ballInImage.y, static_cast<int>(estimatedRadius));
);
best.add(
start.x,
start.y,
end.x,
end.y,
-1.0);
}
}
}
}<|endoftext|> |
<commit_before>#include "sortedList.h"
#include <iostream>
#include <assert.h>
using namespace std;
struct ListElement {
TypeElement value;
ListElement* next;
};
struct Iterator {
ListElement* current;
int index;
};
struct SortedList {
ListElement* sentinel;
Iterator* iter;
int size;
};
ListElement* & getCurrent(SortedList* list)
{
return list->iter->current;
}
void next(SortedList* list)
{
assert(getCurrent(list)->next != nullptr);
getCurrent(list) = getCurrent(list)->next;
(list->iter->index)++;
}
void begin(SortedList* list)
{
// -1
getCurrent(list) = list->sentinel;
list->iter->index = -1;
}
void moveTo(SortedList* list, int index)
{
if (index < list->iter->index) {
begin(list);
}
while (list->iter->index != index) {
next(list);
}
}
void push(TypeElement value, SortedList* list)
{
// add key to sort list
begin(list);
while (getCurrent(list)->next != nullptr && getCurrent(list)->next->value < value) {
next(list);
}
ListElement* newElement = new ListElement{value, getCurrent(list)->next};
getCurrent(list)->next = newElement;
(list->size)++;
}
int remove(SortedList* list, int index)
{
if (index < list->size && index >= 0) {
moveTo(list, index - 1);
ListElement* buffer = getCurrent(list)->next;
getCurrent(list)->next = buffer->next;
delete buffer;
(list->size)--;
return 0;
} else {
return -1;
}
}
TypeElement getValue(SortedList* list, int index)
{
if (index < list->size && index >= 0) {
moveTo(list, index);
return getCurrent(list)->value;
} else {
return -1;
}
}
int getIndex(TypeElement value, SortedList *list)
{
moveTo(list, 0);
bool isExist = true;
while (getCurrent(list)->value != value) {
if (getCurrent(list)->next != nullptr) {
next(list);
} else {
isExist = false;
break;
}
}
return (isExist ? list->iter->index : (-1));
}
int getSize(SortedList *list)
{
return list->size;
}
bool isEmpty(SortedList *list)
{
return (list->sentinel->next == nullptr);
}
void printList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
cout << getCurrent(list)->next->value << ' ';
next(list);
}
cout << endl;
}
SortedList* createList()
{
ListElement* sent = new ListElement{-1, nullptr};
Iterator* iter = new Iterator{sent, -1};
return new SortedList{sent, iter, 0};
}
void clearList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
remove(list, 0);
}
}
void deleteList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
remove(list, 0);
}
delete list->sentinel;
delete list;
}
void test()
{
SortedList* myLst = createList();
push(5, myLst);
push(4, myLst);
push(6, myLst);
printList(myLst);
cout << getValue(myLst, 1) << endl;
cout << getIndex(4, myLst) << endl;
cout << getSize(myLst) << endl;
cout << isEmpty(myLst) << endl;
printList(myLst);
clearList(myLst);
printList(myLst);
deleteList(myLst);
}
<commit_msg>getIndex fixed<commit_after>#include "sortedList.h"
#include <iostream>
#include <assert.h>
using namespace std;
struct ListElement {
TypeElement value;
ListElement* next;
};
struct Iterator {
ListElement* current;
int index;
};
struct SortedList {
ListElement* sentinel;
Iterator* iter;
int size;
};
ListElement* & getCurrent(SortedList* list)
{
return list->iter->current;
}
void next(SortedList* list)
{
assert(getCurrent(list)->next != nullptr);
getCurrent(list) = getCurrent(list)->next;
(list->iter->index)++;
}
void begin(SortedList* list)
{
// -1
getCurrent(list) = list->sentinel;
list->iter->index = -1;
}
void moveTo(SortedList* list, int index)
{
if (index < list->iter->index) {
begin(list);
}
while (list->iter->index != index) {
next(list);
}
}
void push(TypeElement value, SortedList* list)
{
// add key to sort list
begin(list);
while (getCurrent(list)->next != nullptr && getCurrent(list)->next->value < value) {
next(list);
}
ListElement* newElement = new ListElement{value, getCurrent(list)->next};
getCurrent(list)->next = newElement;
(list->size)++;
}
int remove(SortedList* list, int index)
{
if (index < list->size && index >= 0) {
moveTo(list, index - 1);
ListElement* buffer = getCurrent(list)->next;
getCurrent(list)->next = buffer->next;
delete buffer;
(list->size)--;
return 0;
} else {
return -1;
}
}
TypeElement getValue(SortedList* list, int index)
{
if (index < list->size && index >= 0) {
moveTo(list, index);
return getCurrent(list)->value;
} else {
return -1;
}
}
int getIndex(TypeElement value, SortedList *list)
{
begin(list);
bool isExist = false;
while (getCurrent(list)->next != 0) {
next(list);
if (getCurrent(list)->value == value) {
isExist = true;
break;
}
}
return (isExist ? list->iter->index : (-1));
}
int getSize(SortedList *list)
{
return list->size;
}
bool isEmpty(SortedList *list)
{
return (list->sentinel->next == nullptr);
}
void printList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
cout << getCurrent(list)->next->value << ' ';
next(list);
}
cout << endl;
}
SortedList* createList()
{
ListElement* sent = new ListElement{-1, nullptr};
Iterator* iter = new Iterator{sent, -1};
return new SortedList{sent, iter, 0};
}
void clearList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
remove(list, 0);
}
}
void deleteList(SortedList *list)
{
begin(list);
while (getCurrent(list)->next != nullptr) {
remove(list, 0);
}
delete list->sentinel;
delete list;
}
void test()
{
SortedList* myLst = createList();
push(5, myLst);
push(4, myLst);
push(6, myLst);
printList(myLst);
cout << getValue(myLst, 1) << endl;
cout << getIndex(4, myLst) << endl;
cout << getSize(myLst) << endl;
cout << isEmpty(myLst) << endl;
printList(myLst);
clearList(myLst);
printList(myLst);
deleteList(myLst);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/asyncinvoker.h"
#include "webrtc/base/asyncudpsocket.h"
#include "webrtc/base/event.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/physicalsocketserver.h"
#include "webrtc/base/socketaddress.h"
#include "webrtc/base/thread.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#if defined(WEBRTC_WIN)
#include <comdef.h> // NOLINT
#endif
using namespace rtc;
// Generates a sequence of numbers (collaboratively).
class TestGenerator {
public:
TestGenerator() : last(0), count(0) {}
int Next(int prev) {
int result = prev + last;
last = result;
count += 1;
return result;
}
int last;
int count;
};
struct TestMessage : public MessageData {
explicit TestMessage(int v) : value(v) {}
virtual ~TestMessage() {}
int value;
};
// Receives on a socket and sends by posting messages.
class SocketClient : public TestGenerator, public sigslot::has_slots<> {
public:
SocketClient(AsyncSocket* socket, const SocketAddress& addr,
Thread* post_thread, MessageHandler* phandler)
: socket_(AsyncUDPSocket::Create(socket, addr)),
post_thread_(post_thread),
post_handler_(phandler) {
socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
}
~SocketClient() {
delete socket_;
}
SocketAddress address() const { return socket_->GetLocalAddress(); }
void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
const SocketAddress& remote_addr,
const PacketTime& packet_time) {
EXPECT_EQ(size, sizeof(uint32));
uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
uint32 result = Next(prev);
post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
}
private:
AsyncUDPSocket* socket_;
Thread* post_thread_;
MessageHandler* post_handler_;
};
// Receives messages and sends on a socket.
class MessageClient : public MessageHandler, public TestGenerator {
public:
MessageClient(Thread* pth, Socket* socket)
: socket_(socket) {
}
virtual ~MessageClient() {
delete socket_;
}
virtual void OnMessage(Message *pmsg) {
TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
int result = Next(msg->value);
EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
delete msg;
}
private:
Socket* socket_;
};
class CustomThread : public rtc::Thread {
public:
CustomThread() {}
virtual ~CustomThread() { Stop(); }
bool Start() { return false; }
bool WrapCurrent() {
return Thread::WrapCurrent();
}
void UnwrapCurrent() {
Thread::UnwrapCurrent();
}
};
// A thread that does nothing when it runs and signals an event
// when it is destroyed.
class SignalWhenDestroyedThread : public Thread {
public:
SignalWhenDestroyedThread(Event* event)
: event_(event) {
}
virtual ~SignalWhenDestroyedThread() {
Stop();
event_->Set();
}
virtual void Run() {
// Do nothing.
}
private:
Event* event_;
};
// Function objects to test Thread::Invoke.
struct FunctorA {
int operator()() { return 42; }
};
class FunctorB {
public:
explicit FunctorB(bool* flag) : flag_(flag) {}
void operator()() { if (flag_) *flag_ = true; }
private:
bool* flag_;
};
struct FunctorC {
int operator()() {
Thread::Current()->ProcessMessages(50);
return 24;
}
};
// See: https://code.google.com/p/webrtc/issues/detail?id=2409
TEST(ThreadTest, DISABLED_Main) {
const SocketAddress addr("127.0.0.1", 0);
// Create the messaging client on its own thread.
Thread th1;
Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
SOCK_DGRAM);
MessageClient msg_client(&th1, socket);
// Create the socket client on its own thread.
Thread th2;
AsyncSocket* asocket =
th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
SocketClient sock_client(asocket, addr, &th1, &msg_client);
socket->Connect(sock_client.address());
th1.Start();
th2.Start();
// Get the messages started.
th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
// Give the clients a little while to run.
// Messages will be processed at 100, 300, 500, 700, 900.
Thread* th_main = Thread::Current();
th_main->ProcessMessages(1000);
// Stop the sending client. Give the receiver a bit longer to run, in case
// it is running on a machine that is under load (e.g. the build machine).
th1.Stop();
th_main->ProcessMessages(200);
th2.Stop();
// Make sure the results were correct
EXPECT_EQ(5, msg_client.count);
EXPECT_EQ(34, msg_client.last);
EXPECT_EQ(5, sock_client.count);
EXPECT_EQ(55, sock_client.last);
}
// Test that setting thread names doesn't cause a malfunction.
// There's no easy way to verify the name was set properly at this time.
TEST(ThreadTest, DISABLED_ON_MAC(Names)) {
// Default name
Thread *thread;
thread = new Thread();
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
// Name with no object parameter
EXPECT_TRUE(thread->SetName("No object", NULL));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
// Really long name
thread = new Thread();
EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
}
// Test that setting thread priorities doesn't cause a malfunction.
// There's no easy way to verify the priority was set properly at this time.
TEST(ThreadTest, DISABLED_ON_MAC(Priorities)) {
Thread *thread;
thread = new Thread();
EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
EXPECT_TRUE(thread->Start());
#if defined(WEBRTC_WIN)
EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
#else
EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
#endif
thread->Stop();
delete thread;
}
TEST(ThreadTest, DISABLED_ON_MAC(Wrap)) {
CustomThread* cthread = new CustomThread();
EXPECT_TRUE(cthread->WrapCurrent());
EXPECT_TRUE(cthread->RunningForTest());
EXPECT_FALSE(cthread->IsOwned());
cthread->UnwrapCurrent();
EXPECT_FALSE(cthread->RunningForTest());
delete cthread;
}
TEST(ThreadTest, DISABLED_ON_MAC(Invoke)) {
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functors.
EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
bool called = false;
FunctorB f2(&called);
thread.Invoke<void>(f2);
EXPECT_TRUE(called);
// Try calling bare functions.
struct LocalFuncs {
static int Func1() { return 999; }
static void Func2() {}
};
EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
thread.Invoke<void>(&LocalFuncs::Func2);
}
class AsyncInvokeTest : public testing::Test {
public:
void IntCallback(int value) {
EXPECT_EQ(expected_thread_, Thread::Current());
int_value_ = value;
}
void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
expected_thread_ = thread;
invoker->AsyncInvoke(thread, FunctorC(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
invoke_started_.Set();
}
void SetExpectedThreadForIntCallback(Thread* thread) {
expected_thread_ = thread;
}
protected:
enum { kWaitTimeout = 1000 };
AsyncInvokeTest()
: int_value_(0),
invoke_started_(true, false),
expected_thread_(NULL) {}
int int_value_;
Event invoke_started_;
Thread* expected_thread_;
};
TEST_F(AsyncInvokeTest, DISABLED_ON_MAC(FireAndForget)) {
AsyncInvoker invoker;
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
bool called = false;
invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
EXPECT_TRUE_WAIT(called, kWaitTimeout);
}
TEST_F(AsyncInvokeTest, DISABLED_ON_MAC(WithCallback)) {
AsyncInvoker invoker;
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
SetExpectedThreadForIntCallback(Thread::Current());
invoker.AsyncInvoke(&thread, FunctorA(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
}
TEST_F(AsyncInvokeTest, DISABLED_ON_MAC(CancelInvoker)) {
// Create and start the thread.
Thread thread;
thread.Start();
// Try destroying invoker during call.
{
AsyncInvoker invoker;
invoker.AsyncInvoke(&thread, FunctorC(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
}
// With invoker gone, callback should be cancelled.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, DISABLED_ON_MAC(CancelCallingThread)) {
AsyncInvoker invoker;
{ // Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
static_cast<AsyncInvokeTest*>(this),
&invoker, Thread::Current()));
// Wait for the call to begin.
ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
}
// Calling thread is gone. Return message shouldn't happen.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, DISABLED_ON_MAC(KillInvokerBeforeExecute)) {
Thread thread;
thread.Start();
{
AsyncInvoker invoker;
// Try calling functor.
thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
static_cast<AsyncInvokeTest*>(this),
&invoker, Thread::Current()));
// Wait for the call to begin.
ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
}
// Invoker is destroyed. Function should not execute.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, Flush) {
AsyncInvoker invoker;
bool flag1 = false;
bool flag2 = false;
// Queue two async calls to the current thread.
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag1));
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag2));
// Because we haven't pumped messages, these should not have run yet.
EXPECT_FALSE(flag1);
EXPECT_FALSE(flag2);
// Force them to run now.
invoker.Flush(Thread::Current());
EXPECT_TRUE(flag1);
EXPECT_TRUE(flag2);
}
TEST_F(AsyncInvokeTest, FlushWithIds) {
AsyncInvoker invoker;
bool flag1 = false;
bool flag2 = false;
// Queue two async calls to the current thread, one with a message id.
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag1),
5);
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag2));
// Because we haven't pumped messages, these should not have run yet.
EXPECT_FALSE(flag1);
EXPECT_FALSE(flag2);
// Execute pending calls with id == 5.
invoker.Flush(Thread::Current(), 5);
EXPECT_TRUE(flag1);
EXPECT_FALSE(flag2);
flag1 = false;
// Execute all pending calls. The id == 5 call should not execute again.
invoker.Flush(Thread::Current());
EXPECT_FALSE(flag1);
EXPECT_TRUE(flag2);
}
#if defined(WEBRTC_WIN)
class ComThreadTest : public testing::Test, public MessageHandler {
public:
ComThreadTest() : done_(false) {}
protected:
virtual void OnMessage(Message* message) {
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
// S_FALSE means the thread was already inited for a multithread apartment.
EXPECT_EQ(S_FALSE, hr);
if (SUCCEEDED(hr)) {
CoUninitialize();
}
done_ = true;
}
bool done_;
};
TEST_F(ComThreadTest, ComInited) {
Thread* thread = new ComThread();
EXPECT_TRUE(thread->Start());
thread->Post(this, 0);
EXPECT_TRUE_WAIT(done_, 1000);
delete thread;
}
#endif
<commit_msg>Additional disabled tests in rtc_unittests.<commit_after>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/asyncinvoker.h"
#include "webrtc/base/asyncudpsocket.h"
#include "webrtc/base/event.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/physicalsocketserver.h"
#include "webrtc/base/socketaddress.h"
#include "webrtc/base/thread.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#if defined(WEBRTC_WIN)
#include <comdef.h> // NOLINT
#endif
using namespace rtc;
// Generates a sequence of numbers (collaboratively).
class TestGenerator {
public:
TestGenerator() : last(0), count(0) {}
int Next(int prev) {
int result = prev + last;
last = result;
count += 1;
return result;
}
int last;
int count;
};
struct TestMessage : public MessageData {
explicit TestMessage(int v) : value(v) {}
virtual ~TestMessage() {}
int value;
};
// Receives on a socket and sends by posting messages.
class SocketClient : public TestGenerator, public sigslot::has_slots<> {
public:
SocketClient(AsyncSocket* socket, const SocketAddress& addr,
Thread* post_thread, MessageHandler* phandler)
: socket_(AsyncUDPSocket::Create(socket, addr)),
post_thread_(post_thread),
post_handler_(phandler) {
socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
}
~SocketClient() {
delete socket_;
}
SocketAddress address() const { return socket_->GetLocalAddress(); }
void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
const SocketAddress& remote_addr,
const PacketTime& packet_time) {
EXPECT_EQ(size, sizeof(uint32));
uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
uint32 result = Next(prev);
post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
}
private:
AsyncUDPSocket* socket_;
Thread* post_thread_;
MessageHandler* post_handler_;
};
// Receives messages and sends on a socket.
class MessageClient : public MessageHandler, public TestGenerator {
public:
MessageClient(Thread* pth, Socket* socket)
: socket_(socket) {
}
virtual ~MessageClient() {
delete socket_;
}
virtual void OnMessage(Message *pmsg) {
TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
int result = Next(msg->value);
EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
delete msg;
}
private:
Socket* socket_;
};
class CustomThread : public rtc::Thread {
public:
CustomThread() {}
virtual ~CustomThread() { Stop(); }
bool Start() { return false; }
bool WrapCurrent() {
return Thread::WrapCurrent();
}
void UnwrapCurrent() {
Thread::UnwrapCurrent();
}
};
// A thread that does nothing when it runs and signals an event
// when it is destroyed.
class SignalWhenDestroyedThread : public Thread {
public:
SignalWhenDestroyedThread(Event* event)
: event_(event) {
}
virtual ~SignalWhenDestroyedThread() {
Stop();
event_->Set();
}
virtual void Run() {
// Do nothing.
}
private:
Event* event_;
};
// Function objects to test Thread::Invoke.
struct FunctorA {
int operator()() { return 42; }
};
class FunctorB {
public:
explicit FunctorB(bool* flag) : flag_(flag) {}
void operator()() { if (flag_) *flag_ = true; }
private:
bool* flag_;
};
struct FunctorC {
int operator()() {
Thread::Current()->ProcessMessages(50);
return 24;
}
};
// See: https://code.google.com/p/webrtc/issues/detail?id=2409
TEST(ThreadTest, DISABLED_Main) {
const SocketAddress addr("127.0.0.1", 0);
// Create the messaging client on its own thread.
Thread th1;
Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
SOCK_DGRAM);
MessageClient msg_client(&th1, socket);
// Create the socket client on its own thread.
Thread th2;
AsyncSocket* asocket =
th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
SocketClient sock_client(asocket, addr, &th1, &msg_client);
socket->Connect(sock_client.address());
th1.Start();
th2.Start();
// Get the messages started.
th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
// Give the clients a little while to run.
// Messages will be processed at 100, 300, 500, 700, 900.
Thread* th_main = Thread::Current();
th_main->ProcessMessages(1000);
// Stop the sending client. Give the receiver a bit longer to run, in case
// it is running on a machine that is under load (e.g. the build machine).
th1.Stop();
th_main->ProcessMessages(200);
th2.Stop();
// Make sure the results were correct
EXPECT_EQ(5, msg_client.count);
EXPECT_EQ(34, msg_client.last);
EXPECT_EQ(5, sock_client.count);
EXPECT_EQ(55, sock_client.last);
}
// Test that setting thread names doesn't cause a malfunction.
// There's no easy way to verify the name was set properly at this time.
TEST(ThreadTest, DISABLED_ON_MAC(Names)) {
// Default name
Thread *thread;
thread = new Thread();
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
// Name with no object parameter
EXPECT_TRUE(thread->SetName("No object", NULL));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
// Really long name
thread = new Thread();
EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
}
// Test that setting thread priorities doesn't cause a malfunction.
// There's no easy way to verify the priority was set properly at this time.
TEST(ThreadTest, DISABLED_ON_MAC(Priorities)) {
Thread *thread;
thread = new Thread();
EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
EXPECT_TRUE(thread->Start());
thread->Stop();
delete thread;
thread = new Thread();
EXPECT_TRUE(thread->Start());
#if defined(WEBRTC_WIN)
EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
#else
EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
#endif
thread->Stop();
delete thread;
}
TEST(ThreadTest, DISABLED_ON_MAC(Wrap)) {
CustomThread* cthread = new CustomThread();
EXPECT_TRUE(cthread->WrapCurrent());
EXPECT_TRUE(cthread->RunningForTest());
EXPECT_FALSE(cthread->IsOwned());
cthread->UnwrapCurrent();
EXPECT_FALSE(cthread->RunningForTest());
delete cthread;
}
TEST(ThreadTest, DISABLED_ON_MAC(Invoke)) {
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functors.
EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
bool called = false;
FunctorB f2(&called);
thread.Invoke<void>(f2);
EXPECT_TRUE(called);
// Try calling bare functions.
struct LocalFuncs {
static int Func1() { return 999; }
static void Func2() {}
};
EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
thread.Invoke<void>(&LocalFuncs::Func2);
}
class AsyncInvokeTest : public testing::Test {
public:
void IntCallback(int value) {
EXPECT_EQ(expected_thread_, Thread::Current());
int_value_ = value;
}
void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
expected_thread_ = thread;
invoker->AsyncInvoke(thread, FunctorC(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
invoke_started_.Set();
}
void SetExpectedThreadForIntCallback(Thread* thread) {
expected_thread_ = thread;
}
protected:
enum { kWaitTimeout = 1000 };
AsyncInvokeTest()
: int_value_(0),
invoke_started_(true, false),
expected_thread_(NULL) {}
int int_value_;
Event invoke_started_;
Thread* expected_thread_;
};
TEST_F(AsyncInvokeTest, DISABLED_FireAndForget) {
AsyncInvoker invoker;
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
bool called = false;
invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
EXPECT_TRUE_WAIT(called, kWaitTimeout);
}
TEST_F(AsyncInvokeTest, DISABLED_WithCallback) {
AsyncInvoker invoker;
// Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
SetExpectedThreadForIntCallback(Thread::Current());
invoker.AsyncInvoke(&thread, FunctorA(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
}
TEST_F(AsyncInvokeTest, DISABLED_CancelInvoker) {
// Create and start the thread.
Thread thread;
thread.Start();
// Try destroying invoker during call.
{
AsyncInvoker invoker;
invoker.AsyncInvoke(&thread, FunctorC(),
&AsyncInvokeTest::IntCallback,
static_cast<AsyncInvokeTest*>(this));
}
// With invoker gone, callback should be cancelled.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, DISABLED_CancelCallingThread) {
AsyncInvoker invoker;
{ // Create and start the thread.
Thread thread;
thread.Start();
// Try calling functor.
thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
static_cast<AsyncInvokeTest*>(this),
&invoker, Thread::Current()));
// Wait for the call to begin.
ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
}
// Calling thread is gone. Return message shouldn't happen.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, DISABLED_KillInvokerBeforeExecute) {
Thread thread;
thread.Start();
{
AsyncInvoker invoker;
// Try calling functor.
thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
static_cast<AsyncInvokeTest*>(this),
&invoker, Thread::Current()));
// Wait for the call to begin.
ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
}
// Invoker is destroyed. Function should not execute.
Thread::Current()->ProcessMessages(kWaitTimeout);
EXPECT_EQ(0, int_value_);
}
TEST_F(AsyncInvokeTest, DISABLED_Flush) {
AsyncInvoker invoker;
bool flag1 = false;
bool flag2 = false;
// Queue two async calls to the current thread.
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag1));
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag2));
// Because we haven't pumped messages, these should not have run yet.
EXPECT_FALSE(flag1);
EXPECT_FALSE(flag2);
// Force them to run now.
invoker.Flush(Thread::Current());
EXPECT_TRUE(flag1);
EXPECT_TRUE(flag2);
}
TEST_F(AsyncInvokeTest, DISABLED_FlushWithIds) {
AsyncInvoker invoker;
bool flag1 = false;
bool flag2 = false;
// Queue two async calls to the current thread, one with a message id.
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag1),
5);
invoker.AsyncInvoke<void>(Thread::Current(),
FunctorB(&flag2));
// Because we haven't pumped messages, these should not have run yet.
EXPECT_FALSE(flag1);
EXPECT_FALSE(flag2);
// Execute pending calls with id == 5.
invoker.Flush(Thread::Current(), 5);
EXPECT_TRUE(flag1);
EXPECT_FALSE(flag2);
flag1 = false;
// Execute all pending calls. The id == 5 call should not execute again.
invoker.Flush(Thread::Current());
EXPECT_FALSE(flag1);
EXPECT_TRUE(flag2);
}
#if defined(WEBRTC_WIN)
class ComThreadTest : public testing::Test, public MessageHandler {
public:
ComThreadTest() : done_(false) {}
protected:
virtual void OnMessage(Message* message) {
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
// S_FALSE means the thread was already inited for a multithread apartment.
EXPECT_EQ(S_FALSE, hr);
if (SUCCEEDED(hr)) {
CoUninitialize();
}
done_ = true;
}
bool done_;
};
TEST_F(ComThreadTest, ComInited) {
Thread* thread = new ComThread();
EXPECT_TRUE(thread->Start());
thread->Post(this, 0);
EXPECT_TRUE_WAIT(done_, 1000);
delete thread;
}
#endif
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include <TDSet.h>
#include <TThread.h>
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
void JPetManager::run()
{
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskExecutor*> executors;
std::vector<TThread*> threads;
auto i = 0;
for (auto opt : fOptions) {
JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
executors.push_back(executor);
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
i++;
}
for (auto thread : threads) {
thread->Join();
}
for (auto executor : executors) {
delete executor;
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}
void JPetManager::parseCmdLine(int argc, char** argv)
{
JPetCmdParser parser;
fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}
JPetManager::~JPetManager()
{
/**/
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
<commit_msg>In JPetManager destructor add cleaning of param caches.<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include <TDSet.h>
#include <TThread.h>
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
void JPetManager::run()
{
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskExecutor*> executors;
std::vector<TThread*> threads;
auto i = 0;
for (auto opt : fOptions) {
JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
executors.push_back(executor);
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
i++;
}
for (auto thread : threads) {
thread->Join();
}
for (auto& executor : executors) {
if (executor) {
delete executor;
executor = 0;
}
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}
void JPetManager::parseCmdLine(int argc, char** argv)
{
JPetCmdParser parser;
fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}
JPetManager::~JPetManager()
{
/// delete shared caches for paramBanks
/// @todo I think that should be changed
JPetDBParamGetter::clearParamCache();
JPetScopeParamGetter::clearParamCache();
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
<|endoftext|> |
<commit_before>//
// kern_iokit.hpp
// Lilu
//
// Copyright © 2016-2017 vit9696. All rights reserved.
//
#ifndef kern_iokit_hpp
#define kern_iokit_hpp
#include <Headers/kern_config.hpp>
#include <Headers/kern_util.hpp>
#include <Headers/kern_patcher.hpp>
#include <libkern/c++/OSSerialize.h>
#include <IOKit/IORegistryEntry.h>
namespace WIOKit {
/**
* AppleHDAEngine::getLocation teaches us to use loop infinitely when talking to IOReg
* This feels mad and insane, since it may prevent the system from booting.
* Although this had never happened, we will use a far bigger fail-safe stop value.
*/
static constexpr size_t bruteMax {0x10000000};
/**
* Read typed OSData
*
* @param obj read object
* @param value read value
* @param name propert name
*
* @return true on success
*/
template <typename T>
inline bool getOSDataValue(const OSObject *obj, const char *name, T &value) {
if (obj) {
auto data = OSDynamicCast(OSData, obj);
if (data && data->getLength() == sizeof(T)) {
value = *static_cast<const T *>(data->getBytesNoCopy());
DBGLOG("iokit", "getOSData %s has %llX value", name, static_cast<uint64_t>(value));
return true;
} else {
SYSLOG("iokit", "getOSData %s has unexpected format", name);
}
} else {
DBGLOG("iokit", "getOSData %s was not found", name);
}
return false;
}
/**
* Read typed OSData through a temp type
*
* @param obj read object
* @param value read value
* @param name propert name
*
* @return true on success
*/
template <typename AS, typename T>
inline bool getOSDataValue(const OSObject *obj, const char *name, T &value) {
AS tmp;
if (getOSDataValue(obj, name, tmp)) {
value = static_cast<T>(tmp);
return true;
}
return false;
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename T>
inline bool getOSDataValue(const IORegistryEntry *sect, const char *name, T &value) {
return getOSDataValue(sect->getProperty(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename AS, typename T>
inline bool getOSDataValue(const IORegistryEntry *sect, const char *name, T &value) {
return getOSDataValue<AS>(sect->getProperty(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename T>
inline bool getOSDataValue(const OSDictionary *dict, const char *name, T &value) {
return getOSDataValue(dict->getObject(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename AS, typename T>
inline bool getOSDataValue(const OSDictionary *dict, const char *name, T &value) {
return getOSDataValue<AS>(dict->getObject(name), name, value);
}
/**
* Retrieve property object
*
* @param entry IORegistry entry
* @param property property name
*
* @return property object (must be released) or nullptr
*/
EXPORT LIBKERN_RETURNS_RETAINED OSSerialize *getProperty(IORegistryEntry *entry, const char *property);
/**
* Model variants
*/
struct ComputerModel {
enum {
ComputerInvalid = 0x0,
ComputerLaptop = 0x1,
ComputerDesktop = 0x2,
ComputerAny = ComputerLaptop | ComputerDesktop
};
};
/**
* PCI GPU Vendor identifiers
*/
struct VendorID {
enum : uint16_t {
ATIAMD = 0x1002,
AMDZEN = 0x1022,
NVIDIA = 0x10DE,
Intel = 0x8086,
VMware = 0x15AD,
QEMU = 0x1B36,
};
};
/**
* PCI class codes
*/
struct ClassCode {
enum : uint32_t {
VGAController = 0x030000,
// I have never seen this one, but laptops are evil.
XGAController = 0x030100,
// Some laptops use this for Optimus GPUs.
Ex3DController = 0x030200,
DisplayController = 0x038000,
PCIBridge = 0x060400,
// HDA device on some laptops like Acer Aspire VN7-592G (INSYDE).
HDAMmDevice = 0x040100,
// Watch out for PCISubclassMask, 0x040380 is common on laptops.
HDADevice = 0x040300,
// This does not seem to be documented. It works on Haswell at least.
IMEI = 0x078000,
// To ignore device subclasses.
PCISubclassMask = 0xFFFF00,
};
};
/**
* Definitions of PCI Config Registers
*/
enum PCIRegister : uint8_t {
kIOPCIConfigVendorID = 0x00,
kIOPCIConfigDeviceID = 0x02,
kIOPCIConfigCommand = 0x04,
kIOPCIConfigStatus = 0x06,
kIOPCIConfigRevisionID = 0x08,
kIOPCIConfigClassCode = 0x09,
kIOPCIConfigCacheLineSize = 0x0C,
kIOPCIConfigLatencyTimer = 0x0D,
kIOPCIConfigHeaderType = 0x0E,
kIOPCIConfigBIST = 0x0F,
kIOPCIConfigBaseAddress0 = 0x10,
kIOPCIConfigBaseAddress1 = 0x14,
kIOPCIConfigBaseAddress2 = 0x18,
kIOPCIConfigBaseAddress3 = 0x1C,
kIOPCIConfigBaseAddress4 = 0x20,
kIOPCIConfigBaseAddress5 = 0x24,
kIOPCIConfigCardBusCISPtr = 0x28,
kIOPCIConfigSubSystemVendorID = 0x2C,
kIOPCIConfigSubSystemID = 0x2E,
kIOPCIConfigExpansionROMBase = 0x30,
kIOPCIConfigCapabilitiesPtr = 0x34,
kIOPCIConfigInterruptLine = 0x3C,
kIOPCIConfigInterruptPin = 0x3D,
kIOPCIConfigMinimumGrant = 0x3E,
kIOPCIConfigMaximumLatency = 0x3F
};
/**
* Fixed offsets for PCI Config I/O virtual methods
*/
struct PCIConfigOffset {
enum : size_t {
ConfigRead32 = 0x10A,
ConfigWrite32 = 0x10B,
ConfigRead16 = 0x10C,
ConfigWrite16 = 0x10D,
ConfigRead8 = 0x10E,
ConfigWrite8 = 0x10F,
GetBusNumber = 0x11D,
GetDeviceNumber = 0x11E,
GetFunctionNumber = 0x11F
};
};
/**
* PCI Config I/O method prototypes
*/
using t_PCIConfigRead32 = uint32_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigRead16 = uint16_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigRead8 = uint8_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigWrite32 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint32_t data);
using t_PCIConfigWrite16 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint16_t data);
using t_PCIConfigWrite8 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint8_t data);
using t_PCIGetBusNumber = uint8_t (*)(IORegistryEntry *service);
using t_PCIGetDeviceNumber = uint8_t (*)(IORegistryEntry *service);
using t_PCIGetFunctionNumber = uint8_t (*)(IORegistryEntry *service);
/**
* Await for device publishing in IOService plane
*
* @param obj wait for (PCI) object publishing
*
* @retval true on success
*/
EXPORT bool awaitPublishing(IORegistryEntry *obj);
/**
* Read PCI Config register
*
* @param service IOPCIDevice-compatible service.
* @param reg PCI config register
* @param space adress space
* @param size read size for reading custom registers
*
* @return value read
*/
EXPORT uint32_t readPCIConfigValue(IORegistryEntry *service, uint32_t reg, uint32_t space = 0, uint32_t size = 0);
/**
* Retrieve PCI device address
*
* @param service IOPCIDevice-compatible service.
* @param bus bus address
* @param device device address
* @param function function address
*/
EXPORT void getDeviceAddress(IORegistryEntry *service, uint8_t &bus, uint8_t &device, uint8_t &function);
/**
* Retrieve the computer type
*
* @return valid computer type or ComputerAny
*/
EXPORT int getComputerModel() DEPRECATE("Use BaseDeviceInfo");
/**
* Retrieve computer model and/or board-id properties
*
* @param model model name output buffer or null
* @param modelsz model name output buffer size
* @param board board identifier output buffer or null
* @param boardsz board identifier output buffer size
*
* @return true if relevant properties already are available, otherwise buffers are unchanged
*/
EXPORT bool getComputerInfo(char *model, size_t modelsz, char *board, size_t boardsz) DEPRECATE("Use BaseDeviceInfo");
/**
* Retrieve an ioreg entry by path/prefix
*
* @param path an exact lookup path
* @param prefix entry prefix at path
* @param plane plane to lookup in
* @param proc process every found entry with the method
* @param brute kick ioreg until a value is found
* @param user pass some value to the callback function
*
* @return entry pointer (must NOT be released) or nullptr (on failure or in proc mode)
*/
EXPORT LIBKERN_RETURNS_NOT_RETAINED IORegistryEntry *findEntryByPrefix(const char *path, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *)=nullptr, bool brute=false, void *user=nullptr);
/**
* Retrieve an ioreg entry by path/prefix
*
* @param entry an ioreg entry to look in
* @param prefix entry prefix at path
* @param plane plane to lookup in
* @param proc process every found entry with the method
* @param brute kick ioreg until a value is found
* @param user pass some value to the callback function
*
* @return entry pointer (must NOT be released) or nullptr (on failure or in proc mode)
*/
EXPORT LIBKERN_RETURNS_NOT_RETAINED IORegistryEntry *findEntryByPrefix(IORegistryEntry *entry, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *)=nullptr, bool brute=false, void *user=nullptr);
/**
* Check if we are using prelinked kernel/kexts or not
*
* @return true when confirmed that we definitely are
*/
EXPORT bool usingPrelinkedCache();
/**
* Properly rename the device
*
* @param entry device to rename
* @param name new name
* @param compat correct compatible
*
* @return true on success
*/
EXPORT bool renameDevice(IORegistryEntry *entry, const char *name, bool compat=true);
}
#endif /* kern_iokit_hpp */
<commit_msg>WIOKit: Add the GMCH Graphics Control register definition.<commit_after>//
// kern_iokit.hpp
// Lilu
//
// Copyright © 2016-2017 vit9696. All rights reserved.
//
#ifndef kern_iokit_hpp
#define kern_iokit_hpp
#include <Headers/kern_config.hpp>
#include <Headers/kern_util.hpp>
#include <Headers/kern_patcher.hpp>
#include <libkern/c++/OSSerialize.h>
#include <IOKit/IORegistryEntry.h>
namespace WIOKit {
/**
* AppleHDAEngine::getLocation teaches us to use loop infinitely when talking to IOReg
* This feels mad and insane, since it may prevent the system from booting.
* Although this had never happened, we will use a far bigger fail-safe stop value.
*/
static constexpr size_t bruteMax {0x10000000};
/**
* Read typed OSData
*
* @param obj read object
* @param value read value
* @param name propert name
*
* @return true on success
*/
template <typename T>
inline bool getOSDataValue(const OSObject *obj, const char *name, T &value) {
if (obj) {
auto data = OSDynamicCast(OSData, obj);
if (data && data->getLength() == sizeof(T)) {
value = *static_cast<const T *>(data->getBytesNoCopy());
DBGLOG("iokit", "getOSData %s has %llX value", name, static_cast<uint64_t>(value));
return true;
} else {
SYSLOG("iokit", "getOSData %s has unexpected format", name);
}
} else {
DBGLOG("iokit", "getOSData %s was not found", name);
}
return false;
}
/**
* Read typed OSData through a temp type
*
* @param obj read object
* @param value read value
* @param name propert name
*
* @return true on success
*/
template <typename AS, typename T>
inline bool getOSDataValue(const OSObject *obj, const char *name, T &value) {
AS tmp;
if (getOSDataValue(obj, name, tmp)) {
value = static_cast<T>(tmp);
return true;
}
return false;
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename T>
inline bool getOSDataValue(const IORegistryEntry *sect, const char *name, T &value) {
return getOSDataValue(sect->getProperty(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename AS, typename T>
inline bool getOSDataValue(const IORegistryEntry *sect, const char *name, T &value) {
return getOSDataValue<AS>(sect->getProperty(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename T>
inline bool getOSDataValue(const OSDictionary *dict, const char *name, T &value) {
return getOSDataValue(dict->getObject(name), name, value);
}
/**
* Read typed OSData from IORegistryEntry
*
* @see getOSDataValue
*/
template <typename AS, typename T>
inline bool getOSDataValue(const OSDictionary *dict, const char *name, T &value) {
return getOSDataValue<AS>(dict->getObject(name), name, value);
}
/**
* Retrieve property object
*
* @param entry IORegistry entry
* @param property property name
*
* @return property object (must be released) or nullptr
*/
EXPORT LIBKERN_RETURNS_RETAINED OSSerialize *getProperty(IORegistryEntry *entry, const char *property);
/**
* Model variants
*/
struct ComputerModel {
enum {
ComputerInvalid = 0x0,
ComputerLaptop = 0x1,
ComputerDesktop = 0x2,
ComputerAny = ComputerLaptop | ComputerDesktop
};
};
/**
* PCI GPU Vendor identifiers
*/
struct VendorID {
enum : uint16_t {
ATIAMD = 0x1002,
AMDZEN = 0x1022,
NVIDIA = 0x10DE,
Intel = 0x8086,
VMware = 0x15AD,
QEMU = 0x1B36,
};
};
/**
* PCI class codes
*/
struct ClassCode {
enum : uint32_t {
VGAController = 0x030000,
// I have never seen this one, but laptops are evil.
XGAController = 0x030100,
// Some laptops use this for Optimus GPUs.
Ex3DController = 0x030200,
DisplayController = 0x038000,
PCIBridge = 0x060400,
// HDA device on some laptops like Acer Aspire VN7-592G (INSYDE).
HDAMmDevice = 0x040100,
// Watch out for PCISubclassMask, 0x040380 is common on laptops.
HDADevice = 0x040300,
// This does not seem to be documented. It works on Haswell at least.
IMEI = 0x078000,
// To ignore device subclasses.
PCISubclassMask = 0xFFFF00,
};
};
/**
* Definitions of PCI Config Registers
*/
enum PCIRegister : uint8_t {
kIOPCIConfigVendorID = 0x00,
kIOPCIConfigDeviceID = 0x02,
kIOPCIConfigCommand = 0x04,
kIOPCIConfigStatus = 0x06,
kIOPCIConfigRevisionID = 0x08,
kIOPCIConfigClassCode = 0x09,
kIOPCIConfigCacheLineSize = 0x0C,
kIOPCIConfigLatencyTimer = 0x0D,
kIOPCIConfigHeaderType = 0x0E,
kIOPCIConfigBIST = 0x0F,
kIOPCIConfigBaseAddress0 = 0x10,
kIOPCIConfigBaseAddress1 = 0x14,
kIOPCIConfigBaseAddress2 = 0x18,
kIOPCIConfigBaseAddress3 = 0x1C,
kIOPCIConfigBaseAddress4 = 0x20,
kIOPCIConfigBaseAddress5 = 0x24,
kIOPCIConfigCardBusCISPtr = 0x28,
kIOPCIConfigSubSystemVendorID = 0x2C,
kIOPCIConfigSubSystemID = 0x2E,
kIOPCIConfigExpansionROMBase = 0x30,
kIOPCIConfigCapabilitiesPtr = 0x34,
kIOPCIConfigInterruptLine = 0x3C,
kIOPCIConfigInterruptPin = 0x3D,
kIOPCIConfigMinimumGrant = 0x3E,
kIOPCIConfigMaximumLatency = 0x3F,
kIOPCIConfigGraphicsControl = 0x50
};
/**
* Fixed offsets for PCI Config I/O virtual methods
*/
struct PCIConfigOffset {
enum : size_t {
ConfigRead32 = 0x10A,
ConfigWrite32 = 0x10B,
ConfigRead16 = 0x10C,
ConfigWrite16 = 0x10D,
ConfigRead8 = 0x10E,
ConfigWrite8 = 0x10F,
GetBusNumber = 0x11D,
GetDeviceNumber = 0x11E,
GetFunctionNumber = 0x11F
};
};
/**
* PCI Config I/O method prototypes
*/
using t_PCIConfigRead32 = uint32_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigRead16 = uint16_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigRead8 = uint8_t (*)(IORegistryEntry *service, uint32_t space, uint8_t offset);
using t_PCIConfigWrite32 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint32_t data);
using t_PCIConfigWrite16 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint16_t data);
using t_PCIConfigWrite8 = void (*)(IORegistryEntry *service, uint32_t space, uint8_t offset, uint8_t data);
using t_PCIGetBusNumber = uint8_t (*)(IORegistryEntry *service);
using t_PCIGetDeviceNumber = uint8_t (*)(IORegistryEntry *service);
using t_PCIGetFunctionNumber = uint8_t (*)(IORegistryEntry *service);
/**
* Await for device publishing in IOService plane
*
* @param obj wait for (PCI) object publishing
*
* @retval true on success
*/
EXPORT bool awaitPublishing(IORegistryEntry *obj);
/**
* Read PCI Config register
*
* @param service IOPCIDevice-compatible service.
* @param reg PCI config register
* @param space adress space
* @param size read size for reading custom registers
*
* @return value read
*/
EXPORT uint32_t readPCIConfigValue(IORegistryEntry *service, uint32_t reg, uint32_t space = 0, uint32_t size = 0);
/**
* Retrieve PCI device address
*
* @param service IOPCIDevice-compatible service.
* @param bus bus address
* @param device device address
* @param function function address
*/
EXPORT void getDeviceAddress(IORegistryEntry *service, uint8_t &bus, uint8_t &device, uint8_t &function);
/**
* Retrieve the computer type
*
* @return valid computer type or ComputerAny
*/
EXPORT int getComputerModel() DEPRECATE("Use BaseDeviceInfo");
/**
* Retrieve computer model and/or board-id properties
*
* @param model model name output buffer or null
* @param modelsz model name output buffer size
* @param board board identifier output buffer or null
* @param boardsz board identifier output buffer size
*
* @return true if relevant properties already are available, otherwise buffers are unchanged
*/
EXPORT bool getComputerInfo(char *model, size_t modelsz, char *board, size_t boardsz) DEPRECATE("Use BaseDeviceInfo");
/**
* Retrieve an ioreg entry by path/prefix
*
* @param path an exact lookup path
* @param prefix entry prefix at path
* @param plane plane to lookup in
* @param proc process every found entry with the method
* @param brute kick ioreg until a value is found
* @param user pass some value to the callback function
*
* @return entry pointer (must NOT be released) or nullptr (on failure or in proc mode)
*/
EXPORT LIBKERN_RETURNS_NOT_RETAINED IORegistryEntry *findEntryByPrefix(const char *path, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *)=nullptr, bool brute=false, void *user=nullptr);
/**
* Retrieve an ioreg entry by path/prefix
*
* @param entry an ioreg entry to look in
* @param prefix entry prefix at path
* @param plane plane to lookup in
* @param proc process every found entry with the method
* @param brute kick ioreg until a value is found
* @param user pass some value to the callback function
*
* @return entry pointer (must NOT be released) or nullptr (on failure or in proc mode)
*/
EXPORT LIBKERN_RETURNS_NOT_RETAINED IORegistryEntry *findEntryByPrefix(IORegistryEntry *entry, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *)=nullptr, bool brute=false, void *user=nullptr);
/**
* Check if we are using prelinked kernel/kexts or not
*
* @return true when confirmed that we definitely are
*/
EXPORT bool usingPrelinkedCache();
/**
* Properly rename the device
*
* @param entry device to rename
* @param name new name
* @param compat correct compatible
*
* @return true on success
*/
EXPORT bool renameDevice(IORegistryEntry *entry, const char *name, bool compat=true);
}
#endif /* kern_iokit_hpp */
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993-2012 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// httpTest.cpp : Defines the entry point for the DLL application.
//
#include <map>
#include <sstream>
#include "bzfsAPI.h"
#include "bzfsHTTPAPI.h"
class Fastmap : public bzhttp_VDir, public bz_Plugin
{
public:
Fastmap(): bzhttp_VDir(),bz_Plugin(), mapData(NULL), mapDataSize(0) {}
virtual ~Fastmap()
{
Unloadable = false;
if (mapData)
free(mapData);
mapData = NULL;
};
const char* Name () { return "Fast Map";}
virtual const char* VDirName(){return "fastmap";}
virtual const char* VDirDescription(){return "Deploys maps over HTTP";}
void Init(const char* /*commandLine*/)
{
bz_debugMessage(4,"Fastmap plugin loaded");
Register(bz_eWorldFinalized);
bzhttp_RegisterVDir(this,this);
}
void Cleanup(void)
{
Flush();
bzhttp_RemoveAllVdirs(this);
}
virtual bzhttp_ePageGenStatus GeneratePage (const bzhttp_Request &,
bzhttp_Responce &responce)
{
responce.ReturnCode = e200OK;
responce.DocumentType = eOctetStream;
if (mapData && mapDataSize) {
responce.MD5Hash = md5;
responce.AddBodyData(mapData,mapDataSize);
} else {
responce.AddBodyData("404 Fastmap not Valid");
responce.ReturnCode = e404NotFound;
}
return ePageDone;
}
virtual void Event(bz_EventData * eventData)
{
if (eventData->eventType == bz_eWorldFinalized) {
if (mapData)
free(mapData);
mapData = NULL;
mapDataSize = 0;
if (!bz_getPublic() || bz_getClientWorldDownloadURL().size())
return;
mapDataSize = bz_getWorldCacheSize();
if (!mapDataSize)
return;
mapData = (char *) malloc(mapDataSize);
if (!mapData) {
mapDataSize = 0;
return;
}
bz_getWorldCacheData((unsigned char*)mapData);
md5 = bz_MD5(mapData,mapDataSize);
std::string URL = BaseURL.c_str();
bz_debugMessagef(2, "FastMap: Running local HTTP server for maps using URL %s", URL.c_str());
bz_setClientWorldDownloadURL(URL.c_str());
}
}
char *mapData;
size_t mapDataSize;
std::string md5;
};
BZ_PLUGIN(Fastmap)
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Remove unnecessary conversions from char* to std::string and back again.<commit_after>/* bzflag
* Copyright (c) 1993-2012 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// httpTest.cpp : Defines the entry point for the DLL application.
//
#include <map>
#include <sstream>
#include "bzfsAPI.h"
#include "bzfsHTTPAPI.h"
class Fastmap : public bzhttp_VDir, public bz_Plugin
{
public:
Fastmap(): bzhttp_VDir(),bz_Plugin(), mapData(NULL), mapDataSize(0) {}
virtual ~Fastmap()
{
Unloadable = false;
if (mapData)
free(mapData);
mapData = NULL;
};
const char* Name () { return "Fast Map";}
virtual const char* VDirName(){return "fastmap";}
virtual const char* VDirDescription(){return "Deploys maps over HTTP";}
void Init(const char* /*commandLine*/)
{
bz_debugMessage(4,"Fastmap plugin loaded");
Register(bz_eWorldFinalized);
bzhttp_RegisterVDir(this,this);
}
void Cleanup(void)
{
Flush();
bzhttp_RemoveAllVdirs(this);
}
virtual bzhttp_ePageGenStatus GeneratePage (const bzhttp_Request &,
bzhttp_Responce &responce)
{
responce.ReturnCode = e200OK;
responce.DocumentType = eOctetStream;
if (mapData && mapDataSize) {
responce.MD5Hash = md5;
responce.AddBodyData(mapData,mapDataSize);
} else {
responce.AddBodyData("404 Fastmap not Valid");
responce.ReturnCode = e404NotFound;
}
return ePageDone;
}
virtual void Event(bz_EventData * eventData)
{
if (eventData->eventType == bz_eWorldFinalized) {
if (mapData)
free(mapData);
mapData = NULL;
mapDataSize = 0;
if (!bz_getPublic() || bz_getClientWorldDownloadURL().size())
return;
mapDataSize = bz_getWorldCacheSize();
if (!mapDataSize)
return;
mapData = (char *) malloc(mapDataSize);
if (!mapData) {
mapDataSize = 0;
return;
}
bz_getWorldCacheData((unsigned char*)mapData);
md5 = bz_MD5(mapData,mapDataSize);
const char *URL = BaseURL.c_str();
bz_debugMessagef(2, "FastMap: Running local HTTP server for maps using URL %s", URL);
bz_setClientWorldDownloadURL(URL);
}
}
char *mapData;
size_t mapDataSize;
std::string md5;
};
BZ_PLUGIN(Fastmap)
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>// @(#)root/gl:$Name: $:$Id: TGLUtil.cxx,v 1.9 2005/08/10 16:26:35 brun Exp $
// Author: Richard Maunder 25/05/2005
/*************************************************************************
* 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. *
*************************************************************************/
// TODO: Function descriptions
// TODO: Class def - same as header!!!
#include "TGLUtil.h"
#include "TGLIncludes.h"
#include "TError.h"
#include "Riostream.h"
ClassImp(TGLVertex3)
//______________________________________________________________________________
TGLVertex3::TGLVertex3()
{
Fill(0.0);
}
//______________________________________________________________________________
TGLVertex3::TGLVertex3(Double_t x, Double_t y, Double_t z)
{
Set(x,y,z);
}
//______________________________________________________________________________
TGLVertex3::TGLVertex3(const TGLVertex3 & other)
{
Set(other);
}
//______________________________________________________________________________
TGLVertex3::~TGLVertex3()
{
}
//______________________________________________________________________________
void TGLVertex3::Shift(TGLVector3 & shift)
{
fVals[0] += shift[0];
fVals[1] += shift[1];
fVals[2] += shift[2];
}
//______________________________________________________________________________
void TGLVertex3::Shift(Double_t xDelta, Double_t yDelta, Double_t zDelta)
{
fVals[0] += xDelta;
fVals[1] += yDelta;
fVals[2] += zDelta;
}
//______________________________________________________________________________
void TGLVertex3::Dump() const
{
std::cout << "(" << fVals[0] << "," << fVals[1] << "," << fVals[2] << ")" << std::endl;
}
ClassImp(TGLVector3)
//______________________________________________________________________________
TGLVector3::TGLVector3() :
TGLVertex3()
{
}
//______________________________________________________________________________
TGLVector3::TGLVector3(Double_t x, Double_t y, Double_t z) :
TGLVertex3(x, y, z)
{
}
//______________________________________________________________________________
TGLVector3::TGLVector3(const TGLVector3 & other) :
TGLVertex3(other.fVals[0], other.fVals[1], other.fVals[2])
{
}
//______________________________________________________________________________
TGLVector3::~TGLVector3()
{
}
ClassImp(TGLRect)
//______________________________________________________________________________
TGLRect::TGLRect() :
fX(0), fY(0), fWidth(0), fHeight(0)
{
}
//______________________________________________________________________________
TGLRect::TGLRect(Int_t x, Int_t y, UInt_t width, UInt_t height) :
fX(x), fY(y), fWidth(width), fHeight(height)
{
}
//______________________________________________________________________________
TGLRect::~TGLRect()
{
}
//______________________________________________________________________________
void TGLRect::Expand(Int_t x, Int_t y)
{
Int_t delX = x - fX;
Int_t delY = y - fY;
if (delX>static_cast<Int_t>(fWidth)) {
fWidth = delX;
}
if (delY>static_cast<Int_t>(fHeight)) {
fHeight = delY;
}
if (delX<0) {
fX = x;
fWidth += -delX;
}
if (delY<0) {
fY = y;
fHeight += -delY;
}
}
//______________________________________________________________________________
Double_t TGLRect::Aspect() const
{
if (fHeight == 0) {
return 0.0;
} else {
return static_cast<Double_t>(fWidth) / static_cast<Double_t>(fHeight);
}
}
//______________________________________________________________________________
EOverlap TGLRect::Overlap(const TGLRect & other) const
{
if ((fX <= other.fX) && (fX + fWidth >= other.fX + other.fWidth) &&
(fY <= other.fY) && (fY +fHeight >= other.fY + other.fHeight)) {
return kInside;
}
else if ((fX >= other.fX + static_cast<Int_t>(other.fWidth)) ||
(fX + static_cast<Int_t>(fWidth) <= other.fX) ||
(fY >= other.fY + static_cast<Int_t>(other.fHeight)) ||
(fY + static_cast<Int_t>(fHeight) <= other.fY)) {
return kOutside;
} else {
return kPartial;
}
}
ClassImp(TGLPlane)
//______________________________________________________________________________
TGLPlane::TGLPlane()
{
// Construct a default plane of x + y + z = 0
Set(1.0, 1.0, 1.0, 0.0);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLPlane & other)
{
Set(other);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(Double_t a, Double_t b, Double_t c, Double_t d)
{
// Construct plane with equation a.x + b.y + c.z + d = 0
// with optional normalisation
Set(a, b, c, d);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(Double_t eq[4])
{
// Construct plane with equation eq[0].x + eq[1].y + eq[2].z + eq[3] = 0
// with optional normalisation
Set(eq);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLVertex3 & p1, const TGLVertex3 & p2,
const TGLVertex3 & p3)
{
// Construct plane passing through 3 supplied points
// with optional normalisation
Set(p1, p2, p3);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLVector3 & v, const TGLVertex3 & p)
{
// Construct plane with supplied normal vector, passing through point
// with optional normalisation
Set(v, p);
}
//______________________________________________________________________________
TGLPlane::~TGLPlane()
{
}
//______________________________________________________________________________
void TGLPlane::Dump() const
{
std::cout.precision(6);
std::cout << "Plane : " << fVals[0] << "x + " << fVals[1] << "y + " << fVals[2] << "z + " << fVals[3] <<
std::endl;
}
ClassImp(TGLMatrix)
//______________________________________________________________________________
TGLMatrix::TGLMatrix()
{
SetIdentity();
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(Double_t x, Double_t y, Double_t z)
{
SetIdentity();
Set(x, y, z);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLVertex3 & translation)
{
SetIdentity();
Set(translation);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLVertex3 & origin, const TGLVector3 & zAxis)
{
SetIdentity();
Set(origin, zAxis);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const Double_t vals[16])
{
Set(vals);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLMatrix & other)
{
*this = other;
}
//______________________________________________________________________________
TGLMatrix::~TGLMatrix()
{
}
//______________________________________________________________________________
void TGLMatrix::Set(Double_t x, Double_t y, Double_t z)
{
Set(TGLVertex3(x,y,z));
}
//______________________________________________________________________________
void TGLMatrix::Set(const TGLVertex3 & translation)
{
// Set the translation component of matirx - rest left unaffected
fVals[12] = translation[0];
fVals[13] = translation[1];
fVals[14] = translation[2];
}
//______________________________________________________________________________
void TGLMatrix::Set(const TGLVertex3 & origin, const TGLVector3 & z)
{
// Establish matrix transformation which when applied puts local origin at
// passed 'origin' and the local Z axis in direction 'z'. Both
// 'origin' and 'zAxisVec' are expressed in the parent frame
TGLVector3 zAxis(z);
zAxis.Normalise();
TGLVector3 axis;
if (fabsf(zAxis.X()) <= fabsf(zAxis.Y()) && fabsf(zAxis.X()) <= fabsf(zAxis.Z())) {
axis.Set(1, 0, 0);
} else if (fabsf(zAxis.Y()) <= fabsf(zAxis.X()) && fabsf(zAxis.Y()) <= fabsf(zAxis.Z())) {
axis.Set(0, 1, 0);
} else {
axis.Set(0, 0, 1);
}
TGLVector3 xAxis = Cross(zAxis, axis);
xAxis.Normalise();
TGLVector3 yAxis = Cross(zAxis, xAxis);
fVals[0] = xAxis.X(); fVals[4] = yAxis.X(); fVals[8 ] = zAxis.X(); fVals[12] = origin.X();
fVals[1] = xAxis.Y(); fVals[5] = yAxis.Y(); fVals[9 ] = zAxis.Y(); fVals[13] = origin.Y();
fVals[2] = xAxis.Z(); fVals[6] = yAxis.Z(); fVals[10] = zAxis.Z(); fVals[14] = origin.Z();
fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;
}
//______________________________________________________________________________
void TGLMatrix::Set(const Double_t vals[16])
{
for (UInt_t i=0; i < 16; i++) {
fVals[i] = vals[i];
}
}
//______________________________________________________________________________
void TGLMatrix::SetIdentity()
{
fVals[0] = 1.0; fVals[4] = 0.0; fVals[8 ] = 0.0; fVals[12] = 0.0;
fVals[1] = 0.0; fVals[5] = 1.0; fVals[9 ] = 0.0; fVals[13] = 0.0;
fVals[2] = 0.0; fVals[6] = 0.0; fVals[10] = 1.0; fVals[14] = 0.0;
fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;
}
//______________________________________________________________________________
TGLVertex3 TGLMatrix::Translation() const
{
return TGLVertex3(fVals[12], fVals[13], fVals[14]);
}
//______________________________________________________________________________
void TGLMatrix::Shift(const TGLVector3 & shift)
{
fVals[12] += shift[0];
fVals[13] += shift[1];
fVals[14] += shift[2];
}
//______________________________________________________________________________
TGLVector3 TGLMatrix::Scale() const
{
// Get local axis scaling factors
TGLVector3 x(fVals[0], fVals[1], fVals[2]);
TGLVector3 y(fVals[4], fVals[5], fVals[6]);
TGLVector3 z(fVals[8], fVals[9], fVals[10]);
return TGLVector3(x.Mag(), y.Mag(), z.Mag());
}
//______________________________________________________________________________
void TGLMatrix::SetScale(const TGLVector3 & scale)
{
// Set local axis scaling factors
TGLVector3 currentScale = Scale();
// x
if (currentScale[0] != 0.0) {
fVals[0] *= scale[0]/currentScale[0];
fVals[1] *= scale[0]/currentScale[0];
fVals[2] *= scale[0]/currentScale[0];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
// y
if (currentScale[1] != 0.0) {
fVals[4] *= scale[1]/currentScale[1];
fVals[5] *= scale[1]/currentScale[1];
fVals[6] *= scale[1]/currentScale[1];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
// z
if (currentScale[2] != 0.0) {
fVals[8] *= scale[2]/currentScale[2];
fVals[9] *= scale[2]/currentScale[2];
fVals[10] *= scale[2]/currentScale[2];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
}
//______________________________________________________________________________
void TGLMatrix::Transpose3x3()
{
// Transpose the top left 3x3 matrix component along major diagonal
// TODO: Move this fix to the TBuffer3D filling side and remove
// 0 4 8 12
// 1 5 9 13
// 2 6 10 14
// 3 7 11 15
Double_t temp = fVals[4];
fVals[4] = fVals[1];
fVals[1] = temp;
temp = fVals[8];
fVals[8] = fVals[2];
fVals[2] = temp;
temp = fVals[9];
fVals[9] = fVals[6];
fVals[6] = temp;
}
//______________________________________________________________________________
void TGLMatrix::TransformVertex(TGLVertex3 & vertex) const
{
TGLVertex3 orig = vertex;
for (UInt_t i = 0; i < 3; i++) {
vertex[i] = orig[0] * fVals[0+i] + orig[1] * fVals[4+i] +
orig[2] * fVals[8+i] + fVals[12+i];
}
}
//______________________________________________________________________________
void TGLMatrix::Dump() const
{
std::cout.precision(6);
for (Int_t x = 0; x < 4; x++) {
std::cout << "[ ";
for (Int_t y = 0; y < 4; y++) {
std::cout << fVals[y*4 + x] << " ";
}
std::cout << "]" << std::endl;
}
}
ClassImp(TGLUtil)
//______________________________________________________________________________
void TGLUtil::CheckError()
{
GLenum errCode;
const GLubyte *errString;
if ((errCode = glGetError()) != GL_NO_ERROR) {
errString = gluErrorString(errCode);
Error("TGLUtil::CheckError", (const char *)errString);
}
}
<commit_msg>From Richard: Fix Solaris compilation problem - hopefully.<commit_after>// @(#)root/gl:$Name: $:$Id: TGLUtil.cxx,v 1.10 2005/10/03 15:19:35 brun Exp $
// Author: Richard Maunder 25/05/2005
/*************************************************************************
* 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. *
*************************************************************************/
// TODO: Function descriptions
// TODO: Class def - same as header!!!
#include "TGLUtil.h"
#include "TGLIncludes.h"
#include "TError.h"
#include "Riostream.h"
ClassImp(TGLVertex3)
//______________________________________________________________________________
TGLVertex3::TGLVertex3()
{
Fill(0.0);
}
//______________________________________________________________________________
TGLVertex3::TGLVertex3(Double_t x, Double_t y, Double_t z)
{
Set(x,y,z);
}
//______________________________________________________________________________
TGLVertex3::TGLVertex3(const TGLVertex3 & other)
{
Set(other);
}
//______________________________________________________________________________
TGLVertex3::~TGLVertex3()
{
}
//______________________________________________________________________________
void TGLVertex3::Shift(TGLVector3 & shift)
{
fVals[0] += shift[0];
fVals[1] += shift[1];
fVals[2] += shift[2];
}
//______________________________________________________________________________
void TGLVertex3::Shift(Double_t xDelta, Double_t yDelta, Double_t zDelta)
{
fVals[0] += xDelta;
fVals[1] += yDelta;
fVals[2] += zDelta;
}
//______________________________________________________________________________
void TGLVertex3::Dump() const
{
std::cout << "(" << fVals[0] << "," << fVals[1] << "," << fVals[2] << ")" << std::endl;
}
ClassImp(TGLVector3)
//______________________________________________________________________________
TGLVector3::TGLVector3() :
TGLVertex3()
{
}
//______________________________________________________________________________
TGLVector3::TGLVector3(Double_t x, Double_t y, Double_t z) :
TGLVertex3(x, y, z)
{
}
//______________________________________________________________________________
TGLVector3::TGLVector3(const TGLVector3 & other) :
TGLVertex3(other.fVals[0], other.fVals[1], other.fVals[2])
{
}
//______________________________________________________________________________
TGLVector3::~TGLVector3()
{
}
ClassImp(TGLRect)
//______________________________________________________________________________
TGLRect::TGLRect() :
fX(0), fY(0), fWidth(0), fHeight(0)
{
}
//______________________________________________________________________________
TGLRect::TGLRect(Int_t x, Int_t y, UInt_t width, UInt_t height) :
fX(x), fY(y), fWidth(width), fHeight(height)
{
}
//______________________________________________________________________________
TGLRect::~TGLRect()
{
}
//______________________________________________________________________________
void TGLRect::Expand(Int_t x, Int_t y)
{
Int_t delX = x - fX;
Int_t delY = y - fY;
if (delX>static_cast<Int_t>(fWidth)) {
fWidth = delX;
}
if (delY>static_cast<Int_t>(fHeight)) {
fHeight = delY;
}
if (delX<0) {
fX = x;
fWidth += -delX;
}
if (delY<0) {
fY = y;
fHeight += -delY;
}
}
//______________________________________________________________________________
Double_t TGLRect::Aspect() const
{
if (fHeight == 0) {
return 0.0;
} else {
return static_cast<Double_t>(fWidth) / static_cast<Double_t>(fHeight);
}
}
//______________________________________________________________________________
EOverlap TGLRect::Overlap(const TGLRect & other) const
{
if ((fX <= other.fX) && (fX + fWidth >= other.fX + other.fWidth) &&
(fY <= other.fY) && (fY +fHeight >= other.fY + other.fHeight)) {
return kInside;
}
else if ((fX >= other.fX + static_cast<Int_t>(other.fWidth)) ||
(fX + static_cast<Int_t>(fWidth) <= other.fX) ||
(fY >= other.fY + static_cast<Int_t>(other.fHeight)) ||
(fY + static_cast<Int_t>(fHeight) <= other.fY)) {
return kOutside;
} else {
return kPartial;
}
}
ClassImp(TGLPlane)
//______________________________________________________________________________
TGLPlane::TGLPlane()
{
// Construct a default plane of x + y + z = 0
Set(1.0, 1.0, 1.0, 0.0);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLPlane & other)
{
Set(other);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(Double_t a, Double_t b, Double_t c, Double_t d)
{
// Construct plane with equation a.x + b.y + c.z + d = 0
// with optional normalisation
Set(a, b, c, d);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(Double_t eq[4])
{
// Construct plane with equation eq[0].x + eq[1].y + eq[2].z + eq[3] = 0
// with optional normalisation
Set(eq);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLVertex3 & p1, const TGLVertex3 & p2,
const TGLVertex3 & p3)
{
// Construct plane passing through 3 supplied points
// with optional normalisation
Set(p1, p2, p3);
}
//______________________________________________________________________________
TGLPlane::TGLPlane(const TGLVector3 & v, const TGLVertex3 & p)
{
// Construct plane with supplied normal vector, passing through point
// with optional normalisation
Set(v, p);
}
//______________________________________________________________________________
TGLPlane::~TGLPlane()
{
}
//______________________________________________________________________________
void TGLPlane::Dump() const
{
std::cout.precision(6);
std::cout << "Plane : " << fVals[0] << "x + " << fVals[1] << "y + " << fVals[2] << "z + " << fVals[3] <<
std::endl;
}
ClassImp(TGLMatrix)
//______________________________________________________________________________
TGLMatrix::TGLMatrix()
{
SetIdentity();
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(Double_t x, Double_t y, Double_t z)
{
SetIdentity();
Set(x, y, z);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLVertex3 & translation)
{
SetIdentity();
Set(translation);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLVertex3 & origin, const TGLVector3 & zAxis)
{
SetIdentity();
Set(origin, zAxis);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const Double_t vals[16])
{
Set(vals);
}
//______________________________________________________________________________
TGLMatrix::TGLMatrix(const TGLMatrix & other)
{
*this = other;
}
//______________________________________________________________________________
TGLMatrix::~TGLMatrix()
{
}
//______________________________________________________________________________
void TGLMatrix::Set(Double_t x, Double_t y, Double_t z)
{
Set(TGLVertex3(x,y,z));
}
//______________________________________________________________________________
void TGLMatrix::Set(const TGLVertex3 & translation)
{
// Set the translation component of matirx - rest left unaffected
fVals[12] = translation[0];
fVals[13] = translation[1];
fVals[14] = translation[2];
}
//______________________________________________________________________________
void TGLMatrix::Set(const TGLVertex3 & origin, const TGLVector3 & z)
{
// Establish matrix transformation which when applied puts local origin at
// passed 'origin' and the local Z axis in direction 'z'. Both
// 'origin' and 'zAxisVec' are expressed in the parent frame
TGLVector3 zAxis(z);
zAxis.Normalise();
TGLVector3 axis;
if (fabs(zAxis.X()) <= fabs(zAxis.Y()) && fabs(zAxis.X()) <= fabs(zAxis.Z())) {
axis.Set(1, 0, 0);
} else if (fabs(zAxis.Y()) <= fabs(zAxis.X()) && fabs(zAxis.Y()) <= fabs(zAxis.Z())) {
axis.Set(0, 1, 0);
} else {
axis.Set(0, 0, 1);
}
TGLVector3 xAxis = Cross(zAxis, axis);
xAxis.Normalise();
TGLVector3 yAxis = Cross(zAxis, xAxis);
fVals[0] = xAxis.X(); fVals[4] = yAxis.X(); fVals[8 ] = zAxis.X(); fVals[12] = origin.X();
fVals[1] = xAxis.Y(); fVals[5] = yAxis.Y(); fVals[9 ] = zAxis.Y(); fVals[13] = origin.Y();
fVals[2] = xAxis.Z(); fVals[6] = yAxis.Z(); fVals[10] = zAxis.Z(); fVals[14] = origin.Z();
fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;
}
//______________________________________________________________________________
void TGLMatrix::Set(const Double_t vals[16])
{
for (UInt_t i=0; i < 16; i++) {
fVals[i] = vals[i];
}
}
//______________________________________________________________________________
void TGLMatrix::SetIdentity()
{
fVals[0] = 1.0; fVals[4] = 0.0; fVals[8 ] = 0.0; fVals[12] = 0.0;
fVals[1] = 0.0; fVals[5] = 1.0; fVals[9 ] = 0.0; fVals[13] = 0.0;
fVals[2] = 0.0; fVals[6] = 0.0; fVals[10] = 1.0; fVals[14] = 0.0;
fVals[3] = 0.0; fVals[7] = 0.0; fVals[11] = 0.0; fVals[15] = 1.0;
}
//______________________________________________________________________________
TGLVertex3 TGLMatrix::Translation() const
{
return TGLVertex3(fVals[12], fVals[13], fVals[14]);
}
//______________________________________________________________________________
void TGLMatrix::Shift(const TGLVector3 & shift)
{
fVals[12] += shift[0];
fVals[13] += shift[1];
fVals[14] += shift[2];
}
//______________________________________________________________________________
TGLVector3 TGLMatrix::Scale() const
{
// Get local axis scaling factors
TGLVector3 x(fVals[0], fVals[1], fVals[2]);
TGLVector3 y(fVals[4], fVals[5], fVals[6]);
TGLVector3 z(fVals[8], fVals[9], fVals[10]);
return TGLVector3(x.Mag(), y.Mag(), z.Mag());
}
//______________________________________________________________________________
void TGLMatrix::SetScale(const TGLVector3 & scale)
{
// Set local axis scaling factors
TGLVector3 currentScale = Scale();
// x
if (currentScale[0] != 0.0) {
fVals[0] *= scale[0]/currentScale[0];
fVals[1] *= scale[0]/currentScale[0];
fVals[2] *= scale[0]/currentScale[0];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
// y
if (currentScale[1] != 0.0) {
fVals[4] *= scale[1]/currentScale[1];
fVals[5] *= scale[1]/currentScale[1];
fVals[6] *= scale[1]/currentScale[1];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
// z
if (currentScale[2] != 0.0) {
fVals[8] *= scale[2]/currentScale[2];
fVals[9] *= scale[2]/currentScale[2];
fVals[10] *= scale[2]/currentScale[2];
} else {
Error("TGLMatrix::SetScale()", "zero scale div by zero");
}
}
//______________________________________________________________________________
void TGLMatrix::Transpose3x3()
{
// Transpose the top left 3x3 matrix component along major diagonal
// TODO: Move this fix to the TBuffer3D filling side and remove
// 0 4 8 12
// 1 5 9 13
// 2 6 10 14
// 3 7 11 15
Double_t temp = fVals[4];
fVals[4] = fVals[1];
fVals[1] = temp;
temp = fVals[8];
fVals[8] = fVals[2];
fVals[2] = temp;
temp = fVals[9];
fVals[9] = fVals[6];
fVals[6] = temp;
}
//______________________________________________________________________________
void TGLMatrix::TransformVertex(TGLVertex3 & vertex) const
{
TGLVertex3 orig = vertex;
for (UInt_t i = 0; i < 3; i++) {
vertex[i] = orig[0] * fVals[0+i] + orig[1] * fVals[4+i] +
orig[2] * fVals[8+i] + fVals[12+i];
}
}
//______________________________________________________________________________
void TGLMatrix::Dump() const
{
std::cout.precision(6);
for (Int_t x = 0; x < 4; x++) {
std::cout << "[ ";
for (Int_t y = 0; y < 4; y++) {
std::cout << fVals[y*4 + x] << " ";
}
std::cout << "]" << std::endl;
}
}
ClassImp(TGLUtil)
//______________________________________________________________________________
void TGLUtil::CheckError()
{
GLenum errCode;
const GLubyte *errString;
if ((errCode = glGetError()) != GL_NO_ERROR) {
errString = gluErrorString(errCode);
Error("TGLUtil::CheckError", (const char *)errString);
}
}
<|endoftext|> |
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_GL_DATA_FORMAT_HPP__
#define LASERCAKE_GL_DATA_FORMAT_HPP__
// This header does not use GL types (GLfloat, GLubyte) in order to
// be agnostic between GLEW and Qt's opinions of OpenGL headers.
// gl_data_preparation.cpp static_asserts that they're the types we
// expect.
// (This might not be necessary currently, but doesn't hurt anything
// (that I know of).)
#include <string>
#include <vector>
#include "cxx11/array.hpp"
#include <ostream>
#include <stdlib.h> //malloc
#include <string.h> //memcpy
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include "world_constants.hpp"
namespace gl_data_format {
typedef float header_GLfloat;
typedef unsigned char header_GLubyte;
// These are to be passed as part of arrays to OpenGL.
// Thus their data format/layout makes a difference.
// TODO maybe make vector3<GLfloat> and vertex the same thing?
// Is vector3<GLfloat>'s layout required to be the same as that of
// this struct? I believe so. typedef vector3<GLfloat> vertex; ?
// TODO use glm types?
struct vertex {
vertex() {}
vertex(header_GLfloat x, header_GLfloat y, header_GLfloat z) : x(x), y(y), z(z) {}
/* implicit conversion */ vertex(vector3<header_GLfloat> const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::vec3 const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::dvec3 const& v) : x(v.x), y(v.y), z(v.z) {}
header_GLfloat x, y, z;
};
static_assert(sizeof(vertex) == 3*sizeof(header_GLfloat), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex const& v) {
// TODO does the float precision we output here matter?
return os << '(' << v.x << ", " << v.y << ", " << v.z << ')';
}
struct color {
color() {}
// Use hex RGBA values as familiar from e.g. CSS.
// e.g. 0x00ff0077 is pure green at 50% opacity.
explicit color(uint32_t rgba)
: r(header_GLubyte(rgba >> 24)), g(header_GLubyte(rgba >> 16)),
b(header_GLubyte(rgba >> 8)), a(header_GLubyte(rgba)) {}
color(header_GLubyte r, header_GLubyte g, header_GLubyte b, header_GLubyte a)
: r(r), g(g), b(b), a(a) {}
// random Web forums thought a factor of 255.0 was correct, but is it exactly the right conversion?
color(header_GLfloat r, header_GLfloat g, header_GLfloat b, header_GLfloat a)
: r(header_GLubyte(r*255)), g(header_GLubyte(g*255)), b(header_GLubyte(b*255)), a(header_GLubyte(a*255)) {}
header_GLubyte r, g, b, a;
};
static_assert(sizeof(color) == 4*sizeof(header_GLubyte), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, color const& c) {
// TODO does the float precision we output here matter?
const char oldfill = os.fill('0');
const std::ios::fmtflags oldflags = os.setf(std::ios::hex, std::ios::basefield);
os << "rgba(";
os.width(2); os << int(c.r);
os.width(2); os << int(c.g);
os.width(2); os << int(c.b);
os.width(2); os << int(c.a);
os << ')';
os.flags(oldflags);
os.fill(oldfill);
return os;
}
struct vertex_with_color {
vertex_with_color() {}
vertex_with_color(vertex v, color c) : c(c), v(v) {}
vertex_with_color(header_GLfloat x, header_GLfloat y, header_GLfloat z, color c)
: c(c), v(x,y,z) {}
color c;
vertex v;
};
static_assert(sizeof(vertex_with_color) == 16, "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex_with_color const& vc) {
// TODO does the float precision we output here matter?
return os << vc.c << '~' << vc.v;
}
struct gl_call_data {
typedef uint32_t size_type;
size_type count;
size_type alloced;
vertex_with_color* vertices;
//vertex_with_color* vertices_end;
static const size_type default_size = 5;
static const size_type expand_multiplier = 4;
gl_call_data()
: count(0),
alloced(default_size),
vertices((vertex_with_color*)malloc(default_size*sizeof(vertex_with_color))) {
assert(vertices);
}
gl_call_data(gl_call_data&& other)
: count(other.count),
alloced(other.alloced),
vertices(other.vertices) {
other.vertices = nullptr;
}
gl_call_data(gl_call_data const& other)
: count(other.count),
alloced(other.alloced),
vertices((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color))) {
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
}
gl_call_data& operator=(gl_call_data const& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = ((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color)));
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
return *this;
}
gl_call_data& operator=(gl_call_data&& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = other.vertices;
other.vertices = nullptr;
return *this;
}
~gl_call_data() { free(vertices); }
void push_vertex(vertex_with_color const& v) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count] = v;
++count;
}
void push_vertex(vertex const& v, color const& c) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count].c = c;
vertices[count].v = v;
++count;
}
void reserve_new_slots(size_type num_slots) {
const size_type new_count = count + num_slots;
if(new_count > alloced) do_realloc(new_count * expand_multiplier);
count = new_count;
}
size_type size() const { return count; }
void do_realloc(size_type new_size) {
assert(new_size > alloced);
vertex_with_color* new_vertices = (vertex_with_color*)malloc(new_size * sizeof(vertex_with_color));
assert(new_vertices);
memcpy(new_vertices, vertices, count*sizeof(vertex_with_color));
free(vertices);
vertices = new_vertices;
alloced = new_size;
}
};
struct gl_collection {
// Points and lines are for debugging, because they don't change size at distance,
// and TODO can be represented reasonably by triangles.
// Triangles are legit.
// Quads are TODO OpenGL prefers you to use triangles (esp. OpenGL ES) and
// they'll be converted at some point.
gl_call_data points;
gl_call_data lines;
gl_call_data triangles;
gl_call_data quads;
};
//The gl_collection:s with higher indices here are intended to be
//further away and rendered first (therefore covered up most
//by everything else that's closer).
typedef std::vector<gl_collection> gl_collectionplex;
struct heads_up_display_text {
// text may contain newlines, and will also
// be soft-wrapped to fit on the screen.
std::string text;
color c;
std::string font_name;
int point_size;
int horizontal_margin_in_pixels;
int vertical_margin_in_pixels;
};
struct gl_all_data {
gl_collectionplex stuff_to_draw_as_gl_collections_by_distance;
color tint_everything_with_this_color;
heads_up_display_text hud_text;
vector3<header_GLfloat> facing;
vector3<header_GLfloat> facing_up;
};
const int32_t fovy_degrees = 80;
const non_normalized_rational<int32_t> pretend_aspect_ratio_value_when_culling(2,1);
const distance near_clipping_plane = tile_width / 10;
const distance far_clipping_plane = tile_width * 300;
// TODO: we can, with some more work,
// use non-floating-point matrices for several things.
// Which would allow main-simulation code to filter based on
// view frustums, for example.
inline glm::mat4 make_projection_matrix(float aspect_ratio) {
return glm::perspective(
float(fovy_degrees),
float(aspect_ratio),
get_primitive_float(near_clipping_plane/fine_distance_units),
get_primitive_float(far_clipping_plane/fine_distance_units)
);
}
const vector3<float> view_from(0);
inline glm::mat4 make_view_matrix(vector3<float> view_towards, vector3<float> up) {
return glm::lookAt(
glm::vec3(view_from.x, view_from.y, view_from.z),
glm::vec3(view_towards.x, view_towards.y, view_towards.z),
glm::vec3(up.x, up.y, up.z)
);
}
// TODO glm has glm::detail::tmat4x4<> etc, needed to templatize
// this, if I want to templatize it.
struct frustum {
enum direction {
// Windows headers define NEAR and FAR
// and I don't want to tempt any dragons by #undef'ing
// them, so just add an underscore to those names here.
LEFT, RIGHT, BOTTOM, TOP, NEAR_, FAR_
};
array<glm::vec4, 6> half_spaces;
};
inline frustum make_frustum_from_matrix(glm::mat4 m) {
frustum result;
result.half_spaces[frustum::LEFT] = glm::normalize(glm::row(m, 3) + glm::row(m, 0));
result.half_spaces[frustum::RIGHT] = glm::normalize(glm::row(m, 3) - glm::row(m, 0));
result.half_spaces[frustum::BOTTOM] = glm::normalize(glm::row(m, 3) + glm::row(m, 1));
result.half_spaces[frustum::TOP] = glm::normalize(glm::row(m, 3) - glm::row(m, 1));
result.half_spaces[frustum::NEAR_] = glm::normalize(glm::row(m, 3) + glm::row(m, 2));
result.half_spaces[frustum::FAR_] = glm::normalize(glm::row(m, 3) - glm::row(m, 2));
return result;
}
} // end namespace gl_data_format
#endif
<commit_msg>fix for newer GLM<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_GL_DATA_FORMAT_HPP__
#define LASERCAKE_GL_DATA_FORMAT_HPP__
#define GLM_FORCE_RADIANS
// This header does not use GL types (GLfloat, GLubyte) in order to
// be agnostic between GLEW and Qt's opinions of OpenGL headers.
// gl_data_preparation.cpp static_asserts that they're the types we
// expect.
// (This might not be necessary currently, but doesn't hurt anything
// (that I know of).)
#include <string>
#include <vector>
#include "cxx11/array.hpp"
#include <ostream>
#include <stdlib.h> //malloc
#include <string.h> //memcpy
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include "world_constants.hpp"
namespace gl_data_format {
typedef float header_GLfloat;
typedef unsigned char header_GLubyte;
// These are to be passed as part of arrays to OpenGL.
// Thus their data format/layout makes a difference.
// TODO maybe make vector3<GLfloat> and vertex the same thing?
// Is vector3<GLfloat>'s layout required to be the same as that of
// this struct? I believe so. typedef vector3<GLfloat> vertex; ?
// TODO use glm types?
struct vertex {
vertex() {}
vertex(header_GLfloat x, header_GLfloat y, header_GLfloat z) : x(x), y(y), z(z) {}
/* implicit conversion */ vertex(vector3<header_GLfloat> const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::vec3 const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::dvec3 const& v) : x(v.x), y(v.y), z(v.z) {}
header_GLfloat x, y, z;
};
static_assert(sizeof(vertex) == 3*sizeof(header_GLfloat), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex const& v) {
// TODO does the float precision we output here matter?
return os << '(' << v.x << ", " << v.y << ", " << v.z << ')';
}
struct color {
color() {}
// Use hex RGBA values as familiar from e.g. CSS.
// e.g. 0x00ff0077 is pure green at 50% opacity.
explicit color(uint32_t rgba)
: r(header_GLubyte(rgba >> 24)), g(header_GLubyte(rgba >> 16)),
b(header_GLubyte(rgba >> 8)), a(header_GLubyte(rgba)) {}
color(header_GLubyte r, header_GLubyte g, header_GLubyte b, header_GLubyte a)
: r(r), g(g), b(b), a(a) {}
// random Web forums thought a factor of 255.0 was correct, but is it exactly the right conversion?
color(header_GLfloat r, header_GLfloat g, header_GLfloat b, header_GLfloat a)
: r(header_GLubyte(r*255)), g(header_GLubyte(g*255)), b(header_GLubyte(b*255)), a(header_GLubyte(a*255)) {}
header_GLubyte r, g, b, a;
};
static_assert(sizeof(color) == 4*sizeof(header_GLubyte), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, color const& c) {
// TODO does the float precision we output here matter?
const char oldfill = os.fill('0');
const std::ios::fmtflags oldflags = os.setf(std::ios::hex, std::ios::basefield);
os << "rgba(";
os.width(2); os << int(c.r);
os.width(2); os << int(c.g);
os.width(2); os << int(c.b);
os.width(2); os << int(c.a);
os << ')';
os.flags(oldflags);
os.fill(oldfill);
return os;
}
struct vertex_with_color {
vertex_with_color() {}
vertex_with_color(vertex v, color c) : c(c), v(v) {}
vertex_with_color(header_GLfloat x, header_GLfloat y, header_GLfloat z, color c)
: c(c), v(x,y,z) {}
color c;
vertex v;
};
static_assert(sizeof(vertex_with_color) == 16, "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex_with_color const& vc) {
// TODO does the float precision we output here matter?
return os << vc.c << '~' << vc.v;
}
struct gl_call_data {
typedef uint32_t size_type;
size_type count;
size_type alloced;
vertex_with_color* vertices;
//vertex_with_color* vertices_end;
static const size_type default_size = 5;
static const size_type expand_multiplier = 4;
gl_call_data()
: count(0),
alloced(default_size),
vertices((vertex_with_color*)malloc(default_size*sizeof(vertex_with_color))) {
assert(vertices);
}
gl_call_data(gl_call_data&& other)
: count(other.count),
alloced(other.alloced),
vertices(other.vertices) {
other.vertices = nullptr;
}
gl_call_data(gl_call_data const& other)
: count(other.count),
alloced(other.alloced),
vertices((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color))) {
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
}
gl_call_data& operator=(gl_call_data const& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = ((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color)));
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
return *this;
}
gl_call_data& operator=(gl_call_data&& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = other.vertices;
other.vertices = nullptr;
return *this;
}
~gl_call_data() { free(vertices); }
void push_vertex(vertex_with_color const& v) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count] = v;
++count;
}
void push_vertex(vertex const& v, color const& c) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count].c = c;
vertices[count].v = v;
++count;
}
void reserve_new_slots(size_type num_slots) {
const size_type new_count = count + num_slots;
if(new_count > alloced) do_realloc(new_count * expand_multiplier);
count = new_count;
}
size_type size() const { return count; }
void do_realloc(size_type new_size) {
assert(new_size > alloced);
vertex_with_color* new_vertices = (vertex_with_color*)malloc(new_size * sizeof(vertex_with_color));
assert(new_vertices);
memcpy(new_vertices, vertices, count*sizeof(vertex_with_color));
free(vertices);
vertices = new_vertices;
alloced = new_size;
}
};
struct gl_collection {
// Points and lines are for debugging, because they don't change size at distance,
// and TODO can be represented reasonably by triangles.
// Triangles are legit.
// Quads are TODO OpenGL prefers you to use triangles (esp. OpenGL ES) and
// they'll be converted at some point.
gl_call_data points;
gl_call_data lines;
gl_call_data triangles;
gl_call_data quads;
};
//The gl_collection:s with higher indices here are intended to be
//further away and rendered first (therefore covered up most
//by everything else that's closer).
typedef std::vector<gl_collection> gl_collectionplex;
struct heads_up_display_text {
// text may contain newlines, and will also
// be soft-wrapped to fit on the screen.
std::string text;
color c;
std::string font_name;
int point_size;
int horizontal_margin_in_pixels;
int vertical_margin_in_pixels;
};
struct gl_all_data {
gl_collectionplex stuff_to_draw_as_gl_collections_by_distance;
color tint_everything_with_this_color;
heads_up_display_text hud_text;
vector3<header_GLfloat> facing;
vector3<header_GLfloat> facing_up;
};
const int32_t fovy_degrees = 80;
const non_normalized_rational<int32_t> pretend_aspect_ratio_value_when_culling(2,1);
const distance near_clipping_plane = tile_width / 10;
const distance far_clipping_plane = tile_width * 300;
// TODO: we can, with some more work,
// use non-floating-point matrices for several things.
// Which would allow main-simulation code to filter based on
// view frustums, for example.
inline glm::mat4 make_projection_matrix(float aspect_ratio) {
return glm::perspective(
glm::radians(float(fovy_degrees)),
float(aspect_ratio),
get_primitive_float(near_clipping_plane/fine_distance_units),
get_primitive_float(far_clipping_plane/fine_distance_units)
);
}
const vector3<float> view_from(0);
inline glm::mat4 make_view_matrix(vector3<float> view_towards, vector3<float> up) {
return glm::lookAt(
glm::vec3(view_from.x, view_from.y, view_from.z),
glm::vec3(view_towards.x, view_towards.y, view_towards.z),
glm::vec3(up.x, up.y, up.z)
);
}
// TODO glm has glm::detail::tmat4x4<> etc, needed to templatize
// this, if I want to templatize it.
struct frustum {
enum direction {
// Windows headers define NEAR and FAR
// and I don't want to tempt any dragons by #undef'ing
// them, so just add an underscore to those names here.
LEFT, RIGHT, BOTTOM, TOP, NEAR_, FAR_
};
array<glm::vec4, 6> half_spaces;
};
inline frustum make_frustum_from_matrix(glm::mat4 m) {
frustum result;
result.half_spaces[frustum::LEFT] = glm::normalize(glm::row(m, 3) + glm::row(m, 0));
result.half_spaces[frustum::RIGHT] = glm::normalize(glm::row(m, 3) - glm::row(m, 0));
result.half_spaces[frustum::BOTTOM] = glm::normalize(glm::row(m, 3) + glm::row(m, 1));
result.half_spaces[frustum::TOP] = glm::normalize(glm::row(m, 3) - glm::row(m, 1));
result.half_spaces[frustum::NEAR_] = glm::normalize(glm::row(m, 3) + glm::row(m, 2));
result.half_spaces[frustum::FAR_] = glm::normalize(glm::row(m, 3) - glm::row(m, 2));
return result;
}
} // end namespace gl_data_format
#endif
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "org_mitk_simulation_Activator.h"
#include <mitkGetSimulationPreferences.h>
#include <mitkLoadPropertiesModule.h>
#include <mitkNodePredicateDataType.h>
#include <mitkPropertyFilters.h>
#include <mitkSimulationObjectFactory.h>
#include <QmitkNodeDescriptorManager.h>
#include <QtPlugin>
#include <sofa/helper/system/PluginManager.h>
template <class T>
T* GetPropertyService(ctkPluginContext* context)
{
if (context == NULL)
return NULL;
mitk::LoadPropertiesModule();
ctkServiceReference serviceRef = context->getServiceReference<T>();
return serviceRef
? context->getService<T>(serviceRef)
: NULL;
}
static void InitSOFAPlugins()
{
berry::IPreferences::Pointer preferences = mitk::GetSimulationPreferences();
if (preferences.IsNull())
return;
QString pluginPaths = preferences->GetByteArray("plugin paths", "").c_str();
if (pluginPaths.isEmpty())
return;
QStringList pluginPathList = pluginPaths.split(';', QString::SkipEmptyParts);
QStringListIterator it(pluginPathList);
typedef sofa::helper::system::PluginManager PluginManager;
PluginManager& pluginManager = PluginManager::getInstance();
while (it.hasNext())
{
std::string path = it.next().toStdString();
std::ostringstream errlog;
pluginManager.loadPlugin(path, &errlog);
if (errlog.str().empty())
pluginManager.getPluginMap()[path].initExternalModule();
}
}
static void SetPropertyFilters(ctkPluginContext* context)
{
mitk::PropertyFilters* propertyFilters = GetPropertyService<mitk::PropertyFilters>(context);
if (propertyFilters == NULL)
return;
mitk::PropertyFilter simulationFilter;
simulationFilter.AddEntry("layer", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("name", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("path", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("selected", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("visible", mitk::PropertyFilter::Blacklist);
propertyFilters->AddFilter("Simulation", simulationFilter);
propertyFilters->AddFilter("SimulationTemplate", simulationFilter);
}
void mitk::org_mitk_simulation_Activator::start(ctkPluginContext* context)
{
RegisterSimulationObjectFactory();
InitSOFAPlugins();
SetPropertyFilters(context);
QmitkNodeDescriptorManager* nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance();
if (nodeDescriptorManager != NULL)
{
mitk::NodePredicateDataType::Pointer isSimulation = mitk::NodePredicateDataType::New("Simulation");
nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("Simulation", ":/Simulation/simulation.png", isSimulation, nodeDescriptorManager));
mitk::NodePredicateDataType::Pointer isSimulationTemplate = mitk::NodePredicateDataType::New("SimulationTemplate");
nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("SimulationTemplate", ":/Simulation/simulationTemplate.png", isSimulationTemplate, nodeDescriptorManager));
}
}
void mitk::org_mitk_simulation_Activator::stop(ctkPluginContext*)
{
}
Q_EXPORT_PLUGIN2(org_mitk_simulation, mitk::org_mitk_simulation_Activator)
<commit_msg>Adapted MITK Simulation to new property filters API.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "org_mitk_simulation_Activator.h"
#include <mitkGetSimulationPreferences.h>
#include <mitkLoadPropertiesModule.h>
#include <mitkNodePredicateDataType.h>
#include <mitkIPropertyFilters.h>
#include <mitkSimulationObjectFactory.h>
#include <QmitkNodeDescriptorManager.h>
#include <QtPlugin>
#include <sofa/helper/system/PluginManager.h>
template <class T>
T* GetPropertyService(ctkPluginContext* context)
{
if (context == NULL)
return NULL;
mitk::LoadPropertiesModule();
ctkServiceReference serviceRef = context->getServiceReference<T>();
return serviceRef
? context->getService<T>(serviceRef)
: NULL;
}
static void InitSOFAPlugins()
{
berry::IPreferences::Pointer preferences = mitk::GetSimulationPreferences();
if (preferences.IsNull())
return;
QString pluginPaths = preferences->GetByteArray("plugin paths", "").c_str();
if (pluginPaths.isEmpty())
return;
QStringList pluginPathList = pluginPaths.split(';', QString::SkipEmptyParts);
QStringListIterator it(pluginPathList);
typedef sofa::helper::system::PluginManager PluginManager;
PluginManager& pluginManager = PluginManager::getInstance();
while (it.hasNext())
{
std::string path = it.next().toStdString();
std::ostringstream errlog;
pluginManager.loadPlugin(path, &errlog);
if (errlog.str().empty())
pluginManager.getPluginMap()[path].initExternalModule();
}
}
static void SetPropertyFilters(ctkPluginContext* context)
{
mitk::IPropertyFilters* propertyFilters = GetPropertyService<mitk::IPropertyFilters>(context);
if (propertyFilters == NULL)
return;
mitk::PropertyFilter simulationFilter;
simulationFilter.AddEntry("layer", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("name", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("path", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("selected", mitk::PropertyFilter::Blacklist);
simulationFilter.AddEntry("visible", mitk::PropertyFilter::Blacklist);
propertyFilters->AddFilter(simulationFilter, "Simulation");
propertyFilters->AddFilter(simulationFilter, "SimulationTemplate");
}
void mitk::org_mitk_simulation_Activator::start(ctkPluginContext* context)
{
RegisterSimulationObjectFactory();
InitSOFAPlugins();
SetPropertyFilters(context);
QmitkNodeDescriptorManager* nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance();
if (nodeDescriptorManager != NULL)
{
mitk::NodePredicateDataType::Pointer isSimulation = mitk::NodePredicateDataType::New("Simulation");
nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("Simulation", ":/Simulation/simulation.png", isSimulation, nodeDescriptorManager));
mitk::NodePredicateDataType::Pointer isSimulationTemplate = mitk::NodePredicateDataType::New("SimulationTemplate");
nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("SimulationTemplate", ":/Simulation/simulationTemplate.png", isSimulationTemplate, nodeDescriptorManager));
}
}
void mitk::org_mitk_simulation_Activator::stop(ctkPluginContext*)
{
}
Q_EXPORT_PLUGIN2(org_mitk_simulation, mitk::org_mitk_simulation_Activator)
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
#if FULL_SYSTEM
return readIpr(misc_reg, tc);
#else
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
#if FULL_SYSTEM
setIpr(misc_reg, val, tc);
#else
panic("No registers with side effects in SE mode!");
#endif
return;
}
}
}
<commit_msg>fix MiscRegFile::readRegWithEffect, which neglected the MISCREGS.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
return readIpr(misc_reg, tc);
#else
default:
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
#if FULL_SYSTEM
setIpr(misc_reg, val, tc);
#else
panic("No registers with side effects in SE mode!");
#endif
return;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2016 Andrew Sutton
// All rights reserved
#include "ast-hash.hpp"
#include "ast.hpp"
#include <typeinfo>
namespace banjo
{
// Returns an initial hash value based on the dynamic type of T.
template<typename T>
std::size_t hash_type(T const& t)
{
return typeid(t).hash_code();
}
// -------------------------------------------------------------------------- //
// Terms
std::size_t
hash_value(Term const& x)
{
if (Name const* n = as<Name>(&x))
return hash_value(*n);
if (Type const* t = as<Type>(&x))
return hash_value(*t);
if (Expr const* e = as<Expr>(&x))
return hash_value(*e);
if (Decl const* d = as<Decl>(&x))
return hash_value(*d);
lingo_unreachable();
}
// -------------------------------------------------------------------------- //
// Names
inline std::size_t
hash_value(Simple_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, &n.symbol());
return h;
}
inline std::size_t
hash_value(Global_id const& n)
{
return hash_type(n);
}
inline std::size_t
hash_value(Placeholder_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, n.number());
return h;
}
inline std::size_t
hash_value(Operator_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, n.kind());
return h;
}
inline std::size_t
hash_value(Conversion_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Literal_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Destructor_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Template_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Concept_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Qualified_id const&)
{
lingo_unreachable();
}
std::size_t
hash_value(Name const& n)
{
struct fn
{
std::size_t operator()(Simple_id const& n) { return hash_value(n); }
std::size_t operator()(Global_id const& n) { return hash_value(n); }
std::size_t operator()(Placeholder_id const& n) { return hash_value(n); }
std::size_t operator()(Operator_id const& n) { return hash_value(n); }
std::size_t operator()(Conversion_id const& n) { return hash_value(n); }
std::size_t operator()(Literal_id const& n) { return hash_value(n); }
std::size_t operator()(Destructor_id const& n) { return hash_value(n); }
std::size_t operator()(Template_id const& n) { return hash_value(n); }
std::size_t operator()(Concept_id const& n) { return hash_value(n); }
std::size_t operator()(Qualified_id const& n) { return hash_value(n); }
};
return apply(n, fn{});
}
// -------------------------------------------------------------------------- //
// Types
template<typename T>
inline std::size_t
hash_nullary_type(T const& t)
{
return hash_type(t);
}
inline std::size_t
hash_integer(Integer_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.sign());
boost::hash_combine(h, t.precision());
return h;
}
inline std::size_t
hash_float(Float_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.precision());
return h;
}
inline std::size_t
hash_value(Auto_type const& t)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Decltype_type const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Declauto_type const& t)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Function_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.parameter_types());
boost::hash_combine(h, t.return_type());
return h;
}
// The hash value of a user-defined type is that of its declaration.
inline std::size_t
hash_udt(User_defined_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.declaration());
return h;
}
// Compute the hash value of a type.
std::size_t
hash_value(Type const& t)
{
struct fn
{
std::size_t operator()(Type const& t) const { lingo_unhandled(t); }
std::size_t operator()(Void_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Boolean_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Byte_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Integer_type const& t) const { return hash_integer(t); }
std::size_t operator()(Float_type const& t) const { return hash_float(t); }
std::size_t operator()(Auto_type const& t) const { return hash_value(t); }
std::size_t operator()(Decltype_type const& t) const { return hash_value(t); }
std::size_t operator()(Declauto_type const& t) const { return hash_value(t); }
std::size_t operator()(Function_type const& t) const { return hash_value(t); }
std::size_t operator()(Qualified_type const& t) const { return hash_composite(t); }
std::size_t operator()(Pointer_type const& t) const { return hash_composite(t); }
std::size_t operator()(Reference_type const& t) const { return hash_composite(t); }
std::size_t operator()(Array_type const& t) const { return hash_composite(t); }
std::size_t operator()(Sequence_type const& t) const { return hash_composite(t); }
std::size_t operator()(Typename_type const& t) const { return hash_udt(t); }
std::size_t operator()(Synthetic_type const& t) const { banjo_unhandled_case(t); }
};
return apply(t, fn{});
}
// -------------------------------------------------------------------------- //
// Expressions
template<typename T>
std::size_t
hash_value(Literal_expr<T> const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.value());
return h;
}
std::size_t
hash_value(Reference_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.declaration());
return h;
}
std::size_t
hash_value(Unary_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.operand());
return h;
}
std::size_t
hash_value(Binary_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.left());
boost::hash_combine(h, e.right());
return h;
}
std::size_t
hash_value(Call_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.function());
boost::hash_combine(h, e.arguments());
return h;
}
std::size_t
hash_conv(Conv const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.destination());
boost::hash_combine(h, e.source());
return h;
}
std::size_t
hash_value(Expr const& e)
{
struct fn
{
std::size_t operator()(Expr const& e) const { banjo_unhandled_case(e); }
std::size_t operator()(Boolean_expr const& e) const { return hash_value(e); }
std::size_t operator()(Integer_expr const& e) const { return hash_value(e); }
std::size_t operator()(Reference_expr const& e) const { return hash_value(e); }
std::size_t operator()(Unary_expr const& e) const { return hash_value(e); }
std::size_t operator()(Binary_expr const& e) const { return hash_value(e); }
std::size_t operator()(Call_expr const& e) const { return hash_value(e); }
std::size_t operator()(Conv const& e) const { return hash_conv(e); }
};
return apply(e, fn{});
}
// -------------------------------------------------------------------------- //
// Declartions
// Compute the hash value of a declaration. Because declarations
// are unique, the hash is derived from the identity of the declaration.
std::size_t
hash_decl(Decl const& d)
{
std::hash<Decl const*> h;
return h(&d);
}
std::size_t
hash_parm(Type_parm const& d)
{
std::size_t h = hash_type(d);
boost::hash_combine(h, d.index());
return h;
}
std::size_t
hash_value(Decl const& d)
{
struct fn
{
std::size_t operator()(Decl const& d) { return hash_decl(d); }
std::size_t operator()(Type_parm const& d) { return hash_parm(d); }
};
return apply(d, fn{});
}
// -------------------------------------------------------------------------- //
// Constraints
std::size_t
hash_value(Concept_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.declaration());
boost::hash_combine(h, c.arguments());
return h;
}
std::size_t
hash_value(Predicate_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.expression());
return h;
}
template<typename T>
std::size_t
hash_usage(T const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.expression());
boost::hash_combine(h, c.type());
return h;
}
std::size_t
hash_parm(Parameterized_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.variables());
boost::hash_combine(h, c.constraint());
return h;
}
std::size_t
hash_value(Binary_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.left());
boost::hash_combine(h, c.right());
return h;
}
std::size_t
hash_value(Cons const& c)
{
struct fn
{
std::size_t operator()(Cons const& c) const { banjo_unhandled_case(c); }
std::size_t operator()(Concept_cons const& c) const { return hash_value(c); }
std::size_t operator()(Predicate_cons const& c) const { return hash_value(c); }
std::size_t operator()(Expression_cons const& c) const { return hash_usage(c); }
std::size_t operator()(Conversion_cons const& c) const { return hash_usage(c); }
std::size_t operator()(Parameterized_cons const& c) const { return hash_parm(c); }
std::size_t operator()(Binary_cons const& c) const { return hash_value(c); }
};
return apply(c, fn{});
}
} // namespace banjo
<commit_msg>Fix compiler error.<commit_after>// Copyright (c) 2015-2016 Andrew Sutton
// All rights reserved
#include "ast-hash.hpp"
#include "ast.hpp"
#include <typeinfo>
namespace banjo
{
// Returns an initial hash value based on the dynamic type of T.
template<typename T>
std::size_t hash_type(T const& t)
{
return typeid(t).hash_code();
}
// -------------------------------------------------------------------------- //
// Terms
std::size_t
hash_value(Term const& x)
{
if (Name const* n = as<Name>(&x))
return hash_value(*n);
if (Type const* t = as<Type>(&x))
return hash_value(*t);
if (Expr const* e = as<Expr>(&x))
return hash_value(*e);
if (Decl const* d = as<Decl>(&x))
return hash_value(*d);
lingo_unreachable();
}
// -------------------------------------------------------------------------- //
// Names
inline std::size_t
hash_value(Simple_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, &n.symbol());
return h;
}
inline std::size_t
hash_value(Global_id const& n)
{
return hash_type(n);
}
inline std::size_t
hash_value(Placeholder_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, n.number());
return h;
}
inline std::size_t
hash_value(Operator_id const& n)
{
std::size_t h = hash_type(n);
boost::hash_combine(h, n.kind());
return h;
}
inline std::size_t
hash_value(Conversion_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Literal_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Destructor_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Template_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Concept_id const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Qualified_id const&)
{
lingo_unreachable();
}
std::size_t
hash_value(Name const& n)
{
struct fn
{
std::size_t operator()(Simple_id const& n) { return hash_value(n); }
std::size_t operator()(Global_id const& n) { return hash_value(n); }
std::size_t operator()(Placeholder_id const& n) { return hash_value(n); }
std::size_t operator()(Operator_id const& n) { return hash_value(n); }
std::size_t operator()(Conversion_id const& n) { return hash_value(n); }
std::size_t operator()(Literal_id const& n) { return hash_value(n); }
std::size_t operator()(Destructor_id const& n) { return hash_value(n); }
std::size_t operator()(Template_id const& n) { return hash_value(n); }
std::size_t operator()(Concept_id const& n) { return hash_value(n); }
std::size_t operator()(Qualified_id const& n) { return hash_value(n); }
};
return apply(n, fn{});
}
// -------------------------------------------------------------------------- //
// Types
template<typename T>
inline std::size_t
hash_nullary_type(T const& t)
{
return hash_type(t);
}
inline std::size_t
hash_integer(Integer_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.sign());
boost::hash_combine(h, t.precision());
return h;
}
inline std::size_t
hash_float(Float_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.precision());
return h;
}
inline std::size_t
hash_value(Auto_type const& t)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Decltype_type const&)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Declauto_type const& t)
{
lingo_unreachable();
}
inline std::size_t
hash_value(Function_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.parameter_types());
boost::hash_combine(h, t.return_type());
return h;
}
// The hash value of a user-defined type is that of its declaration.
inline std::size_t
hash_udt(User_defined_type const& t)
{
std::size_t h = hash_type(t);
boost::hash_combine(h, t.declaration());
return h;
}
// Compute the hash value of a type.
std::size_t
hash_value(Type const& t)
{
struct fn
{
std::size_t operator()(Type const& t) const { lingo_unhandled(t); }
std::size_t operator()(Void_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Boolean_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Byte_type const& t) const { return hash_nullary_type(t); }
std::size_t operator()(Integer_type const& t) const { return hash_integer(t); }
std::size_t operator()(Float_type const& t) const { return hash_float(t); }
std::size_t operator()(Auto_type const& t) const { return hash_value(t); }
std::size_t operator()(Decltype_type const& t) const { return hash_value(t); }
std::size_t operator()(Declauto_type const& t) const { return hash_value(t); }
std::size_t operator()(Function_type const& t) const { return hash_value(t); }
std::size_t operator()(Typename_type const& t) const { return hash_udt(t); }
std::size_t operator()(Synthetic_type const& t) const { banjo_unhandled_case(t); }
};
return apply(t, fn{});
}
// -------------------------------------------------------------------------- //
// Expressions
template<typename T>
std::size_t
hash_value(Literal_expr<T> const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.value());
return h;
}
std::size_t
hash_value(Reference_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.declaration());
return h;
}
std::size_t
hash_value(Unary_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.operand());
return h;
}
std::size_t
hash_value(Binary_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.left());
boost::hash_combine(h, e.right());
return h;
}
std::size_t
hash_value(Call_expr const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.function());
boost::hash_combine(h, e.arguments());
return h;
}
std::size_t
hash_conv(Conv const& e)
{
std::size_t h = hash_type(e);
boost::hash_combine(h, e.destination());
boost::hash_combine(h, e.source());
return h;
}
std::size_t
hash_value(Expr const& e)
{
struct fn
{
std::size_t operator()(Expr const& e) const { banjo_unhandled_case(e); }
std::size_t operator()(Boolean_expr const& e) const { return hash_value(e); }
std::size_t operator()(Integer_expr const& e) const { return hash_value(e); }
std::size_t operator()(Reference_expr const& e) const { return hash_value(e); }
std::size_t operator()(Unary_expr const& e) const { return hash_value(e); }
std::size_t operator()(Binary_expr const& e) const { return hash_value(e); }
std::size_t operator()(Call_expr const& e) const { return hash_value(e); }
std::size_t operator()(Conv const& e) const { return hash_conv(e); }
};
return apply(e, fn{});
}
// -------------------------------------------------------------------------- //
// Declartions
// Compute the hash value of a declaration. Because declarations
// are unique, the hash is derived from the identity of the declaration.
std::size_t
hash_decl(Decl const& d)
{
std::hash<Decl const*> h;
return h(&d);
}
std::size_t
hash_parm(Type_parm const& d)
{
std::size_t h = hash_type(d);
boost::hash_combine(h, d.index());
return h;
}
std::size_t
hash_value(Decl const& d)
{
struct fn
{
std::size_t operator()(Decl const& d) { return hash_decl(d); }
std::size_t operator()(Type_parm const& d) { return hash_parm(d); }
};
return apply(d, fn{});
}
// -------------------------------------------------------------------------- //
// Constraints
std::size_t
hash_value(Concept_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.declaration());
boost::hash_combine(h, c.arguments());
return h;
}
std::size_t
hash_value(Predicate_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.expression());
return h;
}
template<typename T>
std::size_t
hash_usage(T const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.expression());
boost::hash_combine(h, c.type());
return h;
}
std::size_t
hash_parm(Parameterized_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.variables());
boost::hash_combine(h, c.constraint());
return h;
}
std::size_t
hash_value(Binary_cons const& c)
{
std::size_t h = hash_type(c);
boost::hash_combine(h, c.left());
boost::hash_combine(h, c.right());
return h;
}
std::size_t
hash_value(Cons const& c)
{
struct fn
{
std::size_t operator()(Cons const& c) const { banjo_unhandled_case(c); }
std::size_t operator()(Concept_cons const& c) const { return hash_value(c); }
std::size_t operator()(Predicate_cons const& c) const { return hash_value(c); }
std::size_t operator()(Expression_cons const& c) const { return hash_usage(c); }
std::size_t operator()(Conversion_cons const& c) const { return hash_usage(c); }
std::size_t operator()(Parameterized_cons const& c) const { return hash_parm(c); }
std::size_t operator()(Binary_cons const& c) const { return hash_value(c); }
};
return apply(c, fn{});
}
} // namespace banjo
<|endoftext|> |
<commit_before>#ifndef __ESN_EXCEPTIONS_H__
#define __ESN_EXCEPTIONS_H__
#include <exception>
namespace ESN {
class OutputIsNotFinite : public std::domain_error
{
public:
OutputIsNotFinite()
: std::domain_error("One or more outputs of the network are "
"not finite values.")
{}
};
} // namespace ESN
#endif // __ESN_EXCEPTIONS_H__
<commit_msg>esn : fix include at exceptions.hpp<commit_after>#ifndef __ESN_EXCEPTIONS_H__
#define __ESN_EXCEPTIONS_H__
#include <stdexcept>
namespace ESN {
class OutputIsNotFinite : public std::domain_error
{
public:
OutputIsNotFinite()
: std::domain_error("One or more outputs of the network are "
"not finite values.")
{}
};
} // namespace ESN
#endif // __ESN_EXCEPTIONS_H__
<|endoftext|> |
<commit_before>//
// AsyncTaskQueue.cpp
// Clock Signal
//
// Created by Thomas Harte on 07/10/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "AsyncTaskQueue.hpp"
using namespace Concurrency;
AsyncTaskQueue::AsyncTaskQueue()
#ifndef __APPLE__
: should_destruct_(false)
#endif
{
#ifdef __APPLE__
serial_dispatch_queue_ = dispatch_queue_create("com.thomasharte.clocksignal.asyntaskqueue", DISPATCH_QUEUE_SERIAL);
#else
thread_.reset(new std::thread([this]() {
while(!should_destruct_) {
std::function<void(void)> next_function;
// Take lock, check for a new task
std::unique_lock<std::mutex> lock(queue_mutex_);
if(!pending_tasks_.empty()) {
next_function = pending_tasks_.front();
pending_tasks_.pop_front();
}
if(next_function) {
// If there is a task, release lock and perform it
lock.unlock();
next_function();
} else {
// If there isn't a task, atomically block on the processing condition and release the lock
// until there's something pending (and then release it again via scope)
processing_condition_.wait(lock);
}
}
}));
#endif
}
AsyncTaskQueue::~AsyncTaskQueue() {
#ifdef __APPLE__
dispatch_release(serial_dispatch_queue_);
#else
should_destruct_ = true;
enqueue([](){});
thread_->join();
thread_.reset();
#endif
}
void AsyncTaskQueue::enqueue(std::function<void(void)> function) {
#ifdef __APPLE__
dispatch_async(serial_dispatch_queue_, ^{function();});
#else
std::lock_guard<std::mutex> lock(queue_mutex_);
pending_tasks_.push_back(function);
processing_condition_.notify_all();
#endif
}
void AsyncTaskQueue::flush() {
#ifdef __APPLE__
dispatch_sync(serial_dispatch_queue_, ^{});
#else
std::shared_ptr<std::mutex> flush_mutex(new std::mutex);
std::shared_ptr<std::condition_variable> flush_condition(new std::condition_variable);
std::unique_lock<std::mutex> lock(*flush_mutex);
enqueue([=] () {
std::unique_lock<std::mutex> inner_lock(*flush_mutex);
flush_condition->notify_all();
});
flush_condition->wait(lock);
#endif
}
<commit_msg>Added an explicit nilling, to help with debugging.<commit_after>//
// AsyncTaskQueue.cpp
// Clock Signal
//
// Created by Thomas Harte on 07/10/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "AsyncTaskQueue.hpp"
using namespace Concurrency;
AsyncTaskQueue::AsyncTaskQueue()
#ifndef __APPLE__
: should_destruct_(false)
#endif
{
#ifdef __APPLE__
serial_dispatch_queue_ = dispatch_queue_create("com.thomasharte.clocksignal.asyntaskqueue", DISPATCH_QUEUE_SERIAL);
#else
thread_.reset(new std::thread([this]() {
while(!should_destruct_) {
std::function<void(void)> next_function;
// Take lock, check for a new task
std::unique_lock<std::mutex> lock(queue_mutex_);
if(!pending_tasks_.empty()) {
next_function = pending_tasks_.front();
pending_tasks_.pop_front();
}
if(next_function) {
// If there is a task, release lock and perform it
lock.unlock();
next_function();
} else {
// If there isn't a task, atomically block on the processing condition and release the lock
// until there's something pending (and then release it again via scope)
processing_condition_.wait(lock);
}
}
}));
#endif
}
AsyncTaskQueue::~AsyncTaskQueue() {
#ifdef __APPLE__
dispatch_release(serial_dispatch_queue_);
serial_dispatch_queue_ = nullptr;
#else
should_destruct_ = true;
enqueue([](){});
thread_->join();
thread_.reset();
#endif
}
void AsyncTaskQueue::enqueue(std::function<void(void)> function) {
#ifdef __APPLE__
dispatch_async(serial_dispatch_queue_, ^{function();});
#else
std::lock_guard<std::mutex> lock(queue_mutex_);
pending_tasks_.push_back(function);
processing_condition_.notify_all();
#endif
}
void AsyncTaskQueue::flush() {
#ifdef __APPLE__
dispatch_sync(serial_dispatch_queue_, ^{});
#else
std::shared_ptr<std::mutex> flush_mutex(new std::mutex);
std::shared_ptr<std::condition_variable> flush_condition(new std::condition_variable);
std::unique_lock<std::mutex> lock(*flush_mutex);
enqueue([=] () {
std::unique_lock<std::mutex> inner_lock(*flush_mutex);
flush_condition->notify_all();
});
flush_condition->wait(lock);
#endif
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010 - 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "CQEFMResultWidget.h"
#include "CQEFMNetReactionDM.h"
#include "CQEFMReactionDM.h"
#include "CQEFMSpeciesDM.h"
#include "CopasiFileDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "elementaryFluxModes/CEFMTask.h"
#include "elementaryFluxModes/CFluxMode.h"
#include "utilities/utility.h"
#include "commandline/CLocaleString.h"
CQEFMResultWidget::CQEFMResultWidget(QWidget* parent, const char* name) :
CopasiWidget(parent, name),
mpTask(NULL),
mpProxyModelReactions(NULL),
mpReactionDM(NULL),
mpProxyModelSpecies(NULL),
mpSpeciesDM(NULL),
mpProxyModelNetReactions(NULL),
mpNetReactionDM(NULL)
{
setupUi(this);
mpReactionMatrix->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpReactionMatrix->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpReactionMatrix->verticalHeader()->hide();
//Create Source Data Model.
mpReactionDM = new CQEFMReactionDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelReactions = new CQSortFilterProxyModel();
mpProxyModelReactions->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelReactions->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelReactions->setSourceModel(mpReactionDM);
//Set Model for the TableView
mpReactionMatrix->setModel(NULL);
mpReactionMatrix->setModel(mpProxyModelReactions);
mpReactionMatrix->resizeColumnsToContents();
mpSpeciesMatrix->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpSpeciesMatrix->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpSpeciesMatrix->verticalHeader()->hide();
//Create Source Data Model.
mpSpeciesDM = new CQEFMSpeciesDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelSpecies = new CQSortFilterProxyModel();
mpProxyModelSpecies->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelSpecies->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelSpecies->setSourceModel(mpSpeciesDM);
//Set Model for the TableView
mpSpeciesMatrix->setModel(NULL);
mpSpeciesMatrix->setModel(mpProxyModelSpecies);
mpSpeciesMatrix->resizeColumnsToContents();
mpNetReactions->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpNetReactions->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpNetReactions->verticalHeader()->hide();
//Create Source Data Model.
mpNetReactionDM = new CQEFMNetReactionDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelNetReactions = new CQSortFilterProxyModel();
mpProxyModelNetReactions->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelNetReactions->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelNetReactions->setSourceModel(mpNetReactionDM);
//Set Model for the TableView
mpNetReactions->setModel(NULL);
mpNetReactions->setModel(mpProxyModelNetReactions);
mpNetReactions->resizeColumnsToContents();
}
CQEFMResultWidget::~CQEFMResultWidget()
{
pdelete(mpProxyModelNetReactions);
pdelete(mpProxyModelReactions);
pdelete(mpProxyModelSpecies);
}
// virtual
bool CQEFMResultWidget::leave()
{
return true;
}
// virtual
bool CQEFMResultWidget::update(ListViews::ObjectType objectType,
ListViews::Action action,
const std::string & /* key */)
{
// We need to update the task when a new model is loaded.
switch (objectType)
{
case ListViews::MODEL:
switch (action)
{
case ListViews::ADD:
case ListViews::DELETE:
loadResult(NULL);
break;
default:
break;
}
break;
default:
break;
}
return true;
}
// virtual
bool CQEFMResultWidget::enterProtected()
{
return true;
}
// virtual
bool CQEFMResultWidget::loadResult(const CCopasiTask * pTask)
{
mpTask = dynamic_cast<const CEFMTask *>(pTask);
if (mpTask != NULL)
{
mpEditFluxModes->setText(QString::number(mpTask->getFluxModes().size()));
}
else
{
mpEditFluxModes->setText(QString::number(0));
}
bool success = true;
success &= mpEFMListWidget->loadResult(mpTask);
mpReactionDM->setTask(mpTask);
mpProxyModelReactions->setSourceModel(mpReactionDM);
//Set Model for the TableView
mpReactionMatrix->setModel(NULL);
mpReactionMatrix->setModel(mpProxyModelReactions);
mpReactionMatrix->resizeColumnsToContents();
mpSpeciesDM->setTask(mpTask);
mpProxyModelSpecies->setSourceModel(mpSpeciesDM);
//Set Model for the TableView
mpSpeciesMatrix->setModel(NULL);
mpSpeciesMatrix->setModel(mpProxyModelSpecies);
mpSpeciesMatrix->resizeColumnsToContents();
mpNetReactionDM->setTask(mpTask);
mpProxyModelNetReactions->setSourceModel(mpNetReactionDM);
//Set Model for the TableView
mpNetReactions->setModel(NULL);
mpNetReactions->setModel(mpProxyModelNetReactions);
mpNetReactions->resizeColumnsToContents();
return success;
}
void CQEFMResultWidget::slotSave()
{
C_INT32 Answer = QMessageBox::No;
QString fileName;
while (Answer == QMessageBox::No)
{
fileName =
CopasiFileDialog::getSaveFileName(this, "Save File Dialog",
"untitled.txt", "TEXT Files (*.txt)", "Save to");
if (fileName.isEmpty()) return;
// Checks whether the file exists
Answer = checkSelection(fileName);
if (Answer == QMessageBox::Cancel) return;
}
std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str());
if (file.fail())
return;
if (mpTask != NULL)
file << mpTask->getResult();
return;
}
<commit_msg>Fixed Bug 2288. The flux mode results are now cleared when a reaction or species is added or deleted.<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include "CQEFMResultWidget.h"
#include "CQEFMNetReactionDM.h"
#include "CQEFMReactionDM.h"
#include "CQEFMSpeciesDM.h"
#include "CopasiFileDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "elementaryFluxModes/CEFMTask.h"
#include "elementaryFluxModes/CFluxMode.h"
#include "utilities/utility.h"
#include "commandline/CLocaleString.h"
CQEFMResultWidget::CQEFMResultWidget(QWidget* parent, const char* name) :
CopasiWidget(parent, name),
mpTask(NULL),
mpProxyModelReactions(NULL),
mpReactionDM(NULL),
mpProxyModelSpecies(NULL),
mpSpeciesDM(NULL),
mpProxyModelNetReactions(NULL),
mpNetReactionDM(NULL)
{
setupUi(this);
mpReactionMatrix->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpReactionMatrix->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpReactionMatrix->verticalHeader()->hide();
//Create Source Data Model.
mpReactionDM = new CQEFMReactionDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelReactions = new CQSortFilterProxyModel();
mpProxyModelReactions->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelReactions->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelReactions->setSourceModel(mpReactionDM);
//Set Model for the TableView
mpReactionMatrix->setModel(NULL);
mpReactionMatrix->setModel(mpProxyModelReactions);
mpReactionMatrix->resizeColumnsToContents();
mpSpeciesMatrix->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpSpeciesMatrix->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpSpeciesMatrix->verticalHeader()->hide();
//Create Source Data Model.
mpSpeciesDM = new CQEFMSpeciesDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelSpecies = new CQSortFilterProxyModel();
mpProxyModelSpecies->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelSpecies->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelSpecies->setSourceModel(mpSpeciesDM);
//Set Model for the TableView
mpSpeciesMatrix->setModel(NULL);
mpSpeciesMatrix->setModel(mpProxyModelSpecies);
mpSpeciesMatrix->resizeColumnsToContents();
mpNetReactions->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder);
mpNetReactions->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
mpNetReactions->verticalHeader()->hide();
//Create Source Data Model.
mpNetReactionDM = new CQEFMNetReactionDM(this);
//Create the Proxy Model for sorting/filtering and set its properties.
mpProxyModelNetReactions = new CQSortFilterProxyModel();
mpProxyModelNetReactions->setSortCaseSensitivity(Qt::CaseInsensitive);
mpProxyModelNetReactions->setFilterKeyColumn(COL_REACTION_NAME);
mpProxyModelNetReactions->setSourceModel(mpNetReactionDM);
//Set Model for the TableView
mpNetReactions->setModel(NULL);
mpNetReactions->setModel(mpProxyModelNetReactions);
mpNetReactions->resizeColumnsToContents();
}
CQEFMResultWidget::~CQEFMResultWidget()
{
pdelete(mpProxyModelNetReactions);
pdelete(mpProxyModelReactions);
pdelete(mpProxyModelSpecies);
}
// virtual
bool CQEFMResultWidget::leave()
{
return true;
}
// virtual
bool CQEFMResultWidget::update(ListViews::ObjectType objectType,
ListViews::Action action,
const std::string & /* key */)
{
// We need to update the task when a new model is loaded.
switch (objectType)
{
case ListViews::MODEL:
case ListViews::REACTION:
case ListViews::METABOLITE:
switch (action)
{
case ListViews::ADD:
case ListViews::DELETE:
loadResult(NULL);
break;
default:
break;
}
break;
default:
break;
}
return true;
}
// virtual
bool CQEFMResultWidget::enterProtected()
{
return true;
}
// virtual
bool CQEFMResultWidget::loadResult(const CCopasiTask * pTask)
{
mpTask = dynamic_cast<const CEFMTask *>(pTask);
if (mpTask != NULL)
{
mpEditFluxModes->setText(QString::number(mpTask->getFluxModes().size()));
}
else
{
mpEditFluxModes->setText(QString::number(0));
}
bool success = true;
success &= mpEFMListWidget->loadResult(mpTask);
mpReactionDM->setTask(mpTask);
mpProxyModelReactions->setSourceModel(mpReactionDM);
//Set Model for the TableView
mpReactionMatrix->setModel(NULL);
mpReactionMatrix->setModel(mpProxyModelReactions);
mpReactionMatrix->resizeColumnsToContents();
mpSpeciesDM->setTask(mpTask);
mpProxyModelSpecies->setSourceModel(mpSpeciesDM);
//Set Model for the TableView
mpSpeciesMatrix->setModel(NULL);
mpSpeciesMatrix->setModel(mpProxyModelSpecies);
mpSpeciesMatrix->resizeColumnsToContents();
mpNetReactionDM->setTask(mpTask);
mpProxyModelNetReactions->setSourceModel(mpNetReactionDM);
//Set Model for the TableView
mpNetReactions->setModel(NULL);
mpNetReactions->setModel(mpProxyModelNetReactions);
mpNetReactions->resizeColumnsToContents();
return success;
}
void CQEFMResultWidget::slotSave()
{
C_INT32 Answer = QMessageBox::No;
QString fileName;
while (Answer == QMessageBox::No)
{
fileName =
CopasiFileDialog::getSaveFileName(this, "Save File Dialog",
"untitled.txt", "TEXT Files (*.txt)", "Save to");
if (fileName.isEmpty()) return;
// Checks whether the file exists
Answer = checkSelection(fileName);
if (Answer == QMessageBox::Cancel) return;
}
std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str());
if (file.fail())
return;
if (mpTask != NULL)
file << mpTask->getResult();
return;
}
<|endoftext|> |
<commit_before>
#include "zorba/zorba_api.h"
#include <pthread.h>
#include <iostream>
using namespace std;
using namespace xqp;
/*
Using Zorba in full api mode.
Init the engine, create a query in main thread and execute it in parallel threads.
This way we optimize on compiling time.
*/
void DisplayErrorListForCurrentThread(std::ostream &result_file);
void* query_thread(void *param);
#define NR_THREADS 20
static XQuery_t xquery;
int usecase7(int argc, char* argv[])
{
//init the engine in full api mode
ZorbaEngine &zorba_engine = ZorbaEngine::getInstance();
unsigned int i;
pthread_t pt[NR_THREADS];
///in full api mode you have to call initThread() / uninitThread()
zorba_engine.initThread();
//create and compile a query with the static context
xquery = zorba_engine.createQuery(".//chapter[@id=$var1]");
if(xquery.isNull())
{
cout << "Error creating and compiling query1" << endl;
assert(false);
return 1;
}
for(i=0;i<NR_THREADS;i++)
{
pthread_create(&pt[i], NULL, query_thread, (void*)i);
}
///now wait for threads to finish
for(i=0;i<NR_THREADS;i++)
{
void *thread_result;
pthread_join(pt[i], &thread_result);
}
//close the engine for this thread and shutdown completely
zorba_engine.uninitThread();
zorba_engine.shutdown();
return 0;
}
void* query_thread(void *param)
{
//ZorbaEngine::getInstance can be called at any time
//only first call initializes the engine
ZorbaEngine &zorba_engine = ZorbaEngine::getInstance();
DynamicQueryContext_t dctx;
unsigned int iparam = (unsigned int)param;
//must call initThread before using any of Zorba features (other than getInstance())
zorba_engine.initThread();
dctx = zorba_engine.createDynamicContext();
//context item is set as variable with reserved name "."
if(!dctx->SetVariableAsDocument(".", "books.xml"))
{
cout << "cannot load document into context item" << endl;
assert(false);
return (void*)1;
}
if(!dctx->SetVariableAsInteger("var1", iparam))
{
cout << "cannot set var1 to iparam " << iparam << endl;
assert(false);
return (void*)1;
}
//execute the query and serialize its result
if(!xquery->executeSerializeXML(std::cout, dctx))//output will be a little scrammbled
{
cout << "Error executing and serializing query" << endl;
assert(false);
return (void*)1;
}
//must uninit the thread
zorba_engine.uninitThread();
//using zorba objects after this moment is prohibited
return (void*)0;
}
<commit_msg>check for pthread.h properly<commit_after>
#include "zorba/zorba_api.h"
#ifdef HAVE_PTHREAD_H
# include <pthread.h>
#else
# include "util/win32/pthread.h"
#endif
#include <iostream>
using namespace std;
using namespace xqp;
/*
Using Zorba in full api mode.
Init the engine, create a query in main thread and execute it in parallel threads.
This way we optimize on compiling time.
*/
void DisplayErrorListForCurrentThread(std::ostream &result_file);
void* query_thread(void *param);
#define NR_THREADS 20
static XQuery_t xquery;
int usecase7(int argc, char* argv[])
{
//init the engine in full api mode
ZorbaEngine &zorba_engine = ZorbaEngine::getInstance();
unsigned int i;
pthread_t pt[NR_THREADS];
///in full api mode you have to call initThread() / uninitThread()
zorba_engine.initThread();
//create and compile a query with the static context
xquery = zorba_engine.createQuery(".//chapter[@id=$var1]");
if(xquery.isNull())
{
cout << "Error creating and compiling query1" << endl;
assert(false);
return 1;
}
for(i=0;i<NR_THREADS;i++)
{
pthread_create(&pt[i], NULL, query_thread, (void*)i);
}
///now wait for threads to finish
for(i=0;i<NR_THREADS;i++)
{
void *thread_result;
pthread_join(pt[i], &thread_result);
}
//close the engine for this thread and shutdown completely
zorba_engine.uninitThread();
zorba_engine.shutdown();
return 0;
}
void* query_thread(void *param)
{
//ZorbaEngine::getInstance can be called at any time
//only first call initializes the engine
ZorbaEngine &zorba_engine = ZorbaEngine::getInstance();
DynamicQueryContext_t dctx;
unsigned int iparam = (unsigned int)param;
//must call initThread before using any of Zorba features (other than getInstance())
zorba_engine.initThread();
dctx = zorba_engine.createDynamicContext();
//context item is set as variable with reserved name "."
if(!dctx->SetVariableAsDocument(".", "books.xml"))
{
cout << "cannot load document into context item" << endl;
assert(false);
return (void*)1;
}
if(!dctx->SetVariableAsInteger("var1", iparam))
{
cout << "cannot set var1 to iparam " << iparam << endl;
assert(false);
return (void*)1;
}
//execute the query and serialize its result
if(!xquery->executeSerializeXML(std::cout, dctx))//output will be a little scrammbled
{
cout << "Error executing and serializing query" << endl;
assert(false);
return (void*)1;
}
//must uninit the thread
zorba_engine.uninitThread();
//using zorba objects after this moment is prohibited
return (void*)0;
}
<|endoftext|> |
<commit_before>/*
* Main application window
*
* This file is part of softrig, a simple software defined radio transceiver.
*
* Copyright 2017 Alexandru Csete OZ9AEC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <QDebug>
#include <QMenu>
#include <QToolButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>
#include "app/sdr_thread.h"
#include "gui/control_panel.h"
#include "gui/device_config.h"
#include "gui/freq_ctrl.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QWidget *spacer1;
QWidget *spacer2;
QWidget *spacer3;
ui->setupUi(this);
sdr = new SdrThread();
// 3 horizontal spacers
spacer1 = new QWidget();
spacer1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
spacer2 = new QWidget();
spacer2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
spacer3 = new QWidget();
spacer3->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
createButtons();
fctl = new FreqCtrl(this);
fctl->setup(8, 0, 60e6, 1, FCTL_UNIT_NONE);
fctl->setFrequency(14236000);
// top layout with frequency controller, meter and buttons
top_layout = new QHBoxLayout();
top_layout->addWidget(ptt_button);
top_layout->addWidget(spacer1);
top_layout->addWidget(fctl);
top_layout->addWidget(spacer2);
top_layout->addWidget(run_button);
top_layout->addWidget(cfg_button);
// main layout with FFT and control panel
main_layout = new QHBoxLayout();
// top level window layout
win_layout = new QVBoxLayout();
win_layout->addLayout(top_layout, 0);
win_layout->addLayout(main_layout, 1);
ui->centralWidget->setLayout(win_layout);
// connect(ui->cpanel, SIGNAL(confButtonClicked()),
// this, SLOT(runDeviceConfig()));
}
MainWindow::~MainWindow()
{
delete sdr;
delete cfg_menu;
delete cfg_button;
delete ptt_button;
delete run_button;
delete fctl;
delete top_layout;
delete main_layout;
delete win_layout;
delete ui;
}
void MainWindow::createButtons(void)
{
ptt_button = new QToolButton(this);
ptt_button->setText(tr("PTT"));
ptt_button->setCheckable(true);
ptt_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
run_button = new QToolButton(this);
run_button->setText(tr("Run"));
run_button->setCheckable(true);
run_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
connect(run_button, SIGNAL(clicked(bool)),
this, SLOT(runButtonClicked(bool)));
cfg_menu = new QMenu();
cfg_menu->setTitle(tr("Configure..."));
cfg_menu->addAction(tr("SDR device"));
cfg_menu->addAction(tr("Soundcard"));
cfg_menu->addAction(tr("User interface"));
cfg_button = new QToolButton(this);
cfg_button->setMenu(cfg_menu);
cfg_button->setArrowType(Qt::NoArrow);
cfg_button->setText(tr("CTL"));
cfg_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
connect(cfg_button, SIGNAL(triggered(QAction *)),
this, SLOT(menuActivated(QAction *)));
}
void MainWindow::runDeviceConfig()
{
DeviceConfig *dc;
int code;
dc = new DeviceConfig(this);
// dc->readSettings();
code = dc->exec();
if (code == QDialog::Accepted)
{
// dc->saveSettings
}
delete dc;
}
void MainWindow::runButtonClicked(bool checked)
{
qInfo("%s(%d)", __func__, checked);
if (checked)
sdr->start();
else
sdr->stop();
}
void MainWindow::menuActivated(QAction *action)
{
qInfo("'%s' activated", qUtf8Printable(action->text()));
}
<commit_msg>Remove remaining qInfo() calls<commit_after>/*
* Main application window
*
* This file is part of softrig, a simple software defined radio transceiver.
*
* Copyright 2017 Alexandru Csete OZ9AEC.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <QDebug>
#include <QMenu>
#include <QToolButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>
#include "app/sdr_thread.h"
#include "gui/control_panel.h"
#include "gui/device_config.h"
#include "gui/freq_ctrl.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QWidget *spacer1;
QWidget *spacer2;
QWidget *spacer3;
ui->setupUi(this);
sdr = new SdrThread();
// 3 horizontal spacers
spacer1 = new QWidget();
spacer1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
spacer2 = new QWidget();
spacer2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
spacer3 = new QWidget();
spacer3->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
createButtons();
fctl = new FreqCtrl(this);
fctl->setup(8, 0, 60e6, 1, FCTL_UNIT_NONE);
fctl->setFrequency(14236000);
// top layout with frequency controller, meter and buttons
top_layout = new QHBoxLayout();
top_layout->addWidget(ptt_button);
top_layout->addWidget(spacer1);
top_layout->addWidget(fctl);
top_layout->addWidget(spacer2);
top_layout->addWidget(run_button);
top_layout->addWidget(cfg_button);
// main layout with FFT and control panel
main_layout = new QHBoxLayout();
// top level window layout
win_layout = new QVBoxLayout();
win_layout->addLayout(top_layout, 0);
win_layout->addLayout(main_layout, 1);
ui->centralWidget->setLayout(win_layout);
// connect(ui->cpanel, SIGNAL(confButtonClicked()),
// this, SLOT(runDeviceConfig()));
}
MainWindow::~MainWindow()
{
delete sdr;
delete cfg_menu;
delete cfg_button;
delete ptt_button;
delete run_button;
delete fctl;
delete top_layout;
delete main_layout;
delete win_layout;
delete ui;
}
void MainWindow::createButtons(void)
{
ptt_button = new QToolButton(this);
ptt_button->setText(tr("PTT"));
ptt_button->setCheckable(true);
ptt_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
run_button = new QToolButton(this);
run_button->setText(tr("Run"));
run_button->setCheckable(true);
run_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
connect(run_button, SIGNAL(clicked(bool)),
this, SLOT(runButtonClicked(bool)));
cfg_menu = new QMenu();
cfg_menu->setTitle(tr("Configure..."));
cfg_menu->addAction(tr("SDR device"));
cfg_menu->addAction(tr("Soundcard"));
cfg_menu->addAction(tr("User interface"));
cfg_button = new QToolButton(this);
cfg_button->setMenu(cfg_menu);
cfg_button->setArrowType(Qt::NoArrow);
cfg_button->setText(tr("CTL"));
cfg_button->setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::MinimumExpanding);
connect(cfg_button, SIGNAL(triggered(QAction *)),
this, SLOT(menuActivated(QAction *)));
}
void MainWindow::runDeviceConfig()
{
DeviceConfig *dc;
int code;
dc = new DeviceConfig(this);
// dc->readSettings();
code = dc->exec();
if (code == QDialog::Accepted)
{
// dc->saveSettings
}
delete dc;
}
void MainWindow::runButtonClicked(bool checked)
{
if (checked)
sdr->start();
else
sdr->stop();
}
void MainWindow::menuActivated(QAction *action)
{
}
<|endoftext|> |
<commit_before>#pragma once
#include "syslog.h"
#include <string>
#include "blackhole/error.hpp"
#include "blackhole/repository/factory/traits.hpp"
namespace blackhole {
namespace sink {
enum class priority_t : unsigned {
emerg = LOG_EMERG,
alert = LOG_ALERT,
crit = LOG_CRIT,
err = LOG_ERR,
warning = LOG_WARNING,
notice = LOG_NOTICE,
info = LOG_INFO,
debug = LOG_DEBUG
};
template<typename Level>
struct priority_traits;
namespace backend {
class native_t {
const std::string m_identity;
public:
native_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_identity(identity)
{
initialize(option, facility);
}
~native_t() {
::closelog();
}
void write(priority_t priority, const std::string& message) {
::syslog(static_cast<unsigned>(priority), "%s", message.c_str());
}
private:
void initialize(int option, int facility) {
if(m_identity.empty()) {
throw error_t("no syslog identity has been specified");
}
::openlog(m_identity.c_str(), option, facility);
}
};
} // namespace backend
namespace syslog {
struct config_t {
std::string identity;
int option;
int facility;
config_t() {}
config_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
identity(identity),
option(option),
facility(facility)
{}
config_t(const std::string& identity, int facility) :
identity(identity),
option(LOG_PID),
facility(facility)
{}
};
} // namespace syslog
template<typename Level, typename Backend = backend::native_t>
class syslog_t {
Backend m_backend;
public:
typedef syslog::config_t config_type;
static const char* name() {
return "syslog";
}
syslog_t(const config_type& config) :
m_backend(config.identity, config.option, config.facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
syslog_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_backend(identity, option, facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
void consume(Level level, const std::string& message) {
priority_t priority = priority_traits<Level>::map(level);
m_backend.write(priority, message);
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
template<typename Level>
struct factory_traits<sink::syslog_t<Level>> {
typedef sink::syslog_t<Level> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["identity"].to(config.identity);
}
};
} // namespace blackhole
<commit_msg>[Aux] Code style.<commit_after>#pragma once
#include "syslog.h"
#include <string>
#include "blackhole/error.hpp"
#include "blackhole/repository/factory/traits.hpp"
namespace blackhole {
namespace sink {
enum class priority_t : unsigned {
emerg = LOG_EMERG,
alert = LOG_ALERT,
crit = LOG_CRIT,
err = LOG_ERR,
warning = LOG_WARNING,
notice = LOG_NOTICE,
info = LOG_INFO,
debug = LOG_DEBUG
};
template<typename Level>
struct priority_traits;
namespace backend {
class native_t {
const std::string m_identity;
public:
native_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_identity(identity)
{
initialize(option, facility);
}
~native_t() {
::closelog();
}
void write(priority_t priority, const std::string& message) {
::syslog(static_cast<unsigned>(priority), "%s", message.c_str());
}
private:
void initialize(int option, int facility) {
if (m_identity.empty()) {
throw error_t("no syslog identity has been specified");
}
::openlog(m_identity.c_str(), option, facility);
}
};
} // namespace backend
namespace syslog {
struct config_t {
std::string identity;
int option;
int facility;
config_t() {}
config_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
identity(identity),
option(option),
facility(facility)
{}
config_t(const std::string& identity, int facility) :
identity(identity),
option(LOG_PID),
facility(facility)
{}
};
} // namespace syslog
template<typename Level, typename Backend = backend::native_t>
class syslog_t {
Backend m_backend;
public:
typedef syslog::config_t config_type;
static const char* name() {
return "syslog";
}
syslog_t(const config_type& config) :
m_backend(config.identity, config.option, config.facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
syslog_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_backend(identity, option, facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
void consume(Level level, const std::string& message) {
priority_t priority = priority_traits<Level>::map(level);
m_backend.write(priority, message);
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
template<typename Level>
struct factory_traits<sink::syslog_t<Level>> {
typedef sink::syslog_t<Level> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["identity"].to(config.identity);
}
};
} // namespace blackhole
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "kangaru.hpp"
/**
* This example explains advanced use of kangaru and it's components.
* It covers invoke and autocall (injection by setters) through service map.
*/
using std::cout;
using std::endl;
struct Caramel {
Caramel() {
cout << "Caramel made" << endl;
}
void eat() {
cout << "yummy! Caramel!" << endl;
}
};
struct GummyBear {
GummyBear() {
cout << "GummyBear made" << endl;
}
void eat() {
cout << "yummy! GummyBear!" << endl;
}
};
struct CaramelService : kgr::Service<Caramel> {};
struct GummyBearService : kgr::Service<GummyBear> {};
template<typename>
struct ServiceMap;
template<> struct ServiceMap<Caramel> : kgr::Map<CaramelService> {};
template<> struct ServiceMap<GummyBear> : kgr::Map<GummyBearService> {};
struct CandyFactory {
CandyFactory(
kgr::Generator<CaramelService> myCaramelGenerator,
kgr::Generator<kgr::LazyService<GummyBearService>> myGummyBearGenerator,
kgr::Invoker<ServiceMap> myInvoker
) : caramelGenerator{myCaramelGenerator},
gummyBearGenerator{myGummyBearGenerator},
invoker{myInvoker} {}
kgr::Lazy<GummyBearService> makeGummyBear() {
return gummyBearGenerator();
}
Caramel makeCaramel() {
return caramelGenerator();
}
template<typename T>
void mix(T function) {
invoker(function);
}
private:
kgr::Generator<CaramelService> caramelGenerator;
kgr::Generator<kgr::LazyService<GummyBearService>> gummyBearGenerator;
kgr::Invoker<ServiceMap> invoker;
};
struct CandyFactoryService : kgr::SingleService<CandyFactory, kgr::Dependency<
kgr::GeneratorService<CaramelService>,
kgr::GeneratorService<kgr::LazyService<GummyBearService>>,
kgr::InvokerService<ServiceMap>
>> {};
void recepie(Caramel, GummyBear) {
cout << "A sweet recepie mixing Caramel and GummyBear completed" << endl;
}
int main() {
kgr::Container container;
auto candyFactory = container.service<CandyFactoryService>();
auto lazyGummyBear = candyFactory.makeGummyBear();
auto caramel = candyFactory.makeCaramel();
lazyGummyBear->eat();
caramel.eat();
cout << endl << "== Let's make a recepie ==" << endl;
candyFactory.mix(recepie);
return 0;
}
<commit_msg>added more helpful comments<commit_after>#include <iostream>
#include <string>
#include "kangaru.hpp"
/**
* This example explains advanced use of kangaru and it's components.
* It covers invoke and autocall (injection by setters) through service map.
*/
using std::cout;
using std::endl;
// Here we are declaring two candy types
struct Caramel {
Caramel() {
cout << "Caramel made" << endl;
}
void eat() {
cout << "yummy! Caramel!" << endl;
}
};
struct GummyBear {
GummyBear() {
cout << "GummyBear made" << endl;
}
void eat() {
cout << "yummy! GummyBear!" << endl;
}
};
// Then, we are declaring two service definition for them
struct CaramelService : kgr::Service<Caramel> {};
struct GummyBearService : kgr::Service<GummyBear> {};
// We will need the service map
template<typename>
struct ServiceMap;
template<> struct ServiceMap<Caramel> : kgr::Map<CaramelService> {};
template<> struct ServiceMap<GummyBear> : kgr::Map<GummyBearService> {};
// CandyFactory, making candies and recepies
struct CandyFactory {
CandyFactory(
kgr::Generator<CaramelService> myCaramelGenerator,
kgr::Generator<kgr::LazyService<GummyBearService>> myGummyBearGenerator,
kgr::Invoker<ServiceMap> myInvoker
) : caramelGenerator{myCaramelGenerator},
gummyBearGenerator{myGummyBearGenerator},
invoker{myInvoker} {}
kgr::Lazy<GummyBearService> makeGummyBear() {
return gummyBearGenerator();
}
Caramel makeCaramel() {
return caramelGenerator();
}
template<typename T>
void mix(T function) {
invoker(function);
}
private:
kgr::Generator<CaramelService> caramelGenerator;
kgr::Generator<kgr::LazyService<GummyBearService>> gummyBearGenerator;
kgr::Invoker<ServiceMap> invoker;
};
struct CandyFactoryService : kgr::SingleService<CandyFactory, kgr::Dependency<
kgr::GeneratorService<CaramelService>,
kgr::GeneratorService<kgr::LazyService<GummyBearService>>,
kgr::InvokerService<ServiceMap>
>> {};
// a recepie
void recepie(Caramel, GummyBear) {
cout << "A sweet recepie mixing Caramel and GummyBear completed" << endl;
}
int main() {
kgr::Container container;
// We are making our factory
auto candyFactory = container.service<CandyFactoryService>();
// this will print nothing, as there is no candy constructed
auto lazyGummyBear = candyFactory.makeGummyBear();
// this will print "Caramel made"
auto caramel = candyFactory.makeCaramel();
// This will print both "GummyBear made" and "yummy! GummyBear!"
lazyGummyBear->eat();
// This will print "yummy! Caramel!"
caramel.eat();
cout << endl << "== Let's make a recepie ==" << endl;
// As there are new candy made, this will print:
// > Caramel made
// > GummyBear made
// > A sweet recepie mixing Caramel and GummyBear completed
candyFactory.mix(recepie);
return 0;
}
<|endoftext|> |
<commit_before>/*
* good.cpp
*
* First Last
* uniqname@umich.edu
*
* A sample file for EECS 183 Style Grader.
*
* Demonstrates good style.
*/
#include <iostream>
using namespace std;
/**
* Requires: Nothing.
* Modifies: stdout.
* Effects: Greets the world.
*/
void greet(void);
int main(int argc, const char * argv[])
{
// greet the user
greet();
cout << "bye." << endl;
return 0;
}
void greet(void)
{
cout << "o hai world!" << endl;
cout << "o hai world!" << endl;
}
<commit_msg>Added some more issues for checking literal characters and insertion/extraction operators<commit_after>/*
* good.cpp
*
* First Last
* uniqname@umich.edu
*
* A sample file for EECS 183 Style Grader.
*
* Demonstrates good style.
*/
#include <iostream>
using namespace std;
/**
* Requires: Nothing.
* Modifies: stdout.
* Effects: Greets the world.
*/
void greet(void);
int main(int argc, const char * argv[])
{
// greet the user
greet();
cout << "bye.\'" << '*' << '\\' << '\"' << '\'*' << '-' << '+' << endl;
int x;
cin >> x;
return 0;
}
void greet(void)
{
cout << "o hai world!" << endl;
cout << "o hai world!" << endl;
}
<|endoftext|> |
<commit_before>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <cstring>
#include <bson.h>
#include <bsoncxx/document/view.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/json.hpp>
namespace bsoncxx {
BSONCXX_INLINE_NAMESPACE_BEGIN
namespace document {
view::iterator::iterator() {
}
view::iterator::iterator(const element& element) : _element(element) {
}
view::iterator::reference view::iterator::operator*() {
return _element;
}
view::iterator::pointer view::iterator::operator->() {
return &_element;
}
view::iterator& view::iterator::operator++() {
if (!_element) {
return *this;
}
bson_iter_t i;
i.raw = _element.raw;
i.len = _element.length;
i.next_off = _element.offset;
bson_iter_next(&i);
if (!bson_iter_next(&i)) {
_element.raw = nullptr;
_element.length = 0;
_element.offset = 0;
} else {
_element.raw = i.raw;
_element.length = i.len;
_element.offset = i.off;
}
return *this;
}
view::iterator view::iterator::operator++(int) {
iterator before(*this);
operator++();
return before;
}
bool operator==(const view::iterator& lhs, const view::iterator& rhs) {
return (lhs._element.raw == rhs._element.raw && lhs._element.offset == rhs._element.offset);
}
bool operator!=(const view::iterator& lhs, const view::iterator& rhs) {
return !(lhs == rhs);
}
view::const_iterator::const_iterator() {
}
view::const_iterator::const_iterator(const element& element) : _element(element) {
}
view::const_iterator::reference view::const_iterator::operator*() {
return _element;
}
view::const_iterator::pointer view::const_iterator::operator->() {
return &_element;
}
view::const_iterator& view::const_iterator::operator++() {
if (!_element) {
return *this;
}
bson_iter_t i;
i.raw = _element.raw;
i.len = _element.length;
i.next_off = _element.offset;
bson_iter_next(&i);
if (!bson_iter_next(&i)) {
_element.raw = nullptr;
_element.length = 0;
_element.offset = 0;
} else {
_element.raw = i.raw;
_element.length = i.len;
_element.offset = i.off;
}
return *this;
}
view::const_iterator view::const_iterator::operator++(int) {
const_iterator before(*this);
operator++();
return before;
}
bool operator==(const view::const_iterator& lhs, const view::const_iterator& rhs) {
return (lhs._element.raw == rhs._element.raw && lhs._element.offset == rhs._element.offset);
}
bool operator!=(const view::const_iterator& lhs, const view::const_iterator& rhs) {
return !(lhs == rhs);
}
view::const_iterator view::cbegin() const {
bson_t b;
bson_iter_t iter;
bson_init_static(&b, _data, _length);
bson_iter_init(&iter, &b);
bson_iter_next(&iter);
return const_iterator(element{iter.raw, iter.len, iter.off});
}
view::const_iterator view::cend() const {
return const_iterator();
}
view::iterator view::begin() const {
bson_t b;
bson_iter_t iter;
bson_init_static(&b, _data, _length);
bson_iter_init(&iter, &b);
bson_iter_next(&iter);
return iterator(element{iter.raw, iter.len, iter.off});
}
view::iterator view::end() const {
return iterator();
}
view::iterator view::find(stdx::string_view key) const {
bson_t b;
bson_iter_t iter;
bson_init_static(&b, _data, _length);
if (bson_iter_init_find(&iter, &b, key.data())) {
return iterator(element(iter.raw, iter.len, iter.off));
} else {
return end();
}
}
element view::operator[](stdx::string_view key) const {
return *(this->find(key));
}
view::view(const std::uint8_t* data, std::size_t length) : _data(data), _length(length) {
}
namespace {
uint8_t k_default_view[5] = {5, 0, 0, 0, 0};
}
view::view() : _data(k_default_view), _length(sizeof(k_default_view)) {
}
const std::uint8_t* view::data() const {
return _data;
}
std::size_t view::length() const {
return _length;
}
bool view::empty() const {
return _length == 5;
}
bool operator==(view lhs, view rhs) {
return (lhs.length() == rhs.length()) &&
(std::memcmp(lhs.data(), rhs.data(), lhs.length()) == 0);
}
bool operator!=(view lhs, view rhs) {
return !(lhs == rhs);
}
} // namespace document
BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx
<commit_msg>Minor: don't attempt to iterate over invalid bson object<commit_after>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <cstring>
#include <bson.h>
#include <bsoncxx/document/view.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/json.hpp>
namespace bsoncxx {
BSONCXX_INLINE_NAMESPACE_BEGIN
namespace document {
view::iterator::iterator() {
}
view::iterator::iterator(const element& element) : _element(element) {
}
view::iterator::reference view::iterator::operator*() {
return _element;
}
view::iterator::pointer view::iterator::operator->() {
return &_element;
}
view::iterator& view::iterator::operator++() {
if (!_element) {
return *this;
}
bson_iter_t i;
i.raw = _element.raw;
i.len = _element.length;
i.next_off = _element.offset;
bson_iter_next(&i);
if (!bson_iter_next(&i)) {
_element.raw = nullptr;
_element.length = 0;
_element.offset = 0;
} else {
_element.raw = i.raw;
_element.length = i.len;
_element.offset = i.off;
}
return *this;
}
view::iterator view::iterator::operator++(int) {
iterator before(*this);
operator++();
return before;
}
bool operator==(const view::iterator& lhs, const view::iterator& rhs) {
return (lhs._element.raw == rhs._element.raw && lhs._element.offset == rhs._element.offset);
}
bool operator!=(const view::iterator& lhs, const view::iterator& rhs) {
return !(lhs == rhs);
}
view::const_iterator::const_iterator() {
}
view::const_iterator::const_iterator(const element& element) : _element(element) {
}
view::const_iterator::reference view::const_iterator::operator*() {
return _element;
}
view::const_iterator::pointer view::const_iterator::operator->() {
return &_element;
}
view::const_iterator& view::const_iterator::operator++() {
if (!_element) {
return *this;
}
bson_iter_t i;
i.raw = _element.raw;
i.len = _element.length;
i.next_off = _element.offset;
bson_iter_next(&i);
if (!bson_iter_next(&i)) {
_element.raw = nullptr;
_element.length = 0;
_element.offset = 0;
} else {
_element.raw = i.raw;
_element.length = i.len;
_element.offset = i.off;
}
return *this;
}
view::const_iterator view::const_iterator::operator++(int) {
const_iterator before(*this);
operator++();
return before;
}
bool operator==(const view::const_iterator& lhs, const view::const_iterator& rhs) {
return (lhs._element.raw == rhs._element.raw && lhs._element.offset == rhs._element.offset);
}
bool operator!=(const view::const_iterator& lhs, const view::const_iterator& rhs) {
return !(lhs == rhs);
}
view::const_iterator view::cbegin() const {
bson_t b;
bson_iter_t iter;
bson_init_static(&b, _data, _length);
bson_iter_init(&iter, &b);
bson_iter_next(&iter);
return const_iterator(element{iter.raw, iter.len, iter.off});
}
view::const_iterator view::cend() const {
return const_iterator();
}
view::iterator view::begin() const {
bson_t b;
bson_iter_t iter;
bson_init_static(&b, _data, _length);
bson_iter_init(&iter, &b);
bson_iter_next(&iter);
return iterator(element{iter.raw, iter.len, iter.off});
}
view::iterator view::end() const {
return iterator();
}
view::iterator view::find(stdx::string_view key) const {
bson_t b;
bson_iter_t iter;
if (!bson_init_static(&b, _data, _length)) {
return end();
}
if (bson_iter_init_find(&iter, &b, key.data())) {
return iterator(element(iter.raw, iter.len, iter.off));
} else {
return end();
}
}
element view::operator[](stdx::string_view key) const {
return *(this->find(key));
}
view::view(const std::uint8_t* data, std::size_t length) : _data(data), _length(length) {
}
namespace {
uint8_t k_default_view[5] = {5, 0, 0, 0, 0};
}
view::view() : _data(k_default_view), _length(sizeof(k_default_view)) {
}
const std::uint8_t* view::data() const {
return _data;
}
std::size_t view::length() const {
return _length;
}
bool view::empty() const {
return _length == 5;
}
bool operator==(view lhs, view rhs) {
return (lhs.length() == rhs.length()) &&
(std::memcmp(lhs.data(), rhs.data(), lhs.length()) == 0);
}
bool operator!=(view lhs, view rhs) {
return !(lhs == rhs);
}
} // namespace document
BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx
<|endoftext|> |
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
***********************************************************************/
/**
* k-best Batch Mira, as described in:
*
* Colin Cherry and George Foster
* Batch Tuning Strategies for Statistical Machine Translation
* NAACL 2012
*
* Implemented by colin.cherry@nrc-cnrc.gc.ca
*
* To license implementations of any of the other tuners in that paper,
* please get in touch with any member of NRC Canada's Portage project
*
* Input is a set of n-best lists, encoded as feature and score files.
*
* Output is a weight file that results from running MIRA on these
* n-btest lists for J iterations. Will return the set that maximizes
* training BLEU.
**/
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/scoped_ptr.hpp>
#include "BleuScorer.h"
#include "HypPackEnumerator.h"
#include "MiraFeatureVector.h"
#include "MiraWeightVector.h"
using namespace std;
namespace po = boost::program_options;
ValType evaluate(HypPackEnumerator* train, const AvgWeightVector& wv) {
vector<ValType> stats(kBleuNgramOrder*2+1,0);
for(train->reset(); !train->finished(); train->next()) {
// Find max model
size_t max_index=0;
ValType max_score=0;
for(size_t i=0;i<train->cur_size();i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
if(i==0 || score > max_score) {
max_index = i;
max_score = score;
}
}
// Update stats
const vector<float>& sent = train->scoresAt(max_index);
for(size_t i=0;i<sent.size();i++) {
stats[i]+=sent[i];
}
}
return unsmoothedBleu(stats);
}
int main(int argc, char** argv)
{
bool help;
string denseInitFile;
string sparseInitFile;
vector<string> scoreFiles;
vector<string> featureFiles;
int seed;
string outputFile;
float c = 0.01; // Step-size cap C
float decay = 0.999; // Pseudo-corpus decay \gamma
int n_iters = 60; // Max epochs J
bool streaming = false; // Stream all k-best lists?
bool no_shuffle = false; // Don't shuffle, even for in memory version
bool model_bg = false; // Use model for background corpus
// Command-line processing follows pro.cpp
po::options_description desc("Allowed options");
desc.add_options()
("help,h", po::value(&help)->zero_tokens()->default_value(false), "Print this help message and exit")
("scfile,S", po::value<vector<string> >(&scoreFiles), "Scorer data files")
("ffile,F", po::value<vector<string> > (&featureFiles), "Feature data files")
("random-seed,r", po::value<int>(&seed), "Seed for random number generation")
("output-file,o", po::value<string>(&outputFile), "Output file")
("cparam,C", po::value<float>(&c), "MIRA C-parameter, lower for more regularization (default 0.01)")
("decay,D", po::value<float>(&decay), "BLEU background corpus decay rate (default 0.999)")
("iters,J", po::value<int>(&n_iters), "Number of MIRA iterations to run (default 60)")
("dense-init,d", po::value<string>(&denseInitFile), "Weight file for dense features")
("sparse-init,s", po::value<string>(&sparseInitFile), "Weight file for sparse features")
("streaming", po::value(&streaming)->zero_tokens()->default_value(false), "Stream n-best lists to save memory, implies --no-shuffle")
("no-shuffle", po::value(&no_shuffle)->zero_tokens()->default_value(false), "Don't shuffle hypotheses before each epoch")
("model-bg", po::value(&model_bg)->zero_tokens()->default_value(false), "Use model instead of hope for BLEU background");
;
po::options_description cmdline_options;
cmdline_options.add(desc);
po::variables_map vm;
po::store(po::command_line_parser(argc,argv).
options(cmdline_options).run(), vm);
po::notify(vm);
if (help) {
cout << "Usage: " + string(argv[0]) + " [options]" << endl;
cout << desc << endl;
exit(0);
}
if (vm.count("random-seed")) {
cerr << "Initialising random seed to " << seed << endl;
srand(seed);
} else {
cerr << "Initialising random seed from system clock" << endl;
srand(time(NULL));
}
// Initialize weights
///
// Dense
vector<parameter_t> initParams;
if(!denseInitFile.empty()) {
ifstream opt(denseInitFile.c_str());
string buffer;
if (opt.fail()) {
cerr << "could not open dense initfile: " << denseInitFile << endl;
exit(3);
}
parameter_t val;
getline(opt,buffer);
istringstream strstrm(buffer);
while(strstrm >> val) {
initParams.push_back(val);
}
opt.close();
}
size_t initDenseSize = initParams.size();
// Sparse
if(!sparseInitFile.empty()) {
if(initDenseSize==0) {
cerr << "sparse initialization requires dense initialization" << endl;
exit(3);
}
ifstream opt(sparseInitFile.c_str());
if(opt.fail()) {
cerr << "could not open sparse initfile: " << sparseInitFile << endl;
exit(3);
}
int sparseCount=0;
parameter_t val; std::string name;
while(opt >> name >> val) {
size_t id = SparseVector::encode(name) + initDenseSize;
while(initParams.size()<=id) initParams.push_back(0.0);
initParams[id] = val;
sparseCount++;
}
cerr << "Found " << sparseCount << " initial sparse features" << endl;
opt.close();
}
MiraWeightVector wv(initParams);
// Initialize background corpus
vector<ValType> bg;
for(int j=0;j<kBleuNgramOrder;j++){
bg.push_back(kBleuNgramOrder-j);
bg.push_back(kBleuNgramOrder-j);
}
bg.push_back(kBleuNgramOrder);
// Training loop
boost::scoped_ptr<HypPackEnumerator> train;
if(streaming)
train.reset(new StreamingHypPackEnumerator(featureFiles, scoreFiles));
else
train.reset(new RandomAccessHypPackEnumerator(featureFiles, scoreFiles, no_shuffle));
cerr << "Initial BLEU = " << evaluate(train.get(), wv.avg()) << endl;
ValType bestBleu = 0;
for(int j=0;j<n_iters;j++)
{
// MIRA train for one epoch
int iNumHyps = 0;
int iNumExamples = 0;
int iNumUpdates = 0;
ValType totalLoss = 0.0;
for(train->reset(); !train->finished(); train->next()) {
// Hope / fear decode
size_t hope_index=0, fear_index=0, model_index=0;
ValType hope_score=0, fear_score=0, model_score=0;
for(size_t i=0; i< train->cur_size(); i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
ValType bleu = sentenceLevelBackgroundBleu(train->scoresAt(i),bg);
// Hope
if(i==0 || (score + bleu) > hope_score) {
hope_score = score + bleu;
hope_index = i;
}
// Fear
if(i==0 || (score - bleu) > fear_score) {
fear_score = score - bleu;
fear_index = i;
}
// Model
if(i==0 || score > model_score) {
model_score = score;
model_index = i;
}
iNumHyps++;
}
// Update weights
if(hope_index!=fear_index) {
// Vector difference
MiraFeatureVector hope(train->featuresAt(hope_index));
MiraFeatureVector fear(train->featuresAt(fear_index));
MiraFeatureVector diff = hope - fear;
// Bleu difference
const vector<float>& hope_stats = train->scoresAt(hope_index);
ValType hopeBleu = sentenceLevelBackgroundBleu(hope_stats, bg);
const vector<float>& fear_stats = train->scoresAt(fear_index);
ValType fearBleu = sentenceLevelBackgroundBleu(fear_stats, bg);
assert(hopeBleu + 1e-8 >= fearBleu);
ValType delta = hopeBleu - fearBleu;
// Loss and update
ValType diff_score = wv.score(diff);
ValType loss = delta - diff_score;
if(loss > 0) {
ValType eta = min(c, loss / diff.sqrNorm());
wv.update(diff,eta);
totalLoss+=loss;
iNumUpdates++;
}
// Update BLEU statistics
const vector<float>& model_stats = train->scoresAt(model_index);
for(size_t k=0;k<bg.size();k++) {
bg[k]*=decay;
if(model_bg)
bg[k]+=model_stats[k];
else
bg[k]+=hope_stats[k];
}
}
iNumExamples++;
}
// Training Epoch summary
cerr << iNumUpdates << "/" << iNumExamples << " updates"
<< ", avg loss = " << (totalLoss / iNumExamples);
// Evaluate current average weights
AvgWeightVector avg = wv.avg();
ValType bleu = evaluate(train.get(), avg);
cerr << ", BLEU = " << bleu << endl;
if(bleu > bestBleu) {
size_t num_dense = train->num_dense();
if(initDenseSize>0 && initDenseSize!=num_dense) {
cerr << "Error: Initial dense feature count and dense feature count from n-best do not match: "
<< initDenseSize << "!=" << num_dense << endl;
exit(1);
}
// Write to a file
ostream* out;
ofstream outFile;
if (!outputFile.empty() ) {
outFile.open(outputFile.c_str());
if (!(outFile)) {
cerr << "Error: Failed to open " << outputFile << endl;
exit(1);
}
out = &outFile;
} else {
out = &cout;
}
for(size_t i=0;i<avg.size();i++) {
if(i<num_dense)
*out << "F" << i << " " << avg.weight(i) << endl;
else {
if(abs(avg.weight(i))>1e-8)
*out << SparseVector::decode(i-num_dense) << " " << avg.weight(i) << endl;
}
}
outFile.close();
bestBleu = bleu;
}
}
cerr << "Best BLEU = " << bestBleu << endl;
}
// --Emacs trickery--
// Local Variables:
// mode:c++
// c-basic-offset:2
// End:
<commit_msg>Spurious space disagreed with master<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
***********************************************************************/
/**
* k-best Batch Mira, as described in:
*
* Colin Cherry and George Foster
* Batch Tuning Strategies for Statistical Machine Translation
* NAACL 2012
*
* Implemented by colin.cherry@nrc-cnrc.gc.ca
*
* To license implementations of any of the other tuners in that paper,
* please get in touch with any member of NRC Canada's Portage project
*
* Input is a set of n-best lists, encoded as feature and score files.
*
* Output is a weight file that results from running MIRA on these
* n-btest lists for J iterations. Will return the set that maximizes
* training BLEU.
**/
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/program_options.hpp>
#include <boost/scoped_ptr.hpp>
#include "BleuScorer.h"
#include "HypPackEnumerator.h"
#include "MiraFeatureVector.h"
#include "MiraWeightVector.h"
using namespace std;
namespace po = boost::program_options;
ValType evaluate(HypPackEnumerator* train, const AvgWeightVector& wv) {
vector<ValType> stats(kBleuNgramOrder*2+1,0);
for(train->reset(); !train->finished(); train->next()) {
// Find max model
size_t max_index=0;
ValType max_score=0;
for(size_t i=0;i<train->cur_size();i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
if(i==0 || score > max_score) {
max_index = i;
max_score = score;
}
}
// Update stats
const vector<float>& sent = train->scoresAt(max_index);
for(size_t i=0;i<sent.size();i++) {
stats[i]+=sent[i];
}
}
return unsmoothedBleu(stats);
}
int main(int argc, char** argv)
{
bool help;
string denseInitFile;
string sparseInitFile;
vector<string> scoreFiles;
vector<string> featureFiles;
int seed;
string outputFile;
float c = 0.01; // Step-size cap C
float decay = 0.999; // Pseudo-corpus decay \gamma
int n_iters = 60; // Max epochs J
bool streaming = false; // Stream all k-best lists?
bool no_shuffle = false; // Don't shuffle, even for in memory version
bool model_bg = false; // Use model for background corpus
// Command-line processing follows pro.cpp
po::options_description desc("Allowed options");
desc.add_options()
("help,h", po::value(&help)->zero_tokens()->default_value(false), "Print this help message and exit")
("scfile,S", po::value<vector<string> >(&scoreFiles), "Scorer data files")
("ffile,F", po::value<vector<string> > (&featureFiles), "Feature data files")
("random-seed,r", po::value<int>(&seed), "Seed for random number generation")
("output-file,o", po::value<string>(&outputFile), "Output file")
("cparam,C", po::value<float>(&c), "MIRA C-parameter, lower for more regularization (default 0.01)")
("decay,D", po::value<float>(&decay), "BLEU background corpus decay rate (default 0.999)")
("iters,J", po::value<int>(&n_iters), "Number of MIRA iterations to run (default 60)")
("dense-init,d", po::value<string>(&denseInitFile), "Weight file for dense features")
("sparse-init,s", po::value<string>(&sparseInitFile), "Weight file for sparse features")
("streaming", po::value(&streaming)->zero_tokens()->default_value(false), "Stream n-best lists to save memory, implies --no-shuffle")
("no-shuffle", po::value(&no_shuffle)->zero_tokens()->default_value(false), "Don't shuffle hypotheses before each epoch")
("model-bg", po::value(&model_bg)->zero_tokens()->default_value(false), "Use model instead of hope for BLEU background");
;
po::options_description cmdline_options;
cmdline_options.add(desc);
po::variables_map vm;
po::store(po::command_line_parser(argc,argv).
options(cmdline_options).run(), vm);
po::notify(vm);
if (help) {
cout << "Usage: " + string(argv[0]) + " [options]" << endl;
cout << desc << endl;
exit(0);
}
if (vm.count("random-seed")) {
cerr << "Initialising random seed to " << seed << endl;
srand(seed);
} else {
cerr << "Initialising random seed from system clock" << endl;
srand(time(NULL));
}
// Initialize weights
///
// Dense
vector<parameter_t> initParams;
if(!denseInitFile.empty()) {
ifstream opt(denseInitFile.c_str());
string buffer;
if (opt.fail()) {
cerr << "could not open dense initfile: " << denseInitFile << endl;
exit(3);
}
parameter_t val;
getline(opt,buffer);
istringstream strstrm(buffer);
while(strstrm >> val) {
initParams.push_back(val);
}
opt.close();
}
size_t initDenseSize = initParams.size();
// Sparse
if(!sparseInitFile.empty()) {
if(initDenseSize==0) {
cerr << "sparse initialization requires dense initialization" << endl;
exit(3);
}
ifstream opt(sparseInitFile.c_str());
if(opt.fail()) {
cerr << "could not open sparse initfile: " << sparseInitFile << endl;
exit(3);
}
int sparseCount=0;
parameter_t val; std::string name;
while(opt >> name >> val) {
size_t id = SparseVector::encode(name) + initDenseSize;
while(initParams.size()<=id) initParams.push_back(0.0);
initParams[id] = val;
sparseCount++;
}
cerr << "Found " << sparseCount << " initial sparse features" << endl;
opt.close();
}
MiraWeightVector wv(initParams);
// Initialize background corpus
vector<ValType> bg;
for(int j=0;j<kBleuNgramOrder;j++){
bg.push_back(kBleuNgramOrder-j);
bg.push_back(kBleuNgramOrder-j);
}
bg.push_back(kBleuNgramOrder);
// Training loop
boost::scoped_ptr<HypPackEnumerator> train;
if(streaming)
train.reset(new StreamingHypPackEnumerator(featureFiles, scoreFiles));
else
train.reset(new RandomAccessHypPackEnumerator(featureFiles, scoreFiles, no_shuffle));
cerr << "Initial BLEU = " << evaluate(train.get(), wv.avg()) << endl;
ValType bestBleu = 0;
for(int j=0;j<n_iters;j++)
{
// MIRA train for one epoch
int iNumHyps = 0;
int iNumExamples = 0;
int iNumUpdates = 0;
ValType totalLoss = 0.0;
for(train->reset(); !train->finished(); train->next()) {
// Hope / fear decode
size_t hope_index=0, fear_index=0, model_index=0;
ValType hope_score=0, fear_score=0, model_score=0;
for(size_t i=0; i< train->cur_size(); i++) {
MiraFeatureVector vec(train->featuresAt(i));
ValType score = wv.score(vec);
ValType bleu = sentenceLevelBackgroundBleu(train->scoresAt(i),bg);
// Hope
if(i==0 || (score + bleu) > hope_score) {
hope_score = score + bleu;
hope_index = i;
}
// Fear
if(i==0 || (score - bleu) > fear_score) {
fear_score = score - bleu;
fear_index = i;
}
// Model
if(i==0 || score > model_score) {
model_score = score;
model_index = i;
}
iNumHyps++;
}
// Update weights
if(hope_index!=fear_index) {
// Vector difference
MiraFeatureVector hope(train->featuresAt(hope_index));
MiraFeatureVector fear(train->featuresAt(fear_index));
MiraFeatureVector diff = hope - fear;
// Bleu difference
const vector<float>& hope_stats = train->scoresAt(hope_index);
ValType hopeBleu = sentenceLevelBackgroundBleu(hope_stats, bg);
const vector<float>& fear_stats = train->scoresAt(fear_index);
ValType fearBleu = sentenceLevelBackgroundBleu(fear_stats, bg);
assert(hopeBleu + 1e-8 >= fearBleu);
ValType delta = hopeBleu - fearBleu;
// Loss and update
ValType diff_score = wv.score(diff);
ValType loss = delta - diff_score;
if(loss > 0) {
ValType eta = min(c, loss / diff.sqrNorm());
wv.update(diff,eta);
totalLoss+=loss;
iNumUpdates++;
}
// Update BLEU statistics
const vector<float>& model_stats = train->scoresAt(model_index);
for(size_t k=0;k<bg.size();k++) {
bg[k]*=decay;
if(model_bg)
bg[k]+=model_stats[k];
else
bg[k]+=hope_stats[k];
}
}
iNumExamples++;
}
// Training Epoch summary
cerr << iNumUpdates << "/" << iNumExamples << " updates"
<< ", avg loss = " << (totalLoss / iNumExamples);
// Evaluate current average weights
AvgWeightVector avg = wv.avg();
ValType bleu = evaluate(train.get(), avg);
cerr << ", BLEU = " << bleu << endl;
if(bleu > bestBleu) {
size_t num_dense = train->num_dense();
if(initDenseSize>0 && initDenseSize!=num_dense) {
cerr << "Error: Initial dense feature count and dense feature count from n-best do not match: "
<< initDenseSize << "!=" << num_dense << endl;
exit(1);
}
// Write to a file
ostream* out;
ofstream outFile;
if (!outputFile.empty() ) {
outFile.open(outputFile.c_str());
if (!(outFile)) {
cerr << "Error: Failed to open " << outputFile << endl;
exit(1);
}
out = &outFile;
} else {
out = &cout;
}
for(size_t i=0;i<avg.size();i++) {
if(i<num_dense)
*out << "F" << i << " " << avg.weight(i) << endl;
else {
if(abs(avg.weight(i))>1e-8)
*out << SparseVector::decode(i-num_dense) << " " << avg.weight(i) << endl;
}
}
outFile.close();
bestBleu = bleu;
}
}
cerr << "Best BLEU = " << bestBleu << endl;
}
// --Emacs trickery--
// Local Variables:
// mode:c++
// c-basic-offset:2
// End:
<|endoftext|> |
<commit_before>
// Qt includes
#include <QDebug>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QTimer>
// CTK includes
#include <ctkCallback.h>
// Visomics includes
#include "voApplication.h"
#include "voConfigure.h" // For Visomics_VERSION, Visomics_INSTALL_RSCRIPTS_DIR
#include "voMainWindow.h"
// VTK includes
#include <vtkRInterface.h>
#include <vtkNew.h>
namespace
{
//----------------------------------------------------------------------------
void popupMessageAndQuit(QWidget * parent, const QString& message)
{
QMessageBox::critical(parent, QString("Visomics %1").arg(Visomics_VERSION), message);
qCritical() << message;
voApplication::application()->quit();
}
//----------------------------------------------------------------------------
void checkRPrerequisites(void * data)
{
voApplication * app = voApplication::application();
voMainWindow * mainWindow = reinterpret_cast<voMainWindow*>(data);
if (!QFile::exists(app->rHome()))
{
QString message("GnuR requires <b>R_HOME</b> environement variable to be set properly.<br><br>");
if (app->rHome().isEmpty())
{
message.append("R_HOME is either not set or set to an empty value.<br>");
}
else
{
message.append("R_HOME is set to a nonexistent directory:<br>");
message.append("<br>");
message.append(app->rHome()).append("<br>");
}
message.append("<br>The application will be terminated.");
popupMessageAndQuit(mainWindow, message);
return;
}
QString rscriptFilePath = QLatin1String(Visomics_SOURCE_DIR) + "/Utilities/GetRExternalPackages.R";
if(app->isInstalled())
{
rscriptFilePath = app->homeDirectory() + "/" + Visomics_INSTALL_RSCRIPTS_DIR + "/GetRExternalPackages.R";
}
qDebug() << "Evaluating R script:" << rscriptFilePath;
QFile rscriptFile(rscriptFilePath);
if (!rscriptFile.exists())
{
popupMessageAndQuit(mainWindow, QString("Script %1 doesn't exist.").arg(rscriptFilePath));
return;
}
if (!rscriptFile.open(QFile::ReadOnly))
{
popupMessageAndQuit(mainWindow, QString("Failed to read script %1").arg(rscriptFilePath));
return;
}
QTextStream in(&rscriptFile);
QString rscript = in.readAll();
vtkNew<vtkRInterface> rInterface;
char outputBuffer[2048];
rInterface->OutputBuffer(outputBuffer, 2048);
rInterface->EvalRscript(rscript.toLatin1(), /* showRoutput= */ false);
qDebug() << outputBuffer;
QString message("Problem running R script: ");
message.append(rscriptFilePath).append("<br><br>");
foreach(const QString& package, QStringList() << "pls" << "preprocessCore")
{
if (!QString(outputBuffer).contains(QString("Package '%1' found").arg(package)))
{
message.append(QString("Failed to install R package: %1").arg(package));
popupMessageAndQuit(mainWindow, message);
return;
}
}
}
} // end of anonymous namespace
//----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
voApplication app(argc, argv);
Q_INIT_RESOURCE(VisomicsApp);
Q_INIT_RESOURCE(VisomicsBase);
bool exitWhenDone = false;
app.initialize(exitWhenDone);
if (exitWhenDone)
{
return EXIT_SUCCESS;
}
voMainWindow mainwindow;
mainwindow.show();
ctkCallback callback;
callback.setCallback(checkRPrerequisites);
callback.setCallbackData(&mainwindow);
QTimer::singleShot(0, &callback, SLOT(invoke()));
return app.exec();
}
<commit_msg>Missing R packages do not prevent the application from starting<commit_after>
// Qt includes
#include <QDebug>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QTimer>
// CTK includes
#include <ctkCallback.h>
// Visomics includes
#include "voApplication.h"
#include "voConfigure.h" // For Visomics_VERSION, Visomics_INSTALL_RSCRIPTS_DIR
#include "voMainWindow.h"
// VTK includes
#include <vtkRInterface.h>
#include <vtkNew.h>
namespace
{
//----------------------------------------------------------------------------
void popupMessage(QWidget * parent, const QString& message)
{
QMessageBox::critical(parent, QString("Visomics %1").arg(Visomics_VERSION), message);
qCritical() << message;
}
//----------------------------------------------------------------------------
void popupMessageAndQuit(QWidget * parent, const QString& message)
{
QString tmp = message;
popupMessage(parent, tmp.append("<br><br><big><img src=\":/Icons/Bulb.png\"> The application will be terminated</big>"));
voApplication::application()->quit();
}
//----------------------------------------------------------------------------
void checkRPrerequisites(void * data)
{
voApplication * app = voApplication::application();
voMainWindow * mainWindow = reinterpret_cast<voMainWindow*>(data);
QString message;
if (!QFile::exists(app->rHome()))
{
message = "<big>GnuR expects <b>R_HOME</b> environement variable.</big><br><br>";
if (app->rHome().isEmpty())
{
message.append("R_HOME is either not set or set to an empty value.<br>");
}
else
{
message.append("R_HOME is set to a nonexistent directory:<br>");
message.append("<br>");
message.append(app->rHome()).append("<br>");
}
popupMessageAndQuit(mainWindow, message);
return;
}
QString rscriptFilePath = QLatin1String(Visomics_SOURCE_DIR) + "/Utilities/GetRExternalPackages.R";
if(app->isInstalled())
{
rscriptFilePath = app->homeDirectory() + "/" + Visomics_INSTALL_RSCRIPTS_DIR + "/GetRExternalPackages.R";
}
qDebug() << "Evaluating R script:" << rscriptFilePath;
QFile rscriptFile(rscriptFilePath);
if (!rscriptFile.exists())
{
popupMessage(mainWindow, QString("<big>Script doesn't exist</big><br><br>%1").arg(rscriptFilePath));
return;
}
if (!rscriptFile.open(QFile::ReadOnly))
{
popupMessage(mainWindow, QString("<big>Failed to read script</big><br><br>%1").arg(rscriptFilePath));
return;
}
QTextStream in(&rscriptFile);
QString rscript = in.readAll();
vtkNew<vtkRInterface> rInterface;
char outputBuffer[2048];
rInterface->OutputBuffer(outputBuffer, 2048);
rInterface->EvalRscript(rscript.toLatin1(), /* showRoutput= */ false);
qDebug() << outputBuffer;
message = "<big>Problem running R script</big><br><br>";
message.append(rscriptFilePath).append("<br>");
message.append("<ul>");
bool installationFailed = false;
QString package = "pls";
QString requiredBy = "<b>PLSStatistics</b> analysis";
if (!QString(outputBuffer).contains(QString("Package '%1' found").arg(package)))
{
message.append(QString("<li>R package <b>%1</b> required by %2 is not installed</li><br>")
.arg(package).arg(requiredBy));
installationFailed = true;
}
package = "preprocessCore";
requiredBy = "<b>Quantile</b> normalization";
if (!QString(outputBuffer).contains(QString("Package '%1' found").arg(package)))
{
message.append(QString("<li>R package <b>%1</b> required by %2 is not installed</li><br>")
.arg(package).arg(requiredBy));
installationFailed = true;
}
message.append("</ul>");
if(installationFailed)
{
message.append("<br><big><img src=\":/Icons/Bulb.png\"> The application will start but not all"
" functionalities will be available</big>");
popupMessage(mainWindow, message);
}
}
} // end of anonymous namespace
//----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
voApplication app(argc, argv);
Q_INIT_RESOURCE(VisomicsApp);
Q_INIT_RESOURCE(VisomicsBase);
bool exitWhenDone = false;
app.initialize(exitWhenDone);
if (exitWhenDone)
{
return EXIT_SUCCESS;
}
voMainWindow mainwindow;
mainwindow.show();
ctkCallback callback;
callback.setCallback(checkRPrerequisites);
callback.setCallbackData(&mainwindow);
QTimer::singleShot(0, &callback, SLOT(invoke()));
return app.exec();
}
<|endoftext|> |
<commit_before>/**
* @file Cosa/TWI/Driver/ADXL345.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013-2014, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef COSA_TWI_DRIVER_ADXL345_HH
#define COSA_TWI_DRIVER_ADXL345_HH
#include "Cosa/TWI.hh"
#include "Cosa/IOStream.hh"
/**
* Cosa TWI driver for Analog Devices ADXL345 Digital Accelerometer.
* http://www.analog.com/static/imported-files/data_sheets/ADXL345.pdf
* Rev. D, 2/13.
*
* @section Circuit
* The GY-291 module with pull-up resistors (4K7) for TWI signals and
* 3V3 internal voltage converter.
* @code
* GY-291
* +------------+
* (GND)---------------1-|GND |
* (VCC)---------------2-|VCC |
* 3-|CS |
* 4-|A-INT1 |
* 5-|A-INT2 |
* 6-|SDO |
* (A4/SDA)------------7-|SDA |
* (A5/SCL)------------8-|SCL |
* +------------+
* @endcode
*/
class ADXL345 : private TWI::Driver {
public:
/**
* Registers Map (See tab. 19, pp. 23).
*/
enum Register {
DEVID = 0x00, //!< Device ID.
THRESH_TAP = 0x1D, //!< Tap threshold.
OFS = 0x1E, //!< Offset (x, y, z).
DUR = 0x21, //!< Tap duration.
LATENT = 0x22, //!< Tap latency.
WINDOW = 0x23, //!< Tap window.
THRESH_ACT = 0x24, //!< Activity threshold.
THRESH_INACT = 0x25, //!< Inactivity threshold.
TIME_INACT = 0x26, //!< Inactivity time.
ACT_INACT_CTL = 0x27, //!< Axis enable control for activity detection.
THRESH_FF = 0x28, //!< Free-fall threshold.
TIME_FF = 0x29, //!< Free-fall time.
TAP_AXES = 0x2A, //!< Axis control for single tap/double tap.
ACT_TAP_STATUS = 0x2B, //!< Source of single tap/double tap.
BW_RATE = 0x2C, //!< Data rate and power mode control.
POWER_CTL = 0x2D, //!< Power-saving features control.
INT_ENABLE = 0x2E, //!< Interrupt enable control.
INT_MAP = 0x2F, //!< Interrupt mapping control.
INT_SOURCE = 0x30, //!< Source of interrupts.
DATA_FORMAT = 0x31, //!< Data format control.
DATA = 0x32, //!< Data (x, y, z).
FIFO_CTL = 0x38, //!< FIFO control.
FIFO_STATUS = 0x39 //!< FIFO status.
} __attribute__((packed));
/** Register DEVID value (345). */
static const uint8_t ID = 0xe5;
/**
* Register ACT_INACT_CTL bitfields.
*/
enum {
ACT_AC_DC = 7, //!< AC/DC coupled activity.
ACT_X_EN = 6, //!< Activity x axis enable.
ACT_Y_EN = 5, //!< Activity x axis enable.
ACT_Z_EN = 4, //!< Activity x axis enable.
INACT_AC_DC = 3, //!< AC/DC coupled inactivity.
INACT_X_EN = 2, //!< Inactivity x axis enable.
INACT_Y_EN = 1, //!< Inactivity x axis enable.
INACT_Z_EN = 0 //!< Inactivity x axis enable.
} __attribute__((packed));
/**
* Register TAP_AXES bitfields.
*/
enum {
SUPPRES = 3, //!< Suppress.
TAP_X_EN = 2, //!< Tap x enable.
TAP_Y_EN = 1, //!< Tap y enable.
TAP_Z_EN = 0, //!< Tap z enable.
} __attribute__((packed));
/**
* Register ACT_TAP_STATUS bitfields.
*/
enum {
ACT_X_SRC = 6, //!< Activity x event.
ACT_Y_SRC = 5, //!< Activity y event.
ACT_Z_SRC = 4, //!< Activity z event.
ASLEEP = 3, //!< Device is asleep.
TAP_X_SRC = 2, //!< Tap x event.
TAP_Y_SRC = 1, //!< Tap y event.
TAP_Z_SRC = 0 //!< Tap z event.
} __attribute__((packed));
/**
* Register BW_RATE bitfields.
*/
enum {
LOW_POWER = 4, //!< Low power move.
RATE = 0, //!< Data rate (4 bits).
RATE_MASK = 0x0f //!< Data rate mask.
} __attribute__((packed));
/**
* Register POWER_CTL bitfields.
*/
enum {
LINK = 5, //!< Link mode select.
AUTO_SLEEP = 4, //!< Auto sleep enable.
MEASURE = 3, //!< Measurement mode.
SLEEP = 2, //!< Sleep mode.
WAKEUP = 0, //!< Wakeup frequency (2 bits).
} __attribute__((packed));
enum {
WAKEUP_8_HZ = 0, //!< 8 hz.
WAKEUP_4_HZ = 1, //!< 4 hz.
WAKEUP_2_HZ = 2, //!< 2 hz.
WAKEUP_1_HZ = 3, //!< 1 hz.
WAKEUP_MASK = 3 //!< Wakeup frequency mask.
};
/**
* Register INT_ENABLE/INT_MAP/INT_SOURCE bitfields.
*/
enum {
DATA_READY = 7, //!< Data ready interrupt enable/map/source.
SINGLE_TAP = 6, //!< Single tap.
DOUBLE_TAP = 5, //!< Double tap.
ACT = 4, //!< Activity.
INACT = 3, //!< Inactivity.
FREE_FALL = 2, //!< Free fall.
WATERMARK = 1, //!< Watermark.
OVERRUN = 0 //!< Overrun interrupt enable/map/source.
} __attribute__((packed));
/**
* Register DATA_FORMAT bitfields.
*/
enum {
SELF_TEST = 7, //!< Self-test force.
SPI_WIRE_MODE = 6, //!< SPI wire mode.
INT_INVERT = 5, //!< Interrupt active high/low.
FULL_RES = 3, //!< Full resolution.
JUSTIFY = 2, //!< Left justified/sign extend.
RANGE = 0 //!< Range 2-16 g (2 bits).
} __attribute__((packed));
enum {
RANGE_2G = 0, //!< +-2g.
RANGE_4G = 1, //!< +-4g.
RANGE_8G = 2, //!< +-8g.
RANGE_16G = 3, //!< +-16g.
RANGE_MASK = 3 //!< Mask range field.
} __attribute__((packed));
/**
* Register FIFO_CTL bitfields.
*/
enum {
FIFO_MODE = 6, //!< FIFO Mode.
FIFO_MASK = 0xc0, //!< Dito Mask.
TRIG = 5, //!< Trigger event to interrupt pin.
SAMPLES = 0, //!< Number of samples (5 bits).
SAMPLES_MASK = 0x1f //!< Dito Mask.
} __attribute__((packed));
enum {
BYPASS = 0x00, //!< FIFO is bypassed.
FIFO = 0x40, //!< Collects up to 32 values.
STREAM = 0x80, //!< Holds the latest 32 values.
TRIGGER = 0xc0 //!< Latest 32 values before trigger.
};
/**
* Register FIFO_STATUS bitfields.
*/
enum {
FIFO_TRIG = 7, //!< FIFO trigger event occuring.
ENTRIES = 0, //!< Number of entries in FIFO (6 bits).
ENTRIES_MASK = 0x3f //!< Dito Mask.
} __attribute__((packed));
/**
* Write given value to register.
* @param[in] reg register address.
* @param[in] value register value.
*/
void write(Register reg, uint8_t value);
/**
* Write multiple registers with values from give address.
* @param[in] reg register address.
* @param[in] buffer storage.
* @param[in] count number of bytes.
*/
void write(Register reg, void* buffer, uint8_t count);
/**
* Read contents of register.
* @param[in] reg register address.
* @return register value.
*/
uint8_t read(Register reg)
{
uint8_t res;
read(reg, &res, sizeof(res));
return (res);
}
/**
* Read contents of registers, multiple values from give address.
* @param[in] reg register address.
* @param[in] buffer storage.
* @param[in] count number of bytes.
*/
void read(Register reg, void* buffer, uint8_t count);
/** 3-Axis setting (add or or values). */
enum {
X = 4,
Y = 2,
Z = 1
} __attribute__((packed));
/**
* Construct ADXL345 driver with normal or alternative address (pp. 18).
* @param[in] use_alt_address.
*/
ADXL345(bool use_alt_address = false) :
TWI::Driver(use_alt_address ? 0x53 : 0x1d)
{
}
/**
* Start interaction with device. Set full resolution and 16G.
* Single and double tap detection in XYZ-axis. Activity/inactivity
* (5 seconds), and free fall detect. Power control with auto-sleep
* and wakeup at 2 Hz. Interrupts enabled. Measurement turned on.
* @return true(1) if successful otherwise false(0)
*/
bool begin();
/**
* Stop sequence of interaction with device. Turn off measurement.
* @return true(1) if successful otherwise false(0)
*/
bool end();
/**
* Accelerometer offset calibration structure.
*/
struct offset_t {
int8_t x;
int8_t y;
int8_t z;
};
/**
* Calibrate accelerometer with given offsets.
* @param[in] x axis offset.
* @param[in] y axis offset.
* @param[in] z axis offset.
*/
void calibrate(int8_t x, int8_t y, int8_t z)
{
offset_t ofs;
ofs.x = x;
ofs.y = y;
ofs.z = z;
write(OFS, &ofs, sizeof(ofs));
}
/**
* Calibrate accelerometer by resetting offset and
* using the current accelerometer values as offset.
* (-sample/4) according to ADXL345 documentation.
*/
void calibrate();
/**
* Accelerometer sample data structure (axis x, y, z).
*/
struct sample_t {
int x;
int y;
int z;
};
/**
* Sample accelerometer. Return sample is given data structure
* @param[in] s sample storage.
*/
void sample(sample_t& s)
{
read(DATA, &s, sizeof(s));
}
/**
* Check for activity. Returns a bitset with current activity.
* Ignore WATERMARK and OVERRUN.
* @return activities
*/
uint8_t is_activity();
};
/**
* Print the latest reading to the given output stream.
* @param[in] outs output stream.
* @param[in] accelerometer instance.
* @return output stream.
*/
extern IOStream& operator<<(IOStream& outs, ADXL345& accelerometer);
#endif
<commit_msg>Cleanup; add always inline.<commit_after>/**
* @file Cosa/TWI/Driver/ADXL345.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013-2014, Mikael Patel
*
* 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.
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef COSA_TWI_DRIVER_ADXL345_HH
#define COSA_TWI_DRIVER_ADXL345_HH
#include "Cosa/TWI.hh"
#include "Cosa/IOStream.hh"
/**
* Cosa TWI driver for Analog Devices ADXL345 Digital Accelerometer.
* http://www.analog.com/static/imported-files/data_sheets/ADXL345.pdf
* Rev. D, 2/13.
*
* @section Circuit
* The GY-291 module with pull-up resistors (4K7) for TWI signals and
* 3V3 internal voltage converter.
* @code
* GY-291
* +------------+
* (GND)---------------1-|GND |
* (VCC)---------------2-|VCC |
* 3-|CS |
* 4-|A-INT1 |
* 5-|A-INT2 |
* 6-|SDO |
* (A4/SDA)------------7-|SDA |
* (A5/SCL)------------8-|SCL |
* +------------+
* @endcode
*/
class ADXL345 : private TWI::Driver {
public:
/**
* Registers Map (See tab. 19, pp. 23).
*/
enum Register {
DEVID = 0x00, //!< Device ID.
THRESH_TAP = 0x1D, //!< Tap threshold.
OFS = 0x1E, //!< Offset (x, y, z).
DUR = 0x21, //!< Tap duration.
LATENT = 0x22, //!< Tap latency.
WINDOW = 0x23, //!< Tap window.
THRESH_ACT = 0x24, //!< Activity threshold.
THRESH_INACT = 0x25, //!< Inactivity threshold.
TIME_INACT = 0x26, //!< Inactivity time.
ACT_INACT_CTL = 0x27, //!< Axis enable control for activity detection.
THRESH_FF = 0x28, //!< Free-fall threshold.
TIME_FF = 0x29, //!< Free-fall time.
TAP_AXES = 0x2A, //!< Axis control for single tap/double tap.
ACT_TAP_STATUS = 0x2B, //!< Source of single tap/double tap.
BW_RATE = 0x2C, //!< Data rate and power mode control.
POWER_CTL = 0x2D, //!< Power-saving features control.
INT_ENABLE = 0x2E, //!< Interrupt enable control.
INT_MAP = 0x2F, //!< Interrupt mapping control.
INT_SOURCE = 0x30, //!< Source of interrupts.
DATA_FORMAT = 0x31, //!< Data format control.
DATA = 0x32, //!< Data (x, y, z).
FIFO_CTL = 0x38, //!< FIFO control.
FIFO_STATUS = 0x39 //!< FIFO status.
} __attribute__((packed));
/** Register DEVID value (345). */
static const uint8_t ID = 0xe5;
/**
* Register ACT_INACT_CTL bitfields.
*/
enum {
ACT_AC_DC = 7, //!< AC/DC coupled activity.
ACT_X_EN = 6, //!< Activity x axis enable.
ACT_Y_EN = 5, //!< Activity x axis enable.
ACT_Z_EN = 4, //!< Activity x axis enable.
INACT_AC_DC = 3, //!< AC/DC coupled inactivity.
INACT_X_EN = 2, //!< Inactivity x axis enable.
INACT_Y_EN = 1, //!< Inactivity x axis enable.
INACT_Z_EN = 0 //!< Inactivity x axis enable.
} __attribute__((packed));
/**
* Register TAP_AXES bitfields.
*/
enum {
SUPPRES = 3, //!< Suppress.
TAP_X_EN = 2, //!< Tap x enable.
TAP_Y_EN = 1, //!< Tap y enable.
TAP_Z_EN = 0, //!< Tap z enable.
} __attribute__((packed));
/**
* Register ACT_TAP_STATUS bitfields.
*/
enum {
ACT_X_SRC = 6, //!< Activity x event.
ACT_Y_SRC = 5, //!< Activity y event.
ACT_Z_SRC = 4, //!< Activity z event.
ASLEEP = 3, //!< Device is asleep.
TAP_X_SRC = 2, //!< Tap x event.
TAP_Y_SRC = 1, //!< Tap y event.
TAP_Z_SRC = 0 //!< Tap z event.
} __attribute__((packed));
/**
* Register BW_RATE bitfields.
*/
enum {
LOW_POWER = 4, //!< Low power move.
RATE = 0, //!< Data rate (4 bits).
RATE_MASK = 0x0f //!< Data rate mask.
} __attribute__((packed));
/**
* Register POWER_CTL bitfields.
*/
enum {
LINK = 5, //!< Link mode select.
AUTO_SLEEP = 4, //!< Auto sleep enable.
MEASURE = 3, //!< Measurement mode.
SLEEP = 2, //!< Sleep mode.
WAKEUP = 0, //!< Wakeup frequency (2 bits).
} __attribute__((packed));
enum {
WAKEUP_8_HZ = 0, //!< 8 hz.
WAKEUP_4_HZ = 1, //!< 4 hz.
WAKEUP_2_HZ = 2, //!< 2 hz.
WAKEUP_1_HZ = 3, //!< 1 hz.
WAKEUP_MASK = 3 //!< Wakeup frequency mask.
};
/**
* Register INT_ENABLE/INT_MAP/INT_SOURCE bitfields.
*/
enum {
DATA_READY = 7, //!< Data ready interrupt enable/map/source.
SINGLE_TAP = 6, //!< Single tap.
DOUBLE_TAP = 5, //!< Double tap.
ACT = 4, //!< Activity.
INACT = 3, //!< Inactivity.
FREE_FALL = 2, //!< Free fall.
WATERMARK = 1, //!< Watermark.
OVERRUN = 0 //!< Overrun interrupt enable/map/source.
} __attribute__((packed));
/**
* Register DATA_FORMAT bitfields.
*/
enum {
SELF_TEST = 7, //!< Self-test force.
SPI_WIRE_MODE = 6, //!< SPI wire mode.
INT_INVERT = 5, //!< Interrupt active high/low.
FULL_RES = 3, //!< Full resolution.
JUSTIFY = 2, //!< Left justified/sign extend.
RANGE = 0 //!< Range 2-16 g (2 bits).
} __attribute__((packed));
enum {
RANGE_2G = 0, //!< +-2g.
RANGE_4G = 1, //!< +-4g.
RANGE_8G = 2, //!< +-8g.
RANGE_16G = 3, //!< +-16g.
RANGE_MASK = 3 //!< Mask range field.
} __attribute__((packed));
/**
* Register FIFO_CTL bitfields.
*/
enum {
FIFO_MODE = 6, //!< FIFO Mode.
FIFO_MASK = 0xc0, //!< Dito Mask.
TRIG = 5, //!< Trigger event to interrupt pin.
SAMPLES = 0, //!< Number of samples (5 bits).
SAMPLES_MASK = 0x1f //!< Dito Mask.
} __attribute__((packed));
enum {
BYPASS = 0x00, //!< FIFO is bypassed.
FIFO = 0x40, //!< Collects up to 32 values.
STREAM = 0x80, //!< Holds the latest 32 values.
TRIGGER = 0xc0 //!< Latest 32 values before trigger.
};
/**
* Register FIFO_STATUS bitfields.
*/
enum {
FIFO_TRIG = 7, //!< FIFO trigger event occuring.
ENTRIES = 0, //!< Number of entries in FIFO (6 bits).
ENTRIES_MASK = 0x3f //!< Dito Mask.
} __attribute__((packed));
/**
* Write given value to register.
* @param[in] reg register address.
* @param[in] value register value.
*/
void write(Register reg, uint8_t value);
/**
* Write multiple registers with values from give address.
* @param[in] reg register address.
* @param[in] buffer storage.
* @param[in] count number of bytes.
*/
void write(Register reg, void* buffer, uint8_t count);
/**
* Read contents of register.
* @param[in] reg register address.
* @return register value.
*/
uint8_t read(Register reg)
{
uint8_t res;
read(reg, &res, sizeof(res));
return (res);
}
/**
* Read contents of registers, multiple values from give address.
* @param[in] reg register address.
* @param[in] buffer storage.
* @param[in] count number of bytes.
*/
void read(Register reg, void* buffer, uint8_t count);
/** 3-Axis setting (add or or values). */
enum {
X = 4,
Y = 2,
Z = 1
} __attribute__((packed));
/**
* Construct ADXL345 driver with normal or alternative address (pp. 18).
* @param[in] use_alt_address.
*/
ADXL345(bool use_alt_address = false) :
TWI::Driver(use_alt_address ? 0x53 : 0x1d)
{
}
/**
* Start interaction with device. Set full resolution and 16G.
* Single and double tap detection in XYZ-axis. Activity/inactivity
* (5 seconds), and free fall detect. Power control with auto-sleep
* and wakeup at 2 Hz. Interrupts enabled. Measurement turned on.
* @return true(1) if successful otherwise false(0)
*/
bool begin();
/**
* Stop sequence of interaction with device. Turn off measurement.
* @return true(1) if successful otherwise false(0)
*/
bool end();
/**
* Accelerometer offset calibration structure.
*/
struct offset_t {
int8_t x;
int8_t y;
int8_t z;
};
/**
* Calibrate accelerometer with given offsets.
* @param[in] x axis offset.
* @param[in] y axis offset.
* @param[in] z axis offset.
*/
void calibrate(int8_t x, int8_t y, int8_t z)
{
offset_t ofs;
ofs.x = x;
ofs.y = y;
ofs.z = z;
write(OFS, &ofs, sizeof(ofs));
}
/**
* Calibrate accelerometer by resetting offset and
* using the current accelerometer values as offset.
* (-sample/4) according to ADXL345 documentation.
*/
void calibrate();
/**
* Accelerometer sample data structure (axis x, y, z).
*/
struct sample_t {
int x;
int y;
int z;
};
/**
* Sample accelerometer. Return sample is given data structure
* @param[in] s sample storage.
*/
void sample(sample_t& s) __attribute__((always_inline))
{
read(DATA, &s, sizeof(s));
}
/**
* Check for activity. Returns a bitset with current activity.
* Ignore WATERMARK and OVERRUN.
* @return activities
*/
uint8_t is_activity();
};
/**
* Print the latest reading to the given output stream.
* @param[in] outs output stream.
* @param[in] accelerometer instance.
* @return output stream.
*/
extern IOStream& operator<<(IOStream& outs, ADXL345& accelerometer);
#endif
<|endoftext|> |
<commit_before>/** \file add_isbns_or_issns_to_articles.cc
* \brief A tool for adding missing ISBN's (field 020$a) or ISSN's (field 773$x)to articles entries,
* in MARC-21 data.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2015-2018, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "MARC.h"
#include "MiscUtil.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << progname << " master_marc_input marc_output\n";
std::cerr << " Adds host/parent/journal ISBNs and ISSNs to article entries found in the\n";
std::cerr << " master_marc_input and writes this augmented file as marc_output. The ISBNs and ISSNs are\n";
std::cerr << " extracted from superior entries found in master_marc_input.\n";
std::exit(EXIT_FAILURE);
}
struct RecordInfo {
std::string isbn_or_issn_;
bool is_open_access_;
};
void PopulateParentIdToISBNAndISSNMap(MARC::Reader * const marc_reader,
std::unordered_map<std::string, RecordInfo> * const parent_id_to_isbn_issn_and_open_access_status_map)
{
LOG_INFO("Starting extraction of ISBN's and ISSN's.");
unsigned count(0), extracted_isbn_count(0), extracted_issn_count(0);
std::string err_msg;
while (const MARC::Record record = marc_reader->read()) {
++count;
if (not record.isSerial() and not record.isMonograph())
continue;
// Try to see if we have an ISBN:
const auto field_020(record.findTag("020"));
if (field_020 != record.end()) {
const std::string isbn(field_020->getFirstSubfieldWithCode('a'));
if (not isbn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { isbn, MARC::IsOpenAccess(record) };
++extracted_isbn_count;
continue;
}
} else
continue;
std::string issn;
// 1. First try to get an ISSN from 029$a, (according to the BSZ's PICA-to-MARC mapping
// documentation this contains the "authorised" ISSN) but only if the indicators are correct:
for (const auto &_029_field : record.getTagRange("029")) {
const auto subfields(_029_field.getSubfields());
// We only want fields with indicators 'x' and 'a':
if (_029_field.getIndicator1() != 'x' or _029_field.getIndicator2() != 'a')
continue;
issn = subfields.getFirstSubfieldWithCode('a');
if (not issn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };
++extracted_issn_count;
}
}
// 2. If we don't already have an ISSN check 022$a as a last resort:
if (issn.empty()) {
const auto field_022(record.findTag("022"));
if (field_022 != record.end()) {
issn = field_022->getFirstSubfieldWithCode('a');
if (not issn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };
++extracted_issn_count;
}
}
}
}
if (not err_msg.empty())
LOG_ERROR(err_msg);
LOG_INFO("Read " + std::to_string(count) + " records.");
LOG_INFO("Extracted " + std::to_string(extracted_isbn_count) + " ISBNs.");
LOG_INFO("Extracted " + std::to_string(extracted_issn_count) + " ISSNs.");
}
void AddMissingISBNsOrISSNsToArticleEntries(
MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::unordered_map<std::string, RecordInfo> &parent_id_to_isbn_issn_and_open_access_status_map)
{
LOG_INFO("Starting augmentation of article entries.");
unsigned count(0), isbns_added(0), issns_added(0), missing_host_record_ctrl_num_count(0), missing_isbn_or_issn_count(0);
while (MARC::Record record = marc_reader->read()) {
++count;
if (not record.isArticle()) {
marc_writer->write(record);
continue;
}
const auto _773_field(record.findTag("773"));
if (_773_field == record.end()) {
marc_writer->write(record);
continue;
}
auto subfields(_773_field->getSubfields());
if (subfields.hasSubfield('x')) {
marc_writer->write(record);
continue;
}
if (not subfields.hasSubfield('w')) { // Record control number of Host Item Entry.
marc_writer->write(record);
++missing_host_record_ctrl_num_count;
continue;
}
std::string host_id(subfields.getFirstSubfieldWithCode('w'));
if (StringUtil::StartsWith(host_id, "(DE-576)"))
host_id = host_id.substr(8);
const auto &parent_isbn_or_issn_iter(parent_id_to_isbn_issn_and_open_access_status_map.find(host_id));
if (parent_isbn_or_issn_iter == parent_id_to_isbn_issn_and_open_access_status_map.end()) {
marc_writer->write(record);
++missing_isbn_or_issn_count;
continue;
}
if (MiscUtil::IsPossibleISSN(parent_isbn_or_issn_iter->second.isbn_or_issn_)) {
subfields.addSubfield('x', parent_isbn_or_issn_iter->second.isbn_or_issn_);
_773_field->setSubfields(subfields);
++issns_added;
} else { // Deal with ISBNs.
auto _020_field(record.findTag("020"));
if (_020_field == record.end()) {
record.insertField("020", { { 'a', parent_isbn_or_issn_iter->second.isbn_or_issn_ } });
++isbns_added;
} else if (_020_field->getFirstSubfieldWithCode('a').empty()) {
_020_field->appendSubfield('a', parent_isbn_or_issn_iter->second.isbn_or_issn_);
++isbns_added;
}
}
// If parent is open access and we're not, add it!
if (parent_isbn_or_issn_iter->second.is_open_access_ and not MARC::IsOpenAccess(record))
record.insertField("655", { { 'a', "Open Access" } }, /* indicator1 = */' ', /* indicator2 = */'4');
marc_writer->write(record);
}
LOG_INFO("Read " + std::to_string(count) + " records.");
LOG_INFO("Added ISBN's to " + std::to_string(isbns_added) + " article record(s).");
LOG_INFO("Added ISSN's to " + std::to_string(issns_added) + " article record(s).");
LOG_INFO(std::to_string(missing_host_record_ctrl_num_count) +
" articles had missing host record control number(s).");
LOG_INFO("For " + std::to_string(missing_isbn_or_issn_count) + " articles no host ISBN nor ISSN was found.");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc < 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Master input file name equals output file name!");
auto marc_reader(MARC::Reader::Factory(marc_input_filename));
auto marc_writer(MARC::Writer::Factory(marc_output_filename));
std::unordered_map<std::string, RecordInfo> parent_id_to_isbn_issn_and_open_access_status_map;
PopulateParentIdToISBNAndISSNMap(marc_reader.get(), &parent_id_to_isbn_issn_and_open_access_status_map);
marc_reader->rewind();
AddMissingISBNsOrISSNsToArticleEntries(marc_reader.get(), marc_writer.get(), parent_id_to_isbn_issn_and_open_access_status_map);
return EXIT_SUCCESS;
}
<commit_msg>Handle more valid cases.<commit_after>/** \file add_isbns_or_issns_to_articles.cc
* \brief A tool for adding missing ISBN's (field 020$a) or ISSN's (field 773$x)to articles entries,
* in MARC-21 data.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2015-2018, Library of the University of Tübingen
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 <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "MARC.h"
#include "MiscUtil.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << progname << " master_marc_input marc_output\n";
std::cerr << " Adds host/parent/journal ISBNs and ISSNs to article entries found in the\n";
std::cerr << " master_marc_input and writes this augmented file as marc_output. The ISBNs and ISSNs are\n";
std::cerr << " extracted from superior entries found in master_marc_input.\n";
std::exit(EXIT_FAILURE);
}
struct RecordInfo {
std::string isbn_or_issn_;
bool is_open_access_;
};
void PopulateParentIdToISBNAndISSNMap(MARC::Reader * const marc_reader,
std::unordered_map<std::string, RecordInfo> * const parent_id_to_isbn_issn_and_open_access_status_map)
{
LOG_INFO("Starting extraction of ISBN's and ISSN's.");
unsigned count(0), extracted_isbn_count(0), extracted_issn_count(0);
std::string err_msg;
while (const MARC::Record record = marc_reader->read()) {
++count;
if (not record.isSerial() and not record.isMonograph())
continue;
// Try to see if we have an ISBN:
const auto field_020(record.findTag("020"));
if (field_020 != record.end()) {
const std::string isbn(field_020->getFirstSubfieldWithCode('a'));
if (not isbn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { isbn, MARC::IsOpenAccess(record) };
++extracted_isbn_count;
continue;
}
} else
continue;
std::string issn;
// 1. First try to get an ISSN from 029$a, (according to the BSZ's PICA-to-MARC mapping
// documentation this contains the "authorised" ISSN) but only if the indicators are correct:
for (const auto &_029_field : record.getTagRange("029")) {
const auto subfields(_029_field.getSubfields());
// We only want fields with indicators 'x' and 'a':
if (_029_field.getIndicator1() != 'x' or _029_field.getIndicator2() != 'a')
continue;
issn = subfields.getFirstSubfieldWithCode('a');
if (not issn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };
++extracted_issn_count;
}
}
// 2. If we don't already have an ISSN check 022$a as a last resort:
if (issn.empty()) {
const auto field_022(record.findTag("022"));
if (field_022 != record.end()) {
issn = field_022->getFirstSubfieldWithCode('a');
if (not issn.empty()) {
(*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };
++extracted_issn_count;
}
}
}
}
if (not err_msg.empty())
LOG_ERROR(err_msg);
LOG_INFO("Read " + std::to_string(count) + " records.");
LOG_INFO("Extracted " + std::to_string(extracted_isbn_count) + " ISBNs.");
LOG_INFO("Extracted " + std::to_string(extracted_issn_count) + " ISSNs.");
}
void AddMissingISBNsOrISSNsToArticleEntries(
MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
const std::unordered_map<std::string, RecordInfo> &parent_id_to_isbn_issn_and_open_access_status_map)
{
LOG_INFO("Starting augmentation of article entries.");
unsigned count(0), isbns_added(0), issns_added(0), missing_host_record_ctrl_num_count(0), missing_isbn_or_issn_count(0);
while (MARC::Record record = marc_reader->read()) {
++count;
if (not record.isArticle()) {
marc_writer->write(record);
continue;
}
const auto _773_field(record.findTag("773"));
if (_773_field == record.end()) {
marc_writer->write(record);
continue;
}
auto subfields(_773_field->getSubfields());
if (not subfields.hasSubfield('w')) { // Record control number of Host Item Entry.
marc_writer->write(record);
++missing_host_record_ctrl_num_count;
continue;
}
std::string host_id(subfields.getFirstSubfieldWithCode('w'));
if (StringUtil::StartsWith(host_id, "(DE-576)"))
host_id = host_id.substr(8);
const auto parent_isbn_or_issn_iter(parent_id_to_isbn_issn_and_open_access_status_map.find(host_id));
if (parent_isbn_or_issn_iter == parent_id_to_isbn_issn_and_open_access_status_map.end()) {
marc_writer->write(record);
++missing_isbn_or_issn_count;
continue;
}
// If parent is open access and we're not, add it!
if (parent_isbn_or_issn_iter->second.is_open_access_ and not MARC::IsOpenAccess(record))
record.insertField("655", { { 'a', "Open Access" } }, /* indicator1 = */' ', /* indicator2 = */'4');
if (subfields.hasSubfield('x')) {
marc_writer->write(record);
continue;
}
if (MiscUtil::IsPossibleISSN(parent_isbn_or_issn_iter->second.isbn_or_issn_)) {
subfields.addSubfield('x', parent_isbn_or_issn_iter->second.isbn_or_issn_);
_773_field->setSubfields(subfields);
++issns_added;
} else { // Deal with ISBNs.
auto _020_field(record.findTag("020"));
if (_020_field == record.end()) {
record.insertField("020", { { 'a', parent_isbn_or_issn_iter->second.isbn_or_issn_ } });
++isbns_added;
} else if (_020_field->getFirstSubfieldWithCode('a').empty()) {
_020_field->appendSubfield('a', parent_isbn_or_issn_iter->second.isbn_or_issn_);
++isbns_added;
}
}
marc_writer->write(record);
}
LOG_INFO("Read " + std::to_string(count) + " records.");
LOG_INFO("Added ISBN's to " + std::to_string(isbns_added) + " article record(s).");
LOG_INFO("Added ISSN's to " + std::to_string(issns_added) + " article record(s).");
LOG_INFO(std::to_string(missing_host_record_ctrl_num_count) + " articles had missing host record control number(s).");
LOG_INFO("For " + std::to_string(missing_isbn_or_issn_count) + " articles no host ISBN nor ISSN was found.");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc < 3)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string marc_output_filename(argv[2]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Master input file name equals output file name!");
auto marc_reader(MARC::Reader::Factory(marc_input_filename));
auto marc_writer(MARC::Writer::Factory(marc_output_filename));
std::unordered_map<std::string, RecordInfo> parent_id_to_isbn_issn_and_open_access_status_map;
PopulateParentIdToISBNAndISSNMap(marc_reader.get(), &parent_id_to_isbn_issn_and_open_access_status_map);
marc_reader->rewind();
AddMissingISBNsOrISSNsToArticleEntries(marc_reader.get(), marc_writer.get(), parent_id_to_isbn_issn_and_open_access_status_map);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/// HEADER
#include "set_operation.h"
/// PROJECT
#include <csapex_vision/cv_mat_message.h>
#include <csapex/model/connector_in.h>
#include <csapex/model/connector_out.h>
#include <utils_param/parameter_factory.h>
/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#include <QComboBox>
#include <boost/assign/std.hpp>
using namespace vision_plugins;
using namespace csapex;
using namespace connection_types;
CSAPEX_REGISTER_CLASS(vision_plugins::SetOperation, csapex::Node)
using namespace boost::assign;
SetOperation::SetOperation()
{
addTag(Tag::get("Vision"));
std::map<std::string, int> methods = map_list_of
("Complement", (int) COMPLEMENT)
("Intersection", (int) INTERSECTION)
("Union", (int) UNION);
addParameter(param::ParameterFactory::declareParameterSet("operation", methods));
}
void SetOperation::process()
{
CvMatMessage::Ptr img1 = i1_->getMessage<CvMatMessage>();
if(img1->getEncoding() != enc::mono) {
throw std::runtime_error("No Single Channel!");
}
CvMatMessage::Ptr out(new CvMatMessage(img1->getEncoding()));
int op = param<int>("operation");
if(op == COMPLEMENT) {
out->value = ~img1->value;
} else {
if(!i2_->isConnected() || !i2_->hasMessage()) {
return;
}
CvMatMessage::Ptr img2 = i2_->getMessage<CvMatMessage>();
if(img1->value.rows != img2->value.rows || img1->value.cols != img2->value.cols) {
throw std::runtime_error("Dimension is not matching!");
}
if(op == INTERSECTION) {
out->value = img1->value & img2->value;
} else if(op == UNION) {
out->value = img1->value | img2->value;
}
}
if(out->value.rows != 0 && out->value.cols != 0) {
out_->publish(out);
}
}
void SetOperation::setup()
{
setSynchronizedInputs(true);
i1_ = addInput<CvMatMessage>("Mask 1");
i2_ = addInput<CvMatMessage>("Mask 2", true);
out_ = addOutput<CvMatMessage>("Combined");
}
<commit_msg>unnecessary<commit_after>/// HEADER
#include "set_operation.h"
/// PROJECT
#include <csapex_vision/cv_mat_message.h>
#include <csapex/model/connector_in.h>
#include <csapex/model/connector_out.h>
#include <utils_param/parameter_factory.h>
/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
#include <boost/assign/std.hpp>
using namespace vision_plugins;
using namespace csapex;
using namespace connection_types;
CSAPEX_REGISTER_CLASS(vision_plugins::SetOperation, csapex::Node)
using namespace boost::assign;
SetOperation::SetOperation()
{
addTag(Tag::get("Vision"));
std::map<std::string, int> methods = map_list_of
("Complement", (int) COMPLEMENT)
("Intersection", (int) INTERSECTION)
("Union", (int) UNION);
addParameter(param::ParameterFactory::declareParameterSet("operation", methods));
}
void SetOperation::process()
{
CvMatMessage::Ptr img1 = i1_->getMessage<CvMatMessage>();
if(img1->getEncoding() != enc::mono) {
throw std::runtime_error("No Single Channel!");
}
CvMatMessage::Ptr out(new CvMatMessage(img1->getEncoding()));
int op = param<int>("operation");
if(op == COMPLEMENT) {
out->value = ~img1->value;
} else {
if(!i2_->isConnected() || !i2_->hasMessage()) {
return;
}
CvMatMessage::Ptr img2 = i2_->getMessage<CvMatMessage>();
if(img1->value.rows != img2->value.rows || img1->value.cols != img2->value.cols) {
throw std::runtime_error("Dimension is not matching!");
}
if(op == INTERSECTION) {
out->value = img1->value & img2->value;
} else if(op == UNION) {
out->value = img1->value | img2->value;
}
}
if(out->value.rows != 0 && out->value.cols != 0) {
out_->publish(out);
}
}
void SetOperation::setup()
{
setSynchronizedInputs(true);
i1_ = addInput<CvMatMessage>("Mask 1");
i2_ = addInput<CvMatMessage>("Mask 2", true);
out_ = addOutput<CvMatMessage>("Combined");
}
<|endoftext|> |
<commit_before>#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <functional>
#include <Windows.h>
#include <Console\Console.hpp>
#include "Osiris.hpp"
int32_t __stdcall StructuredExceptionPrinter(
uint32_t ErrorCode,
const EXCEPTION_POINTERS* const ExceptionInfo
);
uint32_t __stdcall OsirisThread(void*)
{
__try
{
[]()
{
std::chrono::high_resolution_clock::time_point PrevTime, CurTime;
CurTime = std::chrono::high_resolution_clock::now();
while( true )
{
PrevTime = CurTime;
CurTime = std::chrono::high_resolution_clock::now();
Osiris::Instance()->Tick(
(CurTime - PrevTime)
);
}
}();
}
__except( StructuredExceptionPrinter(GetExceptionCode(), GetExceptionInformation()) )
{
}
return 0;
}
int32_t __stdcall DllMain(HINSTANCE hDLL, uint32_t Reason, void *Reserved)
{
switch( Reason )
{
case DLL_PROCESS_ATTACH:
{
if( !DisableThreadLibraryCalls(hDLL) )
{
MessageBox(nullptr, "Unable to disable thread library calls", "Osiris", MB_OK);
return false;
}
CreateThread(
nullptr,
0,
reinterpret_cast<unsigned long(__stdcall*)(void*)>(&OsirisThread),
nullptr,
0,
nullptr);
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
{
return true;
}
}
return false;
}
int32_t __stdcall StructuredExceptionPrinter(uint32_t ErrorCode, const EXCEPTION_POINTERS* const ExceptionInfo)
{
std::cout << std::endl << "Exception: [0x" << std::uppercase << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << ']';
std::stringstream ErrorMessage;
ErrorMessage << std::hex << std::setfill('0');
switch( ErrorCode )
{
default:
{
ErrorMessage << "Unknown";
break;
}
case EXCEPTION_ACCESS_VIOLATION:
{
ErrorMessage << "EXCEPTION_ACCESS_VIOLATION [";
const char* const MemOperation[2] = { "Reading","Writing" };
ErrorMessage << MemOperation[ExceptionInfo->ExceptionRecord->ExceptionInformation[0] & 1];
ErrorMessage << " to 0x"
<< std::uppercase << std::setw(sizeof(uintptr_t) << 1)
<< ExceptionInfo->ExceptionRecord->ExceptionInformation[1] << ']';
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
ErrorMessage << "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
break;
}
case EXCEPTION_BREAKPOINT:
{
ErrorMessage << "EXCEPTION_BREAKPOINT";
break;
}
case EXCEPTION_DATATYPE_MISALIGNMENT:
{
ErrorMessage << "EXCEPTION_DATATYPE_MISALIGNMENT";
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
ErrorMessage << "EXCEPTION_FLT_DENORMAL_OPERAND";
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_FLT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_FLT_INEXACT_RESULT:
{
ErrorMessage << "EXCEPTION_FLT_INEXACT_RESULT";
break;
}
case EXCEPTION_FLT_INVALID_OPERATION:
{
ErrorMessage << "EXCEPTION_FLT_INVALID_OPERATION";
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_OVERFLOW";
break;
}
case EXCEPTION_FLT_STACK_CHECK:
{
ErrorMessage << "EXCEPTION_FLT_STACK_CHECK";
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
ErrorMessage << "EXCEPTION_FLT_UNDERFLOW";
break;
}
case EXCEPTION_ILLEGAL_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_ILLEGAL_INSTRUCTION";
break;
}
case EXCEPTION_IN_PAGE_ERROR:
{
ErrorMessage << "EXCEPTION_IN_PAGE_ERROR";
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
ErrorMessage << "EXCEPTION_INT_DIVIDE_BY_ZERO";
break;
}
case EXCEPTION_INT_OVERFLOW:
{
ErrorMessage << "EXCEPTION_INT_OVERFLOW";
break;
}
case EXCEPTION_INVALID_DISPOSITION:
{
ErrorMessage << "EXCEPTION_INVALID_DISPOSITION";
break;
}
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
{
ErrorMessage << "EXCEPTION_NONCONTINUABLE_EXCEPTION";
break;
}
case EXCEPTION_PRIV_INSTRUCTION:
{
ErrorMessage << "EXCEPTION_PRIV_INSTRUCTION";
break;
}
case EXCEPTION_SINGLE_STEP:
{
ErrorMessage << "EXCEPTION_SINGLE_STEP";
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
ErrorMessage << "EXCEPTION_STACK_OVERFLOW";
break;
}
}
// Format exception string
std::cout << std::nouppercase << " - " << ErrorMessage.str() << std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}<commit_msg>Removed Top-Level exception handler<commit_after>#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <Windows.h>
#include "Osiris.hpp"
uint32_t __stdcall OsirisThread(void*)
{
std::chrono::high_resolution_clock::time_point PrevTime, CurTime;
CurTime = std::chrono::high_resolution_clock::now();
while( true )
{
PrevTime = CurTime;
CurTime = std::chrono::high_resolution_clock::now();
Osiris::Instance()->Tick(
(CurTime - PrevTime)
);
}
return 0;
}
int32_t __stdcall DllMain(HINSTANCE hDLL, uint32_t Reason, void *Reserved)
{
switch( Reason )
{
case DLL_PROCESS_ATTACH:
{
if( !DisableThreadLibraryCalls(hDLL) )
{
MessageBox(nullptr, "Unable to disable thread library calls", "Osiris", MB_OK);
return false;
}
CreateThread(
nullptr,
0,
reinterpret_cast<unsigned long(__stdcall*)(void*)>(&OsirisThread),
nullptr,
0,
nullptr);
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
{
return true;
}
}
return false;
}<|endoftext|> |
<commit_before>//
// EmiCongestionControl.cpp
// rock
//
// Created by Per Eckerdal on 2012-05-24.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include "EmiCongestionControl.h"
#include "EmiPacketHeader.h"
#include "EmiNetUtil.h"
#include <algorithm>
#include <cmath>
void EmiCongestionControl::onAck(EmiTimeInterval rtt) {
if (0 == _sendingRate) {
// We're in the slow start phase
_congestionWindow = _totalDataSentInSlowStart;
_congestionWindow = std::max(EMI_MIN_CONGESTION_WINDOW, _congestionWindow);
_congestionWindow = std::min(EMI_MAX_CONGESTION_WINDOW, _congestionWindow);
}
else {
// We're not in the slow start phase
float inc = 1;
if (_remoteLinkCapacity > _sendingRate) {
static const double BETA = 0.0000015;
inc = std::max(std::pow(10, std::ceil(std::log10((_remoteLinkCapacity-_sendingRate)*8))) * BETA,
1.0);
}
_sendingRate = (_sendingRate*inc + EMI_TICK_TIME) / (_sendingRate * EMI_TICK_TIME);
_congestionWindow = _remoteDataArrivalRate * (rtt + EMI_TICK_TIME) + EMI_MIN_CONGESTION_WINDOW;
}
}
void EmiCongestionControl::onNak(EmiPacketSequenceNumber nak,
EmiPacketSequenceNumber largestSNSoFar) {
if (0 == _sendingRate) {
// We're in the slow start phase.
if (-1 == _remoteLinkCapacity ||
-1 == _remoteDataArrivalRate) {
// We got a NAK, but we have not yet received
// data about the link capacity and the arrival
// rate. Ignore this packet.
return;
}
// End the slow start phase
_sendingRate = _remoteDataArrivalRate;
}
else {
// We're not in the slow start phase
static const float SENDING_RATE_DECREASE = 1.125;
if (nak > _lastDecSeq) {
// This NAK starts a new congestion period
_sendingRate /= SENDING_RATE_DECREASE;
static const float SMOOTH = 0.125;
_avgNakCount = (1-SMOOTH)*_avgNakCount + SMOOTH*_nakCount;
_nakCount = 1;
_decRandom = (arc4random() % (((int)std::floor(_avgNakCount))+1)) + 1;
_decCount = 1;
_lastDecSeq = largestSNSoFar;
}
else {
// This NAK does not start a new congestion period
if (_decCount <= 5 && _nakCount == _decCount*_decRandom) {
// The _decCount <= 5 ensures that the sending rate is not
// decreased by more than 50% per congestion period (1.125^6≈2)
_sendingRate /= SENDING_RATE_DECREASE;
_decCount++;
_lastDecSeq = largestSNSoFar;
}
_nakCount++;
}
}
}
EmiCongestionControl::EmiCongestionControl() :
_congestionWindow(EMI_MIN_CONGESTION_WINDOW),
_sendingRate(0),
_totalDataSentInSlowStart(0),
_linkCapacity(),
_dataArrivalRate(),
_avgNakCount(1),
_nakCount(1),
_decRandom(2),
_decCount(1),
_lastDecSeq(-1),
_newestSeenSequenceNumber(-1),
_newestSentSequenceNumber(-1),
_remoteLinkCapacity(-1),
_remoteDataArrivalRate(-1) {}
EmiCongestionControl::~EmiCongestionControl() {}
void EmiCongestionControl::gotPacket(EmiTimeInterval now, EmiTimeInterval rtt,
EmiPacketSequenceNumber largestSNSoFar,
const EmiPacketHeader& packetHeader, size_t packetLength) {
static const float SMOOTH = 0.125;
_linkCapacity.gotPacket(now, packetHeader.sequenceNumber, packetLength);
_dataArrivalRate.gotPacket(now, packetLength);
if (packetHeader.flags & EMI_LINK_CAPACITY_PACKET_FLAG &&
// Make sure we don't save bogus data
packetHeader.linkCapacity > 0) {
if (-1 == _remoteLinkCapacity) {
_remoteLinkCapacity = packetHeader.linkCapacity;
}
else {
_remoteLinkCapacity = (1-SMOOTH)*_remoteLinkCapacity + SMOOTH*packetHeader.linkCapacity;
}
}
if (packetHeader.flags & EMI_ARRIVAL_RATE_PACKET_FLAG &&
// Make sure we don't save bogus data
packetHeader.arrivalRate > 0) {
if (-1 == _remoteDataArrivalRate) {
_remoteDataArrivalRate = packetHeader.arrivalRate;
}
else {
_remoteDataArrivalRate = (1-SMOOTH)*_remoteDataArrivalRate + SMOOTH*packetHeader.arrivalRate;
}
}
if (packetHeader.flags & EMI_ACK_PACKET_FLAG) {
onAck(rtt);
}
if (packetHeader.flags & EMI_NAK_PACKET_FLAG) {
onNak(packetHeader.nak, largestSNSoFar);
}
if (-1 == _newestSeenSequenceNumber ||
EmiNetUtil::cyclicDifference24Signed(packetHeader.sequenceNumber, _newestSeenSequenceNumber) > 0) {
_newestSeenSequenceNumber = packetHeader.sequenceNumber;
}
}
void EmiCongestionControl::onRto() {
_sendingRate /= 2;
}
void EmiCongestionControl::onDataSent(size_t size) {
if (0 == _sendingRate) {
// We're in slow start mode
_totalDataSentInSlowStart += size;
}
}
EmiPacketSequenceNumber EmiCongestionControl::ack() {
if (_newestSeenSequenceNumber == _newestSentSequenceNumber) {
return -1;
}
_newestSentSequenceNumber = _newestSeenSequenceNumber;
return _newestSeenSequenceNumber;
}
<commit_msg>The _sendingRate increase formula in EmiCongestionControl now makes sense<commit_after>//
// EmiCongestionControl.cpp
// rock
//
// Created by Per Eckerdal on 2012-05-24.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include "EmiCongestionControl.h"
#include "EmiPacketHeader.h"
#include "EmiNetUtil.h"
#include <algorithm>
#include <cmath>
void EmiCongestionControl::onAck(EmiTimeInterval rtt) {
if (0 == _sendingRate) {
// We're in the slow start phase
_congestionWindow = _totalDataSentInSlowStart;
_congestionWindow = std::max(EMI_MIN_CONGESTION_WINDOW, _congestionWindow);
_congestionWindow = std::min(EMI_MAX_CONGESTION_WINDOW, _congestionWindow);
}
else {
// We're not in the slow start phase
float inc = 1;
if (_remoteLinkCapacity > _sendingRate) {
// These are constants as specified by UDT. I have no
// idea of why they have this particular value.
static const double ALPHA = 8;
static const double BETA = 0.0000015;
inc = std::max(std::pow(10, std::ceil(std::log10((_remoteLinkCapacity-_sendingRate)*ALPHA))) * BETA,
1.0);
}
_sendingRate += inc/EMI_TICK_TIME;
_congestionWindow = _remoteDataArrivalRate * (rtt + EMI_TICK_TIME) + EMI_MIN_CONGESTION_WINDOW;
}
}
void EmiCongestionControl::onNak(EmiPacketSequenceNumber nak,
EmiPacketSequenceNumber largestSNSoFar) {
if (0 == _sendingRate) {
// We're in the slow start phase.
if (-1 == _remoteLinkCapacity ||
-1 == _remoteDataArrivalRate) {
// We got a NAK, but we have not yet received
// data about the link capacity and the arrival
// rate. Ignore this packet.
return;
}
// End the slow start phase
_sendingRate = _remoteDataArrivalRate;
}
else {
// We're not in the slow start phase
static const float SENDING_RATE_DECREASE = 1.125;
if (nak > _lastDecSeq) {
// This NAK starts a new congestion period
_sendingRate /= SENDING_RATE_DECREASE;
static const float SMOOTH = 0.125;
_avgNakCount = (1-SMOOTH)*_avgNakCount + SMOOTH*_nakCount;
_nakCount = 1;
_decRandom = (arc4random() % (((int)std::floor(_avgNakCount))+1)) + 1;
_decCount = 1;
_lastDecSeq = largestSNSoFar;
}
else {
// This NAK does not start a new congestion period
if (_decCount <= 5 && _nakCount == _decCount*_decRandom) {
// The _decCount <= 5 ensures that the sending rate is not
// decreased by more than 50% per congestion period (1.125^6≈2)
_sendingRate /= SENDING_RATE_DECREASE;
_decCount++;
_lastDecSeq = largestSNSoFar;
}
_nakCount++;
}
}
}
EmiCongestionControl::EmiCongestionControl() :
_congestionWindow(EMI_MIN_CONGESTION_WINDOW),
_sendingRate(0),
_totalDataSentInSlowStart(0),
_linkCapacity(),
_dataArrivalRate(),
_avgNakCount(1),
_nakCount(1),
_decRandom(2),
_decCount(1),
_lastDecSeq(-1),
_newestSeenSequenceNumber(-1),
_newestSentSequenceNumber(-1),
_remoteLinkCapacity(-1),
_remoteDataArrivalRate(-1) {}
EmiCongestionControl::~EmiCongestionControl() {}
void EmiCongestionControl::gotPacket(EmiTimeInterval now, EmiTimeInterval rtt,
EmiPacketSequenceNumber largestSNSoFar,
const EmiPacketHeader& packetHeader, size_t packetLength) {
static const float SMOOTH = 0.125;
_linkCapacity.gotPacket(now, packetHeader.sequenceNumber, packetLength);
_dataArrivalRate.gotPacket(now, packetLength);
if (packetHeader.flags & EMI_LINK_CAPACITY_PACKET_FLAG &&
// Make sure we don't save bogus data
packetHeader.linkCapacity > 0) {
if (-1 == _remoteLinkCapacity) {
_remoteLinkCapacity = packetHeader.linkCapacity;
}
else {
_remoteLinkCapacity = (1-SMOOTH)*_remoteLinkCapacity + SMOOTH*packetHeader.linkCapacity;
}
}
if (packetHeader.flags & EMI_ARRIVAL_RATE_PACKET_FLAG &&
// Make sure we don't save bogus data
packetHeader.arrivalRate > 0) {
if (-1 == _remoteDataArrivalRate) {
_remoteDataArrivalRate = packetHeader.arrivalRate;
}
else {
_remoteDataArrivalRate = (1-SMOOTH)*_remoteDataArrivalRate + SMOOTH*packetHeader.arrivalRate;
}
}
if (packetHeader.flags & EMI_ACK_PACKET_FLAG) {
onAck(rtt);
}
if (packetHeader.flags & EMI_NAK_PACKET_FLAG) {
onNak(packetHeader.nak, largestSNSoFar);
}
if (-1 == _newestSeenSequenceNumber ||
EmiNetUtil::cyclicDifference24Signed(packetHeader.sequenceNumber, _newestSeenSequenceNumber) > 0) {
_newestSeenSequenceNumber = packetHeader.sequenceNumber;
}
}
void EmiCongestionControl::onRto() {
_sendingRate /= 2;
}
void EmiCongestionControl::onDataSent(size_t size) {
if (0 == _sendingRate) {
// We're in slow start mode
_totalDataSentInSlowStart += size;
}
}
EmiPacketSequenceNumber EmiCongestionControl::ack() {
if (_newestSeenSequenceNumber == _newestSentSequenceNumber) {
return -1;
}
_newestSentSequenceNumber = _newestSeenSequenceNumber;
return _newestSeenSequenceNumber;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBicubicImageFilter.h"
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkCanvas.h"
#include "SkColorFilterImageFilter.h"
#include "SkColorMatrixFilter.h"
#include "SkDeviceImageFilterProxy.h"
#include "SkDisplacementMapEffect.h"
#include "SkDropShadowImageFilter.h"
#include "SkLightingImageFilter.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkRect.h"
#include "SkTileImageFilter.h"
#include "SkXfermodeImageFilter.h"
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#include "SkGpuDevice.h"
#endif
static const int kBitmapSize = 4;
static void make_small_bitmap(SkBitmap& bitmap) {
bitmap.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
bitmap.allocPixels();
SkBitmapDevice device(bitmap);
SkCanvas canvas(&device);
canvas.clear(0x00000000);
SkPaint darkPaint;
darkPaint.setColor(0xFF804020);
SkPaint lightPaint;
lightPaint.setColor(0xFF244484);
const int i = kBitmapSize / 4;
for (int y = 0; y < kBitmapSize; y += i) {
for (int x = 0; x < kBitmapSize; x += i) {
canvas.save();
canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
canvas.drawRect(SkRect::MakeXYWH(0, 0,
SkIntToScalar(i),
SkIntToScalar(i)), darkPaint);
canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
0,
SkIntToScalar(i),
SkIntToScalar(i)), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(0,
SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i)), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i)), darkPaint);
canvas.restore();
}
}
}
static SkImageFilter* make_scale(float amount, SkImageFilter* input = NULL) {
SkScalar s = amount;
SkScalar matrix[20] = { s, 0, 0, 0, 0,
0, s, 0, 0, 0,
0, 0, s, 0, 0,
0, 0, 0, s, 0 };
SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
return SkColorFilterImageFilter::Create(filter, input);
}
static SkImageFilter* make_grayscale(SkImageFilter* input = NULL, const SkImageFilter::CropRect* cropRect = NULL) {
SkScalar matrix[20];
memset(matrix, 0, 20 * sizeof(SkScalar));
matrix[0] = matrix[5] = matrix[10] = 0.2126f;
matrix[1] = matrix[6] = matrix[11] = 0.7152f;
matrix[2] = matrix[7] = matrix[12] = 0.0722f;
matrix[18] = 1.0f;
SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
return SkColorFilterImageFilter::Create(filter, input, cropRect);
}
DEF_TEST(ImageFilter, reporter) {
{
// Check that two non-clipping color matrices concatenate into a single filter.
SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f));
SkAutoTUnref<SkImageFilter> quarterBrightness(make_scale(0.5f, halfBrightness));
REPORTER_ASSERT(reporter, NULL == quarterBrightness->getInput(0));
}
{
// Check that a clipping color matrix followed by a grayscale does not concatenate into a single filter.
SkAutoTUnref<SkImageFilter> doubleBrightness(make_scale(2.0f));
SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f, doubleBrightness));
REPORTER_ASSERT(reporter, NULL != halfBrightness->getInput(0));
}
{
// Check that a color filter image filter without a crop rect can be
// expressed as a color filter.
SkAutoTUnref<SkImageFilter> gray(make_grayscale());
REPORTER_ASSERT(reporter, true == gray->asColorFilter(NULL));
}
{
// Check that a color filter image filter with a crop rect cannot
// be expressed as a color filter.
SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(0, 0, 100, 100));
SkAutoTUnref<SkImageFilter> grayWithCrop(make_grayscale(NULL, &cropRect));
REPORTER_ASSERT(reporter, false == grayWithCrop->asColorFilter(NULL));
}
{
// Tests pass by not asserting
SkBitmap bitmap, result;
make_small_bitmap(bitmap);
result.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
result.allocPixels();
{
// This tests for :
// 1 ) location at (0,0,1)
SkPoint3 location(0, 0, SK_Scalar1);
// 2 ) location and target at same value
SkPoint3 target(location.fX, location.fY, location.fZ);
// 3 ) large negative specular exponent value
SkScalar specularExponent = -1000;
SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
SkPaint paint;
paint.setImageFilter(SkLightingImageFilter::CreateSpotLitSpecular(
location, target, specularExponent, 180,
0xFFFFFFFF, SK_Scalar1, SK_Scalar1, SK_Scalar1,
bmSrc))->unref();
SkCanvas canvas(result);
SkRect r = SkRect::MakeWH(SkIntToScalar(kBitmapSize),
SkIntToScalar(kBitmapSize));
canvas.drawRect(r, paint);
}
{
// This tests for scale bringing width to 0
SkSize scale = SkSize::Make(-0.001f, SK_Scalar1);
SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
SkAutoTUnref<SkBicubicImageFilter> bicubic(
SkBicubicImageFilter::CreateMitchell(scale, bmSrc));
SkBitmapDevice device(bitmap);
SkDeviceImageFilterProxy proxy(&device);
SkIPoint loc = SkIPoint::Make(0, 0);
// An empty input should early return and return false
REPORTER_ASSERT(reporter,
!bicubic->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &loc));
}
}
}
static void test_crop_rects(SkBaseDevice* device, skiatest::Reporter* reporter) {
// Check that all filters offset to their absolute crop rect,
// unaffected by the input crop rect.
// Tests pass by not asserting.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
bitmap.allocPixels();
bitmap.eraseARGB(0, 0, 0, 0);
SkDeviceImageFilterProxy proxy(device);
SkImageFilter::CropRect inputCropRect(SkRect::MakeXYWH(8, 13, 80, 80));
SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(20, 30, 60, 60));
SkAutoTUnref<SkImageFilter> input(make_grayscale(NULL, &inputCropRect));
SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED, SkXfermode::kSrcIn_Mode));
SkPoint3 location(0, 0, SK_Scalar1);
SkPoint3 target(SK_Scalar1, SK_Scalar1, SK_Scalar1);
SkScalar kernel[9] = {
SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1),
SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
};
SkISize kernelSize = SkISize::Make(3, 3);
SkScalar gain = SK_Scalar1, bias = 0;
SkImageFilter* filters[] = {
SkColorFilterImageFilter::Create(cf.get(), input.get(), &cropRect),
new SkDisplacementMapEffect(SkDisplacementMapEffect::kR_ChannelSelectorType,
SkDisplacementMapEffect::kB_ChannelSelectorType,
40.0f, input.get(), input.get(), &cropRect),
new SkBlurImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkDropShadowImageFilter(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_ColorGREEN, input.get(), &cropRect),
SkLightingImageFilter::CreatePointLitDiffuse(location, SK_ColorGREEN, 0, 0, input.get(), &cropRect),
SkLightingImageFilter::CreatePointLitSpecular(location, SK_ColorGREEN, 0, 0, 0, input.get(), &cropRect),
new SkMatrixConvolutionImageFilter(kernelSize, kernel, gain, bias, SkIPoint::Make(1, 1), SkMatrixConvolutionImageFilter::kRepeat_TileMode, false, input.get(), &cropRect),
new SkMergeImageFilter(input.get(), input.get(), SkXfermode::kSrcOver_Mode, &cropRect),
new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkDilateImageFilter(3, 2, input.get(), &cropRect),
new SkErodeImageFilter(2, 3, input.get(), &cropRect),
new SkTileImageFilter(inputCropRect.rect(), cropRect.rect(), input.get()),
new SkXfermodeImageFilter(SkXfermode::Create(SkXfermode::kSrcOver_Mode), input.get(), input.get(), &cropRect),
};
for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
SkImageFilter* filter = filters[i];
SkBitmap result;
SkIPoint offset;
SkString str;
str.printf("filter %ld", i);
REPORTER_ASSERT_MESSAGE(reporter, filter->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &offset), str.c_str());
REPORTER_ASSERT_MESSAGE(reporter, offset.fX == 20 && offset.fY == 30, str.c_str());
}
for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
SkSafeUnref(filters[i]);
}
}
DEF_TEST(ImageFilterCropRect, reporter) {
SkBitmap temp;
temp.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
temp.allocPixels();
SkBitmapDevice device(temp);
test_crop_rects(&device, reporter);
}
#if SK_SUPPORT_GPU
DEF_GPUTEST(ImageFilterCropRectGPU, reporter, factory) {
GrContext* context = factory->get(static_cast<GrContextFactory::GLContextType>(0));
SkGpuDevice device(context, SkBitmap::kARGB_8888_Config, 100, 100);
test_crop_rects(&device, reporter);
}
#endif
<commit_msg>Speculative build fix after r13292.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBicubicImageFilter.h"
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkCanvas.h"
#include "SkColorFilterImageFilter.h"
#include "SkColorMatrixFilter.h"
#include "SkDeviceImageFilterProxy.h"
#include "SkDisplacementMapEffect.h"
#include "SkDropShadowImageFilter.h"
#include "SkLightingImageFilter.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkRect.h"
#include "SkTileImageFilter.h"
#include "SkXfermodeImageFilter.h"
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#include "SkGpuDevice.h"
#endif
static const int kBitmapSize = 4;
static void make_small_bitmap(SkBitmap& bitmap) {
bitmap.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
bitmap.allocPixels();
SkBitmapDevice device(bitmap);
SkCanvas canvas(&device);
canvas.clear(0x00000000);
SkPaint darkPaint;
darkPaint.setColor(0xFF804020);
SkPaint lightPaint;
lightPaint.setColor(0xFF244484);
const int i = kBitmapSize / 4;
for (int y = 0; y < kBitmapSize; y += i) {
for (int x = 0; x < kBitmapSize; x += i) {
canvas.save();
canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
canvas.drawRect(SkRect::MakeXYWH(0, 0,
SkIntToScalar(i),
SkIntToScalar(i)), darkPaint);
canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
0,
SkIntToScalar(i),
SkIntToScalar(i)), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(0,
SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i)), lightPaint);
canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i),
SkIntToScalar(i)), darkPaint);
canvas.restore();
}
}
}
static SkImageFilter* make_scale(float amount, SkImageFilter* input = NULL) {
SkScalar s = amount;
SkScalar matrix[20] = { s, 0, 0, 0, 0,
0, s, 0, 0, 0,
0, 0, s, 0, 0,
0, 0, 0, s, 0 };
SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
return SkColorFilterImageFilter::Create(filter, input);
}
static SkImageFilter* make_grayscale(SkImageFilter* input = NULL, const SkImageFilter::CropRect* cropRect = NULL) {
SkScalar matrix[20];
memset(matrix, 0, 20 * sizeof(SkScalar));
matrix[0] = matrix[5] = matrix[10] = 0.2126f;
matrix[1] = matrix[6] = matrix[11] = 0.7152f;
matrix[2] = matrix[7] = matrix[12] = 0.0722f;
matrix[18] = 1.0f;
SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
return SkColorFilterImageFilter::Create(filter, input, cropRect);
}
DEF_TEST(ImageFilter, reporter) {
{
// Check that two non-clipping color matrices concatenate into a single filter.
SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f));
SkAutoTUnref<SkImageFilter> quarterBrightness(make_scale(0.5f, halfBrightness));
REPORTER_ASSERT(reporter, NULL == quarterBrightness->getInput(0));
}
{
// Check that a clipping color matrix followed by a grayscale does not concatenate into a single filter.
SkAutoTUnref<SkImageFilter> doubleBrightness(make_scale(2.0f));
SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f, doubleBrightness));
REPORTER_ASSERT(reporter, NULL != halfBrightness->getInput(0));
}
{
// Check that a color filter image filter without a crop rect can be
// expressed as a color filter.
SkAutoTUnref<SkImageFilter> gray(make_grayscale());
REPORTER_ASSERT(reporter, true == gray->asColorFilter(NULL));
}
{
// Check that a color filter image filter with a crop rect cannot
// be expressed as a color filter.
SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(0, 0, 100, 100));
SkAutoTUnref<SkImageFilter> grayWithCrop(make_grayscale(NULL, &cropRect));
REPORTER_ASSERT(reporter, false == grayWithCrop->asColorFilter(NULL));
}
{
// Tests pass by not asserting
SkBitmap bitmap, result;
make_small_bitmap(bitmap);
result.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
result.allocPixels();
{
// This tests for :
// 1 ) location at (0,0,1)
SkPoint3 location(0, 0, SK_Scalar1);
// 2 ) location and target at same value
SkPoint3 target(location.fX, location.fY, location.fZ);
// 3 ) large negative specular exponent value
SkScalar specularExponent = -1000;
SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
SkPaint paint;
paint.setImageFilter(SkLightingImageFilter::CreateSpotLitSpecular(
location, target, specularExponent, 180,
0xFFFFFFFF, SK_Scalar1, SK_Scalar1, SK_Scalar1,
bmSrc))->unref();
SkCanvas canvas(result);
SkRect r = SkRect::MakeWH(SkIntToScalar(kBitmapSize),
SkIntToScalar(kBitmapSize));
canvas.drawRect(r, paint);
}
{
// This tests for scale bringing width to 0
SkSize scale = SkSize::Make(-0.001f, SK_Scalar1);
SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
SkAutoTUnref<SkBicubicImageFilter> bicubic(
SkBicubicImageFilter::CreateMitchell(scale, bmSrc));
SkBitmapDevice device(bitmap);
SkDeviceImageFilterProxy proxy(&device);
SkIPoint loc = SkIPoint::Make(0, 0);
// An empty input should early return and return false
REPORTER_ASSERT(reporter,
!bicubic->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &loc));
}
}
}
static void test_crop_rects(SkBaseDevice* device, skiatest::Reporter* reporter) {
// Check that all filters offset to their absolute crop rect,
// unaffected by the input crop rect.
// Tests pass by not asserting.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
bitmap.allocPixels();
bitmap.eraseARGB(0, 0, 0, 0);
SkDeviceImageFilterProxy proxy(device);
SkImageFilter::CropRect inputCropRect(SkRect::MakeXYWH(8, 13, 80, 80));
SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(20, 30, 60, 60));
SkAutoTUnref<SkImageFilter> input(make_grayscale(NULL, &inputCropRect));
SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED, SkXfermode::kSrcIn_Mode));
SkPoint3 location(0, 0, SK_Scalar1);
SkPoint3 target(SK_Scalar1, SK_Scalar1, SK_Scalar1);
SkScalar kernel[9] = {
SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1),
SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
};
SkISize kernelSize = SkISize::Make(3, 3);
SkScalar gain = SK_Scalar1, bias = 0;
SkImageFilter* filters[] = {
SkColorFilterImageFilter::Create(cf.get(), input.get(), &cropRect),
new SkDisplacementMapEffect(SkDisplacementMapEffect::kR_ChannelSelectorType,
SkDisplacementMapEffect::kB_ChannelSelectorType,
40.0f, input.get(), input.get(), &cropRect),
new SkBlurImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkDropShadowImageFilter(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_ColorGREEN, input.get(), &cropRect),
SkLightingImageFilter::CreatePointLitDiffuse(location, SK_ColorGREEN, 0, 0, input.get(), &cropRect),
SkLightingImageFilter::CreatePointLitSpecular(location, SK_ColorGREEN, 0, 0, 0, input.get(), &cropRect),
new SkMatrixConvolutionImageFilter(kernelSize, kernel, gain, bias, SkIPoint::Make(1, 1), SkMatrixConvolutionImageFilter::kRepeat_TileMode, false, input.get(), &cropRect),
new SkMergeImageFilter(input.get(), input.get(), SkXfermode::kSrcOver_Mode, &cropRect),
new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
new SkDilateImageFilter(3, 2, input.get(), &cropRect),
new SkErodeImageFilter(2, 3, input.get(), &cropRect),
new SkTileImageFilter(inputCropRect.rect(), cropRect.rect(), input.get()),
new SkXfermodeImageFilter(SkXfermode::Create(SkXfermode::kSrcOver_Mode), input.get(), input.get(), &cropRect),
};
for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
SkImageFilter* filter = filters[i];
SkBitmap result;
SkIPoint offset;
SkString str;
str.printf("filter %zd", i);
REPORTER_ASSERT_MESSAGE(reporter, filter->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &offset), str.c_str());
REPORTER_ASSERT_MESSAGE(reporter, offset.fX == 20 && offset.fY == 30, str.c_str());
}
for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
SkSafeUnref(filters[i]);
}
}
DEF_TEST(ImageFilterCropRect, reporter) {
SkBitmap temp;
temp.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
temp.allocPixels();
SkBitmapDevice device(temp);
test_crop_rects(&device, reporter);
}
#if SK_SUPPORT_GPU
DEF_GPUTEST(ImageFilterCropRectGPU, reporter, factory) {
GrContext* context = factory->get(static_cast<GrContextFactory::GLContextType>(0));
SkGpuDevice device(context, SkBitmap::kARGB_8888_Config, 100, 100);
test_crop_rects(&device, reporter);
}
#endif
<|endoftext|> |
<commit_before>#ifndef __CONCURRENCY_CORO_POOL_HPP__
#define __CONCURRENCY_CORO_POOL_HPP__
#include "errors.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "concurrency/drain_semaphore.hpp"
/* coro_pool_t maintains a bunch of coroutines; when you give it tasks, it
distributes them among the coroutines. It draws its tasks from a
`passive_producer_t<boost::function<void()> >*`. */
class coro_pool_t :
public home_thread_mixin_t,
private watchable_t<bool>::watcher_t
{
public:
coro_pool_t(size_t worker_count_, passive_producer_t<boost::function<void()> > *source) :
source(source),
max_worker_count(worker_count_),
active_worker_count(0)
{
rassert(max_worker_count > 0);
on_watchable_changed(); // Start process if necessary
source->available->add_watcher(this);
}
~coro_pool_t() {
assert_thread();
source->available->remove_watcher(this);
coro_drain_semaphore.drain();
rassert(active_worker_count == 0);
}
void rethread(int new_thread) {
/* Can't rethread while there are active operations */
rassert(active_worker_count == 0);
rassert(!source->available->get());
real_home_thread = new_thread;
}
private:
passive_producer_t<boost::function<void()> > *source;
void on_watchable_changed() {
assert_thread();
if (max_worker_count != 1) debugf("on_watchable_changed(), source->available->get()=%s\n", source->available->get() ? "true" : "false");
while (source->available->get() && active_worker_count < max_worker_count) {
if (max_worker_count != 1) debugf("spawning coroutine...\n");
coro_t::spawn_now(boost::bind(
&coro_pool_t::worker_run,
this,
drain_semaphore_t::lock_t(&coro_drain_semaphore)
));
}
}
int max_worker_count, active_worker_count;
drain_semaphore_t coro_drain_semaphore;
void worker_run(UNUSED drain_semaphore_t::lock_t coro_drain_semaphore_lock) {
assert_thread();
if (max_worker_count != 1) debugf("%p worker_run() active_worker_count %d -> %d\n", coro_t::self(), active_worker_count, active_worker_count + 1);
++active_worker_count;
rassert(active_worker_count <= max_worker_count);
while (source->available->get()) {
if (max_worker_count != 1) debugf("%p doing a task...\n", coro_t::self());
/* Pop the task that we are going to do off the queue */
boost::function<void()> task = source->pop();
task(); // Perform the task
assert_thread(); // Make sure that `task()` didn't mess with us
}
if (max_worker_count != 1) debugf("%p worker_run() active_worker_count %d -> %d\n", coro_t::self(), active_worker_count, active_worker_count - 1);
--active_worker_count;
}
};
#endif /* __CONCURRENCY_CORO_POOL_HPP__ */
<commit_msg>Removed some debugf()s<commit_after>#ifndef __CONCURRENCY_CORO_POOL_HPP__
#define __CONCURRENCY_CORO_POOL_HPP__
#include "errors.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "concurrency/drain_semaphore.hpp"
/* coro_pool_t maintains a bunch of coroutines; when you give it tasks, it
distributes them among the coroutines. It draws its tasks from a
`passive_producer_t<boost::function<void()> >*`. */
class coro_pool_t :
public home_thread_mixin_t,
private watchable_t<bool>::watcher_t
{
public:
coro_pool_t(size_t worker_count_, passive_producer_t<boost::function<void()> > *source) :
source(source),
max_worker_count(worker_count_),
active_worker_count(0)
{
rassert(max_worker_count > 0);
on_watchable_changed(); // Start process if necessary
source->available->add_watcher(this);
}
~coro_pool_t() {
assert_thread();
source->available->remove_watcher(this);
coro_drain_semaphore.drain();
rassert(active_worker_count == 0);
}
void rethread(int new_thread) {
/* Can't rethread while there are active operations */
rassert(active_worker_count == 0);
rassert(!source->available->get());
real_home_thread = new_thread;
}
private:
passive_producer_t<boost::function<void()> > *source;
void on_watchable_changed() {
assert_thread();
while (source->available->get() && active_worker_count < max_worker_count) {
coro_t::spawn_now(boost::bind(
&coro_pool_t::worker_run,
this,
drain_semaphore_t::lock_t(&coro_drain_semaphore)
));
}
}
int max_worker_count, active_worker_count;
drain_semaphore_t coro_drain_semaphore;
void worker_run(UNUSED drain_semaphore_t::lock_t coro_drain_semaphore_lock) {
assert_thread();
++active_worker_count;
rassert(active_worker_count <= max_worker_count);
while (source->available->get()) {
/* Pop the task that we are going to do off the queue */
boost::function<void()> task = source->pop();
task(); // Perform the task
assert_thread(); // Make sure that `task()` didn't mess with us
}
--active_worker_count;
}
};
#endif /* __CONCURRENCY_CORO_POOL_HPP__ */
<|endoftext|> |
<commit_before>/*
* Steve Vaught
* This program uses the Unlicense
*/
// == Include statements ==
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
// == Function prototypes ==
string buildRandomString(int length);
void evolve(string& scrambled, const string target);
const int score(const string scrambled);
const int getDistance(const char first, const char second);
void evolve(string& scrambled, const string target);
vector<string> spawn(const string scrambled);
string mutateString(const string scrambled);
string cull(vector<string> children);
// == Tiny functions ==
bool compareScores(const string& first, const string& second){return(score(first)<score(second));}
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0,std::distance(start, end) -1);
std::advance(start,dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start,end,gen);
}
// == Main ==
int main(){
/* Set target, create initial random string, run evolution and keep count*/
string target("Methinks it is like a weasel");
string scrambled = buildRandomString( target.length() );
int attempts = 0;
while( target.compare(scrambled) != 0 ) {
cout << attempts++ << ": " << scrambled << " : " << score(scrambled) << endl;
evolve(scrambled, target);
}
cout << "Solved in " << attempts << " attempts!" << endl;
return 0;
}
vector<char> getAlphanumerics(){
// Return the candidate alphabet from which random letters (and space) are pulled
return vector<char> {
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z',
' '
};
}
string buildRandomString(int length){
vector<char> alphanumerics = getAlphanumerics();
string randstring = "";
for (auto i = 0; i < length; i++){
// push random letters onto the string until we reach the target string length
randstring.push_back( *select_randomly(alphanumerics.begin(), alphanumerics.end()) );
}
return randstring;
}
void evolve(string& parent, const string target){
vector<string> children = spawn(parent); // populate a vector of children based on parent
children.push_back(parent); // parent might be a better fit than any of its children
parent = cull(children); // replace parent with the best fit of it's children (savage!)
return;
}
vector<string> spawn(const string scrambled){
// given a string, populate and return a vector with mutated children based on it
const int litterSize = 99;
vector<string> children = {};
for (int i = 0; i < litterSize; i++){
children.push_back( mutateString(scrambled) );
}
return children;
}
string mutateString(const string parent){
static std::default_random_engine gen; //initialize a rand generator as static (one per program)
static std::uniform_int_distribution<int> dist(0,100); // force random numbers to fit 0-100 distribution
const int mutateChance = 5; // percent chance of mutation
vector<char> alphanumerics = getAlphanumerics();
string mutated = parent; // child string begins as an unaltered copy of parent string
int dice = 0;
for (auto& eachletter : mutated){
dice = dist(gen); // roll the dice
if (dice < mutateChance) {
eachletter = *select_randomly(alphanumerics.begin(), alphanumerics.end()) ;
}
}
return mutated;
}
string cull(vector<string> children){
// from a vector of many children, select the one which has the lowest score
// it's nice when the language has exactly an algorithm to do the task you need
// we only need to pass a function to tell it how to do the comparison
return *std::min_element(children.begin(),children.end(),compareScores);
}
const int score(const string candidate){
const string target("Methinks it is like a weasel"); //need to find a way not to duplicate this
string::const_iterator it = candidate.begin();
string::const_iterator targetit = target.begin();
int score = 0;
for (; it < candidate.end(); it++, targetit++){
if (*it != *targetit){
//cout << "Score: " << getDistance(*it,*targetit) << endl;
//score += getDistance(*it,*targetit);
score += 1;
}
}
return score;
}
const int getDistance(const char firstchar, const char secondchar){
// Currently unused but might be used in the future
// Currently score works by checking if each letter is right or wrong in a yes/no fashion
// if you wanted to get fancier, you could determine how close a letter is to correct
// this function attempts to do that.
// Does not properly handle Z->A comparisons
vector<char> alphabet = getAlphanumerics();
vector<char>::iterator firstit, secondit;
firstit = find(alphabet.begin(), alphabet.end(), firstchar);
secondit = find(alphabet.begin(), alphabet.end(), secondchar);
return abs( distance(firstit,secondit) );
}
<commit_msg>slightly better end output<commit_after>/*
* Steve Vaught
* This program uses the Unlicense
*/
// == Include statements ==
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
// == Function prototypes ==
string buildRandomString(int length);
void evolve(string& scrambled, const string target);
const int score(const string scrambled);
const int getDistance(const char first, const char second);
void evolve(string& scrambled, const string target);
vector<string> spawn(const string scrambled);
string mutateString(const string scrambled);
string cull(vector<string> children);
// == Tiny functions ==
bool compareScores(const string& first, const string& second){return(score(first)<score(second));}
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0,std::distance(start, end) -1);
std::advance(start,dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start,end,gen);
}
// == Main ==
int main(){
/* Set target, create initial random string, run evolution and keep count*/
string target("Methinks it is like a weasel");
string scrambled = buildRandomString( target.length() );
int attempts = 0;
while( target.compare(scrambled) != 0 ) {
cout << attempts++ << ": " << scrambled << " : " << score(scrambled) << endl;
evolve(scrambled, target);
}
cout << scrambled << " : Solved in " << attempts << " attempts!" << endl;
return 0;
}
vector<char> getAlphanumerics(){
// Return the candidate alphabet from which random letters (and space) are pulled
return vector<char> {
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z',
' '
};
}
string buildRandomString(int length){
vector<char> alphanumerics = getAlphanumerics();
string randstring = "";
for (auto i = 0; i < length; i++){
// push random letters onto the string until we reach the target string length
randstring.push_back( *select_randomly(alphanumerics.begin(), alphanumerics.end()) );
}
return randstring;
}
void evolve(string& parent, const string target){
vector<string> children = spawn(parent); // populate a vector of children based on parent
children.push_back(parent); // parent might be a better fit than any of its children
parent = cull(children); // replace parent with the best fit of it's children (savage!)
return;
}
vector<string> spawn(const string scrambled){
// given a string, populate and return a vector with mutated children based on it
const int litterSize = 99;
vector<string> children = {};
for (int i = 0; i < litterSize; i++){
children.push_back( mutateString(scrambled) );
}
return children;
}
string mutateString(const string parent){
static std::default_random_engine gen; //initialize a rand generator as static (one per program)
static std::uniform_int_distribution<int> dist(0,100); // force random numbers to fit 0-100 distribution
const int mutateChance = 5; // percent chance of mutation
vector<char> alphanumerics = getAlphanumerics();
string mutated = parent; // child string begins as an unaltered copy of parent string
int dice = 0;
for (auto& eachletter : mutated){
dice = dist(gen); // roll the dice
if (dice < mutateChance) {
eachletter = *select_randomly(alphanumerics.begin(), alphanumerics.end()) ;
}
}
return mutated;
}
string cull(vector<string> children){
// from a vector of many children, select the one which has the lowest score
// it's nice when the language has exactly an algorithm to do the task you need
// we only need to pass a function to tell it how to do the comparison
return *std::min_element(children.begin(),children.end(),compareScores);
}
const int score(const string candidate){
const string target("Methinks it is like a weasel"); //need to find a way not to duplicate this
string::const_iterator it = candidate.begin();
string::const_iterator targetit = target.begin();
int score = 0;
for (; it < candidate.end(); it++, targetit++){
if (*it != *targetit){
//cout << "Score: " << getDistance(*it,*targetit) << endl;
//score += getDistance(*it,*targetit);
score += 1;
}
}
return score;
}
const int getDistance(const char firstchar, const char secondchar){
// Currently unused but might be used in the future
// Currently score works by checking if each letter is right or wrong in a yes/no fashion
// if you wanted to get fancier, you could determine how close a letter is to correct
// this function attempts to do that.
// Does not properly handle Z->A comparisons
vector<char> alphabet = getAlphanumerics();
vector<char>::iterator firstit, secondit;
firstit = find(alphabet.begin(), alphabet.end(), firstchar);
secondit = find(alphabet.begin(), alphabet.end(), secondchar);
return abs( distance(firstit,secondit) );
}
<|endoftext|> |
<commit_before>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas which have not changed much
// this is horrible with new background; redo it
Mat flow(height, width, CV_8UC1, 1);
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
threshold(flow, flow, 8, 1, THRESH_BINARY);
morphFast(flow);
imshow("flow mask", gray.mul(flow));
times[2] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// flow = Mat(height, width, CV_8UC1, 1);
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark(height, width, CV_8UC1, 1);
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// combine mask with its opening
Mat mask = flow.mul(kindofdark);
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// run haar classifier on nonflow parts of image
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rectImage(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
Mat newRect(height, width, CV_8UC1, Scalar(0));
rectangle(newRect, scaled, Scalar(1), CV_FILLED);
rectImage += newRect;
}
double minVal, maxVal;//ignore minVal, it'll be 0
minMaxLoc(rectImage, &minVal, &maxVal);
Mat recThresh, recBinary;
threshold(rectImage, recThresh, maxVal*0.8, 1, THRESH_BINARY);
// what's the point of this v ?
threshold(rectImage, recBinary, 1, 1, THRESH_BINARY);
bitwise_and(recBinary, mask, mask);
times[5] = getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("mouth", recThresh.mul(gray));
/*
Moments lol = moments(recThresh, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
// update background with new morph mask
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[6] = getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("bg", background);
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas which have not changed much
// this is horrible with new background; redo it
Mat flow(height, width, CV_8UC1, 1);
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
threshold(flow, flow, 6, 1, THRESH_BINARY);
morphFast(flow);
imshow("flow mask", gray.mul(flow));
times[2] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// flow = Mat(height, width, CV_8UC1, 1);
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark(height, width, CV_8UC1, 1);
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// combine mask with its opening
Mat mask = flow.mul(kindofdark);
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] = getMilliseconds() - timenow;
timenow = getMilliseconds();
// run haar classifier on nonflow parts of image
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rectImage(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
Mat newRect(height, width, CV_8UC1, Scalar(0));
rectangle(newRect, scaled, Scalar(1), CV_FILLED);
rectImage += newRect;
}
double minVal, maxVal;//ignore minVal, it'll be 0
minMaxLoc(rectImage, &minVal, &maxVal);
Mat recThresh, recBinary;
threshold(rectImage, recThresh, maxVal*0.8, 1, THRESH_BINARY);
// what's the point of this v ?
threshold(rectImage, recBinary, 1, 1, THRESH_BINARY);
bitwise_and(recBinary, mask, mask);
times[5] = getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("mouth", recThresh.mul(gray));
/*
Moments lol = moments(recThresh, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
// update background with new morph mask
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[6] = getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("bg", background);
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg
/*
// actually dilation is slow and our current mask is already
// really nice :)
Mat dilatedMask;
dilate(smallMask1, dilatedMask, smallKernel);
resize(dilatedMask, dilatedMask, Size(width, height));
imshow("erosion", dilatedMask.mul(gray));
*/
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rectImage(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
Mat newRect(height, width, CV_8UC1, Scalar(0));
rectangle(newRect, scaled, Scalar(1), CV_FILLED);
rectImage += newRect;
}
double minVal, maxVal;//ignore minVal, it'll be 0
minMaxLoc(rectImage, &minVal, &maxVal);
threshold(rectImage, rectImage, maxVal-1, 1, THRESH_BINARY);
printf("max: %.f\n",maxVal);
times[6] += getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("MOUTH", rectImage.mul(gray));
bitwise_and(rectImage, mask, mask);
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg
/*
// actually dilation is slow and our current mask is already
// really nice :)
Mat dilatedMask;
dilate(smallMask1, dilatedMask, smallKernel);
resize(dilatedMask, dilatedMask, Size(width, height));
imshow("erosion", dilatedMask.mul(gray));
*/
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rectImage(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
Mat newRect(height, width, CV_8UC1, Scalar(0));
rectangle(newRect, scaled, Scalar(1), CV_FILLED);
rectImage += newRect;
}
double minVal, maxVal;//ignore minVal, it'll be 0
minMaxLoc(rectImage, &minVal, &maxVal);
threshold(rectImage, rectImage, maxVal-2, 1, THRESH_BINARY);
printf("max: %.f\n",maxVal);
times[6] += getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("MOUTH", rectImage.mul(gray));
bitwise_and(rectImage, mask, mask);
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
imshow("webcam", image);
// thresholds on dark regions
Mat gray, blurred_gray, threshold_gray;
cvtColor(image, gray, CV_BGR2GRAY);
blur(gray, blurred_gray, Size(width/10,height/20));
equalizeHist(blurred_gray, blurred_gray);
threshold(blurred_gray, threshold_gray, 40, 1, THRESH_BINARY_INV);
imshow("threshold", threshold_gray.mul(gray));
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
imshow("webcam", image);
// thresholds on dark regions
Mat gray, blurred_gray, threshold_gray;
cvtColor(image, gray, CV_BGR2GRAY);
blur(gray, blurred_gray, Size(width/10,height/20));
equalizeHist(blurred_gray, blurred_gray);
threshold(blurred_gray, threshold_gray, 40, 1, THRESH_BINARY_INV);
imshow("threshold", threshold_gray.mul(gray));
Moments lol = moments(threshold_gray, 1);
printf("m00: %f, m10: %f, m01: %f, m20: %f, m11: %f\n", lol.m00, lol.m10, lol.m01, lol.m20, lol.m11);
printf("m02: %f, m30: %f, m21: %f, m12: %f, m03: %f\n", lol.m02, lol.m30, lol.m21, lol.m12, lol.m03);
printf("mu20: %f, mu11: %f, mu02: %f, mu30: %f, mu21: %f, mu12: %f, mu03: %f\n", lol.mu20, lol.mu11, lol.mu02, lol.mu30, lol.mu21, lol.mu12, lol.mu03);
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "MessageBuilder.hpp"
#include "common/LinkParser.hpp"
#include "messages/Message.hpp"
#include "messages/MessageElement.hpp"
#include "providers/twitch/PubsubActions.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Theme.hpp"
#include "util/FormatTime.hpp"
#include "util/IrcHelpers.hpp"
#include <QDateTime>
namespace chatterino {
MessagePtr makeSystemMessage(const QString &text)
{
return MessageBuilder(systemMessage, text).release();
}
MessageBuilder::MessageBuilder()
: message_(std::make_shared<Message>())
{
}
MessageBuilder::MessageBuilder(const QString &text)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::DoNotTriggerNotification);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(TimeoutMessageTag, const QString &username,
const QString &durationInSeconds,
const QString &reason, bool multipleTimes)
: MessageBuilder()
{
QString text;
text.append(username);
if (!durationInSeconds.isEmpty()) {
text.append(" has been timed out");
// TODO: Implement who timed the user out
text.append(" for ");
bool ok = true;
int timeoutSeconds = durationInSeconds.toInt(&ok);
if (ok) {
text.append(formatTime(timeoutSeconds));
}
} else {
text.append(" has been permanently banned");
}
if (reason.length() > 0) {
text.append(": \"");
text.append(parseTagString(reason));
text.append("\"");
}
text.append(".");
if (multipleTimes) {
text.append(" (multiple times)");
}
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Timeout);
this->message().flags.set(MessageFlag::DoNotTriggerNotification);
this->message().timeoutUser = username;
}
MessageBuilder::MessageBuilder(const BanAction &action, uint32_t count)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Timeout);
this->message().timeoutUser = action.target.name;
this->message().count = count;
QString text;
if (action.isBan()) {
if (action.reason.isEmpty()) {
text = QString("%1 banned %2.") //
.arg(action.source.name)
.arg(action.target.name);
} else {
text = QString("%1 banned %2: \"%3\".") //
.arg(action.source.name)
.arg(action.target.name)
.arg(action.reason);
}
} else {
if (action.reason.isEmpty()) {
text = QString("%1 timed out %2 for %3.") //
.arg(action.source.name)
.arg(action.target.name)
.arg(formatTime(action.duration));
} else {
text = QString("%1 timed out %2 for %3: \"%4\".") //
.arg(action.source.name)
.arg(action.target.name)
.arg(formatTime(action.duration))
.arg(action.reason);
}
if (count > 1) {
text.append(QString(" (%1 times)").arg(count));
}
}
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(const UnbanAction &action)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Untimeout);
this->message().timeoutUser = action.target.name;
QString text;
if (action.wasBan()) {
text = QString("%1 unbanned %2.") //
.arg(action.source.name)
.arg(action.target.name);
} else {
text = QString("%1 untimedout %2.") //
.arg(action.source.name)
.arg(action.target.name);
}
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
Message *MessageBuilder::operator->()
{
return this->message_.get();
}
Message &MessageBuilder::message()
{
return *this->message_;
}
MessagePtr MessageBuilder::release()
{
std::shared_ptr<Message> ptr;
this->message_.swap(ptr);
return ptr;
}
void MessageBuilder::append(std::unique_ptr<MessageElement> element)
{
this->message().elements.push_back(std::move(element));
}
QString MessageBuilder::matchLink(const QString &string)
{
LinkParser linkParser(string);
static QRegularExpression httpRegex(
"\\bhttps?://", QRegularExpression::CaseInsensitiveOption);
static QRegularExpression ftpRegex(
"\\bftps?://", QRegularExpression::CaseInsensitiveOption);
static QRegularExpression spotifyRegex(
"\\bspotify:", QRegularExpression::CaseInsensitiveOption);
if (!linkParser.hasMatch()) {
return QString();
}
QString captured = linkParser.getCaptured();
if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) &&
!captured.contains(spotifyRegex)) {
captured.insert(0, "http://");
}
return captured;
}
} // namespace chatterino
<commit_msg>fixes that timeout/ban messages didn't show (#728)<commit_after>#include "MessageBuilder.hpp"
#include "common/LinkParser.hpp"
#include "messages/Message.hpp"
#include "messages/MessageElement.hpp"
#include "providers/twitch/PubsubActions.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Theme.hpp"
#include "util/FormatTime.hpp"
#include "util/IrcHelpers.hpp"
#include <QDateTime>
namespace chatterino {
MessagePtr makeSystemMessage(const QString &text)
{
return MessageBuilder(systemMessage, text).release();
}
MessageBuilder::MessageBuilder()
: message_(std::make_shared<Message>())
{
}
MessageBuilder::MessageBuilder(const QString &text)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::DoNotTriggerNotification);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(TimeoutMessageTag, const QString &username,
const QString &durationInSeconds,
const QString &reason, bool multipleTimes)
: MessageBuilder()
{
QString text;
text.append(username);
if (!durationInSeconds.isEmpty()) {
text.append(" has been timed out");
// TODO: Implement who timed the user out
text.append(" for ");
bool ok = true;
int timeoutSeconds = durationInSeconds.toInt(&ok);
if (ok) {
text.append(formatTime(timeoutSeconds));
}
} else {
text.append(" has been permanently banned");
}
if (reason.length() > 0) {
text.append(": \"");
text.append(parseTagString(reason));
text.append("\"");
}
text.append(".");
if (multipleTimes) {
text.append(" (multiple times)");
}
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Timeout);
this->message().flags.set(MessageFlag::DoNotTriggerNotification);
this->message().timeoutUser = username;
this->emplace<TimestampElement>();
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(const BanAction &action, uint32_t count)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Timeout);
this->message().timeoutUser = action.target.name;
this->message().count = count;
QString text;
if (action.isBan()) {
if (action.reason.isEmpty()) {
text = QString("%1 banned %2.") //
.arg(action.source.name)
.arg(action.target.name);
} else {
text = QString("%1 banned %2: \"%3\".") //
.arg(action.source.name)
.arg(action.target.name)
.arg(action.reason);
}
} else {
if (action.reason.isEmpty()) {
text = QString("%1 timed out %2 for %3.") //
.arg(action.source.name)
.arg(action.target.name)
.arg(formatTime(action.duration));
} else {
text = QString("%1 timed out %2 for %3: \"%4\".") //
.arg(action.source.name)
.arg(action.target.name)
.arg(formatTime(action.duration))
.arg(action.reason);
}
if (count > 1) {
text.append(QString(" (%1 times)").arg(count));
}
}
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(const UnbanAction &action)
: MessageBuilder()
{
this->emplace<TimestampElement>();
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::Untimeout);
this->message().timeoutUser = action.target.name;
QString text;
if (action.wasBan()) {
text = QString("%1 unbanned %2.") //
.arg(action.source.name)
.arg(action.target.name);
} else {
text = QString("%1 untimedout %2.") //
.arg(action.source.name)
.arg(action.target.name);
}
this->emplace<TextElement>(text, MessageElementFlag::Text,
MessageColor::System);
this->message().searchText = text;
}
Message *MessageBuilder::operator->()
{
return this->message_.get();
}
Message &MessageBuilder::message()
{
return *this->message_;
}
MessagePtr MessageBuilder::release()
{
std::shared_ptr<Message> ptr;
this->message_.swap(ptr);
return ptr;
}
void MessageBuilder::append(std::unique_ptr<MessageElement> element)
{
this->message().elements.push_back(std::move(element));
}
QString MessageBuilder::matchLink(const QString &string)
{
LinkParser linkParser(string);
static QRegularExpression httpRegex(
"\\bhttps?://", QRegularExpression::CaseInsensitiveOption);
static QRegularExpression ftpRegex(
"\\bftps?://", QRegularExpression::CaseInsensitiveOption);
static QRegularExpression spotifyRegex(
"\\bspotify:", QRegularExpression::CaseInsensitiveOption);
if (!linkParser.hasMatch()) {
return QString();
}
QString captured = linkParser.getCaptured();
if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) &&
!captured.contains(spotifyRegex)) {
captured.insert(0, "http://");
}
return captured;
}
} // namespace chatterino
<|endoftext|> |
<commit_before>/* CUDA global device memory vector
*
* Copyright (C) 2020 Jaslo Ziska
* Copyright (C) 2020 Felix Höfling
* Copyright (C) 2007 Peter Colberg
*
* This file is part of cuda-wrapper.
*
* This software may be modified and distributed under the terms of the
* 3-clause BSD license. See accompanying file LICENSE for details.
*/
#ifndef CUDA_MEMORY_DEVICE_VECTOR_HPP
#define CUDA_MEMORY_DEVICE_VECTOR_HPP
#include <memory>
#include <initializer_list>
#include <cuda_wrapper/copy.hpp>
#include <cuda_wrapper/detail/random_access_iterator.hpp>
#include <cuda_wrapper/iterator_category.hpp>
#include <cuda_wrapper/memory/device/allocator.hpp>
namespace cuda {
namespace memory {
namespace device {
/**
* CUDA global device memory vector
*/
template <typename T>
class vector
{
public:
typedef T value_type;
typedef allocator<T> allocator_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef value_type& reference;
typedef value_type const& const_reference;
typedef value_type* pointer;
typedef value_type const* const_pointer;
typedef detail::random_access_iterator<pointer, device_random_access_iterator_tag> iterator;
typedef detail::random_access_iterator<const_pointer, device_random_access_iterator_tag> const_iterator;
private:
class container
{
public:
/**
* make the class noncopyable by deleting the copy and assignment operator
*/
container(container const&) = delete;
container& operator=(container const&) = delete;
/**
* allocate global device memory
*/
container(size_type size) : m_size(size), m_ptr(NULL)
{
m_ptr = allocator_type().allocate(m_size);
}
/**
* free global device memory
*/
~container()
{
allocator_type().deallocate(m_ptr, m_size);
}
size_type size() const noexcept
{
return m_size;
}
operator pointer() noexcept
{
return m_ptr;
}
operator const_pointer() const noexcept
{
return m_ptr;
}
private:
size_type m_size;
pointer m_ptr;
};
public:
/** create an empty vector */
vector() : m_size(0), m_mem(new container(m_size)) {}
/** create a vector with n elements */
explicit vector(size_type n) : m_size(n), m_mem(new container(m_size)) {}
/** creates a vector with a copy of a range */
template <class InputIterator>
vector(InputIterator begin, InputIterator end) : m_size(end - begin), m_mem(new container(m_size))
{
copy(begin, end, this->begin());
}
/** copy constructor */
vector(vector const& other) : m_size(other.m_size), m_mem(new container(m_size))
{
copy(other.begin(), other.end(), begin());
}
/** move constructor */
vector(vector&& other) noexcept : vector()
{
swap(*this, other);
}
/** construct vector from initializer list */
vector(std::initializer_list<T> list) : m_size(list.size()), m_mem(new container(m_size))
{
copy(list.begin(), list.end(), this->begin());
}
/** destructor */
~vector()
{
delete m_mem;
}
/** copy and move assignment
*
* We use the copy-and-swap idiom and ensure that the operations are
* self-safe and that the move assignment doesn't leak resources.
*/
vector& operator=(vector other)
{
vector temp;
swap(temp, other); // 'other' is empty now
swap(*this, temp);
return *this;
}
/** initializer list assignment */
vector& operator=(std::initializer_list<T> list)
{
delete m_mem;
m_size = list.size();
m_mem = new container(m_size);
copy(list.begin(), list.end(), this->begin());
return *this;
}
/**
* returns the device allocator
*/
allocator_type get_allocator() const noexcept
{
return allocator_type();
}
/**
* checks whether the container is empty
*/
bool empty() const noexcept
{
return this->begin() == this->end();
}
/**
* returns element count of device vector
*/
size_type size() const noexcept
{
return m_size;
}
/**
* returns the maximum possible number of elements
*/
size_type max_size() const noexcept
{
return allocator_type().max_size();
}
/**
* returns capacity
*/
size_type capacity() const noexcept
{
return m_mem->size();
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
this->reserve(size);
m_size = size;
}
/**
* allocate sufficient memory for specified number of elements
*/
void reserve(size_type size)
{
if (size > m_mem->size()) {
delete m_mem;
m_mem = new container(size);
}
}
/**
* swap device memory with vector
*/
friend void swap(vector& first, vector& second) noexcept
{
using std::swap;
swap(first.m_mem, second.m_mem);
swap(first.m_size, second.m_size);
}
/**
* returns device pointer to allocated device memory
*/
pointer data() noexcept
{
return *m_mem;
}
operator pointer() noexcept
{
return *m_mem;
}
const_pointer data() const noexcept
{
return *m_mem;
}
operator const_pointer() const noexcept
{
return *m_mem;
}
iterator begin() noexcept
{
return iterator(*m_mem);
}
const_iterator begin() const noexcept
{
return const_iterator(*m_mem);
}
iterator end() noexcept
{
return iterator(*m_mem + m_size);
}
const_iterator end() const noexcept
{
return const_iterator(*m_mem + m_size);
}
private:
size_type m_size;
container* m_mem;
};
} // namespace device
} // namespace memory
} // namespace cuda
#endif // CUDA_MEMORY_DEVICE_VECTOR_HPP
<commit_msg>Use full namespace name when calling copy() in vector.hpp<commit_after>/* CUDA global device memory vector
*
* Copyright (C) 2020 Jaslo Ziska
* Copyright (C) 2020 Felix Höfling
* Copyright (C) 2007 Peter Colberg
*
* This file is part of cuda-wrapper.
*
* This software may be modified and distributed under the terms of the
* 3-clause BSD license. See accompanying file LICENSE for details.
*/
#ifndef CUDA_MEMORY_DEVICE_VECTOR_HPP
#define CUDA_MEMORY_DEVICE_VECTOR_HPP
#include <memory>
#include <initializer_list>
#include <cuda_wrapper/copy.hpp>
#include <cuda_wrapper/detail/random_access_iterator.hpp>
#include <cuda_wrapper/iterator_category.hpp>
#include <cuda_wrapper/memory/device/allocator.hpp>
namespace cuda {
namespace memory {
namespace device {
/**
* CUDA global device memory vector
*/
template <typename T>
class vector
{
public:
typedef T value_type;
typedef allocator<T> allocator_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef value_type& reference;
typedef value_type const& const_reference;
typedef value_type* pointer;
typedef value_type const* const_pointer;
typedef detail::random_access_iterator<pointer, device_random_access_iterator_tag> iterator;
typedef detail::random_access_iterator<const_pointer, device_random_access_iterator_tag> const_iterator;
private:
class container
{
public:
/**
* make the class noncopyable by deleting the copy and assignment operator
*/
container(container const&) = delete;
container& operator=(container const&) = delete;
/**
* allocate global device memory
*/
container(size_type size) : m_size(size), m_ptr(NULL)
{
m_ptr = allocator_type().allocate(m_size);
}
/**
* free global device memory
*/
~container()
{
allocator_type().deallocate(m_ptr, m_size);
}
size_type size() const noexcept
{
return m_size;
}
operator pointer() noexcept
{
return m_ptr;
}
operator const_pointer() const noexcept
{
return m_ptr;
}
private:
size_type m_size;
pointer m_ptr;
};
public:
/** create an empty vector */
vector() : m_size(0), m_mem(new container(m_size)) {}
/** create a vector with n elements */
explicit vector(size_type n) : m_size(n), m_mem(new container(m_size)) {}
/** creates a vector with a copy of a range */
template <class InputIterator>
vector(InputIterator begin, InputIterator end) : m_size(end - begin), m_mem(new container(m_size))
{
::cuda::copy(begin, end, this->begin());
}
/** copy constructor */
vector(vector const& other) : m_size(other.m_size), m_mem(new container(m_size))
{
::cuda::copy(other.begin(), other.end(), begin());
}
/** move constructor */
vector(vector&& other) noexcept : vector()
{
swap(*this, other);
}
/** construct vector from initializer list */
vector(std::initializer_list<T> list) : m_size(list.size()), m_mem(new container(m_size))
{
copy(list.begin(), list.end(), this->begin());
}
/** destructor */
~vector()
{
delete m_mem;
}
/** copy and move assignment
*
* We use the copy-and-swap idiom and ensure that the operations are
* self-safe and that the move assignment doesn't leak resources.
*/
vector& operator=(vector other)
{
vector temp;
swap(temp, other); // 'other' is empty now
swap(*this, temp);
return *this;
}
/** initializer list assignment */
vector& operator=(std::initializer_list<T> list)
{
delete m_mem;
m_size = list.size();
m_mem = new container(m_size);
copy(list.begin(), list.end(), this->begin());
return *this;
}
/**
* returns the device allocator
*/
allocator_type get_allocator() const noexcept
{
return allocator_type();
}
/**
* checks whether the container is empty
*/
bool empty() const noexcept
{
return this->begin() == this->end();
}
/**
* returns element count of device vector
*/
size_type size() const noexcept
{
return m_size;
}
/**
* returns the maximum possible number of elements
*/
size_type max_size() const noexcept
{
return allocator_type().max_size();
}
/**
* returns capacity
*/
size_type capacity() const noexcept
{
return m_mem->size();
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
this->reserve(size);
m_size = size;
}
/**
* allocate sufficient memory for specified number of elements
*/
void reserve(size_type size)
{
if (size > m_mem->size()) {
delete m_mem;
m_mem = new container(size);
}
}
/**
* swap device memory with vector
*/
friend void swap(vector& first, vector& second) noexcept
{
using std::swap;
swap(first.m_mem, second.m_mem);
swap(first.m_size, second.m_size);
}
/**
* returns device pointer to allocated device memory
*/
pointer data() noexcept
{
return *m_mem;
}
operator pointer() noexcept
{
return *m_mem;
}
const_pointer data() const noexcept
{
return *m_mem;
}
operator const_pointer() const noexcept
{
return *m_mem;
}
iterator begin() noexcept
{
return iterator(*m_mem);
}
const_iterator begin() const noexcept
{
return const_iterator(*m_mem);
}
iterator end() noexcept
{
return iterator(*m_mem + m_size);
}
const_iterator end() const noexcept
{
return const_iterator(*m_mem + m_size);
}
private:
size_type m_size;
container* m_mem;
};
} // namespace device
} // namespace memory
} // namespace cuda
#endif // CUDA_MEMORY_DEVICE_VECTOR_HPP
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreVolumeMeshBuilder.h"
#include <limits.h>
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Ogre::Volume::Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->getTriangles(mVertices, mIndices);
}
}
}<commit_msg>Volume Rendering: removed a warning<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreVolumeMeshBuilder.h"
#include <limits.h>
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Ogre::Volume::Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = (unsigned short)*iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->getTriangles(mVertices, mIndices);
}
}
}<|endoftext|> |
<commit_before>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "usModuleResource.h"
#include "usAtomicInt_p.h"
#include "usModuleResourceTree_p.h"
#include <string>
US_BEGIN_NAMESPACE
class ModuleResourcePrivate
{
public:
ModuleResourcePrivate()
: associatedResourceTree(NULL)
, node(-1)
, size(0)
, data(NULL)
, isFile(false)
, ref(1)
{}
std::string fileName;
std::string path;
std::string filePath;
std::vector<ModuleResourceTree*> resourceTrees;
const ModuleResourceTree* associatedResourceTree;
int node;
int32_t size;
const unsigned char* data;
mutable std::vector<std::string> children;
bool isFile;
/**
* Reference count for implicitly shared private implementation.
*/
AtomicInt ref;
};
ModuleResource::ModuleResource()
: d(new ModuleResourcePrivate)
{
}
ModuleResource::ModuleResource(const ModuleResource &resource)
: d(resource.d)
{
d->ref.Ref();
}
ModuleResource::ModuleResource(const std::string& _file, ModuleResourceTree* associatedResourceTree,
const std::vector<ModuleResourceTree*>& resourceTrees)
: d(new ModuleResourcePrivate)
{
d->resourceTrees = resourceTrees;
d->associatedResourceTree = associatedResourceTree;
std::string file = _file;
if (file.empty()) file = "/";
if (file[0] != '/') file = std::string("/") + file;
std::size_t index = file.find_last_of('/');
if (index < file.size()-1)
{
d->fileName = file.substr(index+1);
}
std::string rawPath = file.substr(0,index+1);
// remove duplicate /
std::string::value_type lastChar = 0;
for (std::size_t i = 0; i < rawPath.size(); ++i)
{
if (rawPath[i] == '/' && lastChar == '/')
{
continue;
}
lastChar = rawPath[i];
d->path.push_back(lastChar);
}
d->filePath = d->path + d->fileName;
d->node = d->associatedResourceTree->FindNode(GetResourcePath());
if (d->node != -1)
{
d->isFile = !associatedResourceTree->IsDir(d->node);
if (d->isFile)
{
d->data = d->associatedResourceTree->GetData(d->node, &d->size);
}
}
}
ModuleResource::~ModuleResource()
{
if (!d->ref.Deref())
delete d;
}
ModuleResource& ModuleResource::operator =(const ModuleResource& resource)
{
ModuleResourcePrivate* curr_d = d;
d = resource.d;
d->ref.Ref();
if (!curr_d->ref.Deref())
delete curr_d;
return *this;
}
bool ModuleResource::operator <(const ModuleResource& resource) const
{
return this->GetResourcePath() < resource.GetResourcePath();
}
bool ModuleResource::operator ==(const ModuleResource& resource) const
{
return d->associatedResourceTree == resource.d->associatedResourceTree &&
this->GetResourcePath() == resource.GetResourcePath();
}
bool ModuleResource::operator !=(const ModuleResource &resource) const
{
return !(*this == resource);
}
bool ModuleResource::IsValid() const
{
return d->associatedResourceTree && d->associatedResourceTree->IsValid() && d->node > -1;
}
ModuleResource::operator bool() const
{
return IsValid();
}
std::string ModuleResource::GetName() const
{
return d->fileName;
}
std::string ModuleResource::GetPath() const
{
return d->path;
}
std::string ModuleResource::GetResourcePath() const
{
return d->filePath;
}
std::string ModuleResource::GetBaseName() const
{
return d->fileName.substr(0, d->fileName.find_first_of('.'));
}
std::string ModuleResource::GetCompleteBaseName() const
{
return d->fileName.substr(0, d->fileName.find_last_of('.'));
}
std::string ModuleResource::GetSuffix() const
{
std::size_t index = d->fileName.find_last_of('.');
return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string("");
}
std::string ModuleResource::GetCompleteSuffix() const
{
std::size_t index = d->fileName.find_first_of('.');
return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string("");
}
bool ModuleResource::IsDir() const
{
return !d->isFile;
}
bool ModuleResource::IsFile() const
{
return d->isFile;
}
std::vector<std::string> ModuleResource::GetChildren() const
{
if (d->isFile || !IsValid()) return d->children;
if (!d->children.empty()) return d->children;
for (std::size_t i = 0; i < d->resourceTrees.size(); ++i)
{
d->resourceTrees[i]->GetChildren(d->node, d->children);
}
return d->children;
}
int ModuleResource::GetSize() const
{
return d->size;
}
const unsigned char* ModuleResource::GetData() const
{
if (!IsValid()) return NULL;
return d->data;
}
std::size_t ModuleResource::Hash() const
{
using namespace US_HASH_FUNCTION_NAMESPACE;
return US_HASH_FUNCTION(std::string, this->GetResourcePath());
}
US_END_NAMESPACE
US_USE_NAMESPACE
std::ostream& operator<<(std::ostream& os, const ModuleResource& resource)
{
return os << resource.GetResourcePath();
}
<commit_msg>Use correct node index for each resource tree when retreiving children.<commit_after>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "usModuleResource.h"
#include "usAtomicInt_p.h"
#include "usModuleResourceTree_p.h"
#include <string>
US_BEGIN_NAMESPACE
class ModuleResourcePrivate
{
public:
ModuleResourcePrivate()
: associatedResourceTree(NULL)
, node(-1)
, size(0)
, data(NULL)
, isFile(false)
, ref(1)
{}
std::string fileName;
std::string path;
std::string filePath;
std::vector<ModuleResourceTree*> resourceTrees;
const ModuleResourceTree* associatedResourceTree;
int node;
int32_t size;
const unsigned char* data;
mutable std::vector<std::string> children;
bool isFile;
/**
* Reference count for implicitly shared private implementation.
*/
AtomicInt ref;
};
ModuleResource::ModuleResource()
: d(new ModuleResourcePrivate)
{
}
ModuleResource::ModuleResource(const ModuleResource &resource)
: d(resource.d)
{
d->ref.Ref();
}
ModuleResource::ModuleResource(const std::string& _file, ModuleResourceTree* associatedResourceTree,
const std::vector<ModuleResourceTree*>& resourceTrees)
: d(new ModuleResourcePrivate)
{
d->resourceTrees = resourceTrees;
d->associatedResourceTree = associatedResourceTree;
std::string file = _file;
if (file.empty()) file = "/";
if (file[0] != '/') file = std::string("/") + file;
std::size_t index = file.find_last_of('/');
if (index < file.size()-1)
{
d->fileName = file.substr(index+1);
}
std::string rawPath = file.substr(0,index+1);
// remove duplicate /
std::string::value_type lastChar = 0;
for (std::size_t i = 0; i < rawPath.size(); ++i)
{
if (rawPath[i] == '/' && lastChar == '/')
{
continue;
}
lastChar = rawPath[i];
d->path.push_back(lastChar);
}
d->filePath = d->path + d->fileName;
d->node = d->associatedResourceTree->FindNode(GetResourcePath());
if (d->node != -1)
{
d->isFile = !associatedResourceTree->IsDir(d->node);
if (d->isFile)
{
d->data = d->associatedResourceTree->GetData(d->node, &d->size);
}
}
}
ModuleResource::~ModuleResource()
{
if (!d->ref.Deref())
delete d;
}
ModuleResource& ModuleResource::operator =(const ModuleResource& resource)
{
ModuleResourcePrivate* curr_d = d;
d = resource.d;
d->ref.Ref();
if (!curr_d->ref.Deref())
delete curr_d;
return *this;
}
bool ModuleResource::operator <(const ModuleResource& resource) const
{
return this->GetResourcePath() < resource.GetResourcePath();
}
bool ModuleResource::operator ==(const ModuleResource& resource) const
{
return d->associatedResourceTree == resource.d->associatedResourceTree &&
this->GetResourcePath() == resource.GetResourcePath();
}
bool ModuleResource::operator !=(const ModuleResource &resource) const
{
return !(*this == resource);
}
bool ModuleResource::IsValid() const
{
return d->associatedResourceTree && d->associatedResourceTree->IsValid() && d->node > -1;
}
ModuleResource::operator bool() const
{
return IsValid();
}
std::string ModuleResource::GetName() const
{
return d->fileName;
}
std::string ModuleResource::GetPath() const
{
return d->path;
}
std::string ModuleResource::GetResourcePath() const
{
return d->filePath;
}
std::string ModuleResource::GetBaseName() const
{
return d->fileName.substr(0, d->fileName.find_first_of('.'));
}
std::string ModuleResource::GetCompleteBaseName() const
{
return d->fileName.substr(0, d->fileName.find_last_of('.'));
}
std::string ModuleResource::GetSuffix() const
{
std::size_t index = d->fileName.find_last_of('.');
return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string("");
}
std::string ModuleResource::GetCompleteSuffix() const
{
std::size_t index = d->fileName.find_first_of('.');
return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string("");
}
bool ModuleResource::IsDir() const
{
return !d->isFile;
}
bool ModuleResource::IsFile() const
{
return d->isFile;
}
std::vector<std::string> ModuleResource::GetChildren() const
{
if (d->isFile || !IsValid()) return d->children;
if (!d->children.empty()) return d->children;
bool indexPastAssociatedResTree = false;
for (std::size_t i = 0; i < d->resourceTrees.size(); ++i)
{
if (d->resourceTrees[i] == d->associatedResourceTree)
{
indexPastAssociatedResTree = true;
d->associatedResourceTree->GetChildren(d->node, d->children);
}
else if (indexPastAssociatedResTree)
{
int nodeIndex = d->resourceTrees[i]->FindNode(GetPath());
if (nodeIndex > -1)
{
d->resourceTrees[i]->GetChildren(d->node, d->children);
}
}
}
return d->children;
}
int ModuleResource::GetSize() const
{
return d->size;
}
const unsigned char* ModuleResource::GetData() const
{
if (!IsValid()) return NULL;
return d->data;
}
std::size_t ModuleResource::Hash() const
{
using namespace US_HASH_FUNCTION_NAMESPACE;
return US_HASH_FUNCTION(std::string, this->GetResourcePath());
}
US_END_NAMESPACE
US_USE_NAMESPACE
std::ostream& operator<<(std::ostream& os, const ModuleResource& resource)
{
return os << resource.GetResourcePath();
}
<|endoftext|> |
<commit_before>#include <nex/math/boundingsphere.h>
#include <nex/math/boundingbox.h>
namespace nx
{
BoundingSphere::BoundingSphere() :
center(vec3f()),
radius(0.0f)
{ }
BoundingSphere::BoundingSphere(const vec3f center, const float radius) :
center(center),
radius(radius)
{ }
inline BoundingSphere BoundingSphere::createMerged(const BoundingSphere& original, const BoundingSphere& additional)
{
const vec3f result = additional.center - original.center;
const float resultLength = result.length();
const float radiusA = original.radius;
const float radiusB = additional.radius;
if (radiusA + radiusB >= resultLength)
{
if (radiusA - radiusB >= resultLength)
return original;
if (radiusB - radiusA >= resultLength)
return additional;
}
const vec3f oneOverLength = result * (1.0f / resultLength);
const float minRad = min(-radiusA, resultLength - radiusB);
const float maxRad = ((max(radiusA, resultLength + radiusB) - minRad) * 0.5f);
BoundingSphere resultSphere;
resultSphere.center = original.center + oneOverLength * (maxRad + minRad);
resultSphere.radius = maxRad;
return resultSphere;
}
inline BoundingSphere BoundingSphere::createFromBoundingBox(const BoundingBox& box)
{
BoundingSphere boundingSphere;
boundingSphere.center = vec3f::lerp(box.min, box.max, 0.5f);
const float resultRadius = vec3f::distance(box.max, box.max);
boundingSphere.radius = resultRadius * 0.5f;
return boundingSphere;
}
} //namespace nx
<commit_msg>Implemented the create from points method in the bounding sphere class.<commit_after>#include <nex/math/boundingsphere.h>
#include <nex/math/boundingbox.h>
namespace nx
{
BoundingSphere::BoundingSphere() :
center(vec3f()),
radius(0.0f)
{ }
BoundingSphere::BoundingSphere(const vec3f center, const float radius) :
center(center),
radius(radius)
{ }
inline BoundingSphere BoundingSphere::createMerged(const BoundingSphere& original, const BoundingSphere& additional)
{
const vec3f result = additional.center - original.center;
const float resultLength = result.length();
const float radiusA = original.radius;
const float radiusB = additional.radius;
if (radiusA + radiusB >= resultLength)
{
if (radiusA - radiusB >= resultLength)
return original;
if (radiusB - radiusA >= resultLength)
return additional;
}
const vec3f oneOverLength = result * (1.0f / resultLength);
const float minRad = min(-radiusA, resultLength - radiusB);
const float maxRad = ((max(radiusA, resultLength + radiusB) - minRad) * 0.5f);
BoundingSphere resultSphere;
resultSphere.center = original.center + oneOverLength * (maxRad + minRad);
resultSphere.radius = maxRad;
return resultSphere;
}
inline BoundingSphere BoundingSphere::createFromBoundingBox(const BoundingBox& box)
{
BoundingSphere boundingSphere;
boundingSphere.center = vec3f::lerp(box.min, box.max, 0.5f);
const float resultRadius = vec3f::distance(box.max, box.max);
boundingSphere.radius = resultRadius * 0.5f;
return boundingSphere;
}
inline BoundingSphere BoundingSphere::createFromPoints(std::vector<vec3f> points)
{
if (points.size() == 0)
return BoundingSphere();
vec3f current = points.at(0);
//min y
vec3f resultA = current;
//max y
vec3f resultB = current;
//min x
vec3f resultC = current;
//max x
vec3f resultD = current;
//min z
vec3f resultF = current;
//max z
vec3f resultG = current;
for (auto& point : points)
{
if (point.x < resultG.x)
resultG = point;
if (point.x > resultF.x)
resultF = point;
if (point.y < resultD.y)
resultD = point;
if (point.y > resultC.y)
resultC = point;
if (point.z < resultB.z)
resultB = point;
if (point.z > resultA.z)
resultA = point;
}
float result1 = vec3f::distance(resultF, resultG);
float result2 = vec3f::distance(resultC, resultD);
float result3 = vec3f::distance(resultA, resultB);
vec3f resultCenter;
float resultRadius;
if (result1 > result2)
{
if (result1 > result3)
{
resultCenter = vec3f::lerp(resultF, resultG, 0.5f);
resultRadius = result1 * 0.5f;
}
else
{
resultRadius = result3 * 0.5f;
resultCenter = vec3f::lerp(resultA, resultB, 0.5f);
}
}
else if (result2 > result3)
{
resultCenter = vec3f::lerp(resultC, resultD, 0.5f);
resultRadius = result2 * 0.5f;
}
else
{
resultCenter = vec3f::lerp(resultA, resultB, 0.5f);
resultRadius = result3 * 0.5f;
}
for (auto& pomint : points)
{
vec3f calc;
calc.x = pomint.x - resultCenter.x;
calc.y = pomint.y - resultCenter.y;
calc.z = pomint.z - resultCenter.z;
float length = calc.length();
if (length > resultRadius)
{
resultRadius = ((resultRadius + length) * 0.5f);
resultCenter += (1.0f - resultRadius / length) * calc;
}
}
BoundingSphere boundingSphere;
boundingSphere.center = resultCenter;
boundingSphere.radius = resultRadius;
return boundingSphere;
}
} //namespace nx
<|endoftext|> |
<commit_before>#include <QtCore>
#include <QtWidgets>
#include <random>
#include "window.h"
#include "soundchanges.h"
#include "highlighter.h"
#include "affixerdialog.h"
Window::Window()
{
QWidget *mainwidget = new QWidget;
setCentralWidget(mainwidget);
m_layout = new QHBoxLayout;
m_leftlayout = new QVBoxLayout;
m_midlayout = new QVBoxLayout;
m_syllableseperatorlayout = new QHBoxLayout;
mainwidget->setLayout(m_layout);
QFont font("Courier", 10);
font.setFixedPitch(true);
m_categories = new QPlainTextEdit;
m_categories->setFont(font);
m_leftlayout->addWidget(m_categories, 2);
m_rewrites = new QPlainTextEdit;
m_leftlayout->addWidget(m_rewrites, 1);
m_layout->addLayout(m_leftlayout);
m_rules = new QPlainTextEdit;
m_rules->setFont(font);
m_highlighter = new Highlighter(m_rules->document());
m_layout->addWidget(m_rules);
m_words = new QPlainTextEdit;
m_layout->addWidget(m_words);
m_apply = new QPushButton("Apply");
m_midlayout->addWidget(m_apply);
m_showChangedWords = new QCheckBox("Show changed words");
m_showChangedWords->setChecked(true);
m_midlayout->addWidget(m_showChangedWords);
m_reportChanges = new QCheckBox("Report which rules apply");
m_midlayout->addWidget(m_reportChanges);
m_doBackwards = new QCheckBox("Rewrite on output");
m_doBackwards->setChecked(true);
m_midlayout->addWidget(m_doBackwards);
const QChar arrow(0x2192);
m_formatgroup = new QGroupBox("Output format");
m_plainformat = new QRadioButton("output > gloss");
m_arrowformat = new QRadioButton(QString("input %1 output").arg(arrow));
m_squareinputformat = new QRadioButton("output [input]");
m_squareglossformat = new QRadioButton("output [gloss]");
m_arrowglossformat = new QRadioButton(QString("input %1 output [gloss]").arg(arrow));
QVBoxLayout *fbox = new QVBoxLayout;
fbox->addWidget(m_plainformat);
fbox->addWidget(m_arrowformat);
fbox->addWidget(m_squareinputformat);
fbox->addWidget(m_squareglossformat);
fbox->addWidget(m_arrowglossformat);
m_plainformat->setChecked(true);
m_formatgroup->setLayout(fbox);
m_midlayout->addWidget(m_formatgroup);
m_midlayout->addStretch();
m_syllabify = new QLineEdit;
m_midlayout->addWidget(m_syllabify);
m_syllableseperatorlabel = new QLabel("Syllable seperator: ");
m_syllableseperatorlayout->addWidget(m_syllableseperatorlabel);
m_syllableseperator = new QLineEdit;
m_syllableseperator->setMaxLength(1);
// make width equal to 1em so it's clear the textbox only accepts 1 char
// we multiply by 2 because we also need some space on the side
m_syllableseperator->setFixedWidth(m_syllableseperator->fontMetrics().width('M') * 2);
m_syllableseperator->setText("-");
m_syllableseperator->setAlignment(Qt::AlignCenter);
m_syllableseperatorlayout->addWidget(m_syllableseperator);
m_syllableseperatorlayout->addStretch();
m_syllableseperatorlayout->setSpacing(0);
m_midlayout->addLayout(m_syllableseperatorlayout);
m_layout->addLayout(m_midlayout);
m_results = new QTextEdit;
m_results->setReadOnly(true);
m_layout->addWidget(m_results);
m_categorieslist = new QMap<QChar, QList<QChar>>();
connect(m_categories, &QPlainTextEdit::textChanged, this, &Window::UpdateCategories);
connect(m_apply, &QPushButton::clicked, this, &Window::DoSoundChanges);
fileMenu = menuBar()->addMenu("File");
fileMenu->addAction("Open .esc file", this, &Window::OpenEsc);
fileMenu->addAction("Open .lex file", this, &Window::OpenLex);
fileMenu->addAction("Save .esc file", this, &Window::SaveEsc);
fileMenu->addAction("Save .lex file", this, &Window::SaveLex);
toolsMenu = menuBar()->addMenu("Tools");
toolsMenu->addAction("Affixer", this, &Window::LaunchAffixer);
helpMenu = menuBar()->addMenu("Help");
helpMenu->addAction("About", this, &Window::LaunchAboutBox);
helpMenu->addAction("About Qt", this, &Window::LaunchAboutQt);
}
void Window::DoSoundChanges()
{
QStringList result;
QString syllabifyregexp(SoundChanges::PreProcessRegexp(m_syllabify->text(), *m_categorieslist));
QString report;
for (QString word : m_words->toPlainText().split('\n', QString::SkipEmptyParts))
{
QString gloss = "";
bool hasGloss = false;
if (word.split('>').length() > 1)
{
hasGloss = true;
QStringList split = word.split('>');
gloss = split.at(1);
word = split.at(0);
}
QString changed = "";
for (QString subword : word.split(' ', QString::SkipEmptyParts))
{
QString subchanged = ApplyRewrite(subword);
for (QString change : ApplyRewrite(m_rules->toPlainText()).split('\n', QString::SkipEmptyParts))
{
QStringList splitchange = change.replace(QRegularExpression(R"(\*.*)"), "").split(' ', QString::SkipEmptyParts);
if (splitchange.length() == 0) continue;
QString _change;
int prob = 100;
if (splitchange.length() > 1)
{
_change = splitchange.at(1);
switch (splitchange.at(0).at(0).toLatin1())
{
case 'x':
subchanged = SoundChanges::Syllabify(syllabifyregexp, subchanged, m_syllableseperator->text().at(0));
case '?':
bool ok;
int _prob = QString(splitchange.at(0).mid(1)).toInt(&ok);
if (ok)
{
prob = _prob;
}
}
}
else _change = splitchange.at(0);
QString before = subchanged;
subchanged = SoundChanges::ApplyChange(subchanged, _change, *m_categorieslist, prob);
subchanged.remove(m_syllableseperator->text().at(0));
if (subchanged != before)
report.append(QString("<b>%1</b> changed <b>%2</b> to <b>%3</b><br/>").arg(_change, before, subchanged));
}
if (m_doBackwards->isChecked()) subchanged = ApplyRewrite(subchanged, true);
if (m_showChangedWords->isChecked() && subchanged != subword) subchanged = QString("<b>").append(subchanged).append("</b>");
if (changed.length() == 0) changed = subchanged;
else changed += ' ' + subchanged;
}
changed = FormatOutput(word.trimmed(), changed.trimmed(), gloss.trimmed(), hasGloss);
result.append(changed);
}
m_results->setHtml(result.join("<br/>"));
if (m_reportChanges->isChecked())
{
QMessageBox *msgBox = new QMessageBox(this);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->setText(report);
msgBox->setWindowModality(Qt::NonModal);
msgBox->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
msgBox->show();
}
}
void Window::UpdateCategories()
{
bool first = true;
for (QString line : ApplyRewrite(m_categories->toPlainText()).split('\n', QString::SkipEmptyParts))
{
if (!QRegularExpression("^.=.+$").match(line).hasMatch()) continue;
QStringList parts = line.split("=");
if (first) { m_categorieslist = new QMap<QChar, QList<QChar>>; first = false; }
QList<QChar> phonemes;
for (QChar c : parts.at(1))
{
if (m_categorieslist->contains(c)) phonemes.append(m_categorieslist->value(c));
else phonemes.append(c);
}
m_categorieslist->insert(parts.at(0).at(0), phonemes);
}
QString regexp("");
first = true;
for (QChar key : m_categorieslist->keys())
{
if (!first) regexp.append("|");
if (first) first = false;
regexp.append(key);
}
m_highlighter->MakeHighlightingRules(regexp);
m_highlighter->rehighlight();
}
QString Window::ApplyRewrite(QString str, bool backwards)
{
QString rewritten = str;
QString s = m_rewrites->toPlainText();
for (QString line : m_rewrites->toPlainText().split('\n', QString::SkipEmptyParts))
{
QStringList parts = line.split('>');
if (parts.length() != 2) continue;
if (backwards) rewritten.replace(parts.at(1), parts.at(0));
else rewritten.replace(parts.at(0), parts.at(1));
}
return rewritten;
}
QString Window::FormatOutput(QString in, QString out, QString gloss, bool hasGloss)
{
const QChar arrow(0x2192);
if (m_plainformat->isChecked())
{
if (hasGloss) return QString("%1 > %2").arg(out, gloss);
else return out;
}
else if (m_arrowformat->isChecked())
{
return QString("%1 %2 %3").arg(in, arrow, out);
}
else if (m_squareinputformat->isChecked())
{
return QString("%1 [%2]").arg(out, in);
}
else if (m_squareglossformat->isChecked())
{
if (hasGloss) return QString("%1 [%2]").arg(out, gloss);
else return out;
}
else if (m_arrowglossformat->isChecked())
{
if (hasGloss) return QString("%1 %2 %3 [%4]").arg(in, arrow, out, gloss);
else return QString("%1 %2 %3").arg(in, arrow, out);
}
return out;
}
void Window::LaunchAffixer()
{
AffixerDialog *affixer = new AffixerDialog;
affixer->show();
connect(affixer, &AffixerDialog::addText, this, &Window::AddFromAffixer);
}
void Window::AddFromAffixer(QStringList words, AffixerDialog::PlaceToAdd placeToAdd)
{
QString textToAdd = words.join('\n');
switch (placeToAdd)
{
case AffixerDialog::PlaceToAdd::AddToStart:
m_words->setPlainText(textToAdd.append('\n').append(m_words->toPlainText()));
break;
case AffixerDialog::PlaceToAdd::AddToEnd:
m_words->setPlainText(m_words->toPlainText().append('\n').append(textToAdd));
break;
case AffixerDialog::PlaceToAdd::AddAtCursor:
m_words->insertPlainText(QString('\n').append(textToAdd).append('\n'));
break;
case AffixerDialog::PlaceToAdd::Overwrite:
m_words->setPlainText(textToAdd);
break;
}
}
void Window::OpenEsc()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA Files (*.esc);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream in(&file);
in.setCodec("UTF-8");
QStringList cats, rules, rews;
while (!in.atEnd())
{
QString line = in.readLine();
if (line.contains('=')) cats.append(line);
else if (line.contains('>') && !line.contains('/')) rews.append(line);
else rules.append(line);
}
m_categories->setPlainText(cats.join('\n'));
m_rules->setPlainText(rules.join('\n'));
m_rewrites->setPlainText(rews.join('\n'));
file.close();
}
void Window::OpenLex()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA word files (*.lex);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream in(&file);
in.setCodec("UTF-8");
QStringList words;
while (!in.atEnd()) words.append(in.readLine());
m_words->setPlainText(words.join('\n'));
file.close();
}
void Window::SaveEsc()
{
QString fileName = QFileDialog::getSaveFileName(this, "Open .esc File", QString(), "exSCA Files (*.esc);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream out(&file);
out.setCodec("UTF-8");
out << m_categories->toPlainText().toUtf8() << endl;
out << m_rewrites ->toPlainText().toUtf8() << endl;
out << m_rules ->toPlainText().toUtf8() << endl;
file.close();
}
void Window::SaveLex()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA word files (*.lex);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream out(&file);
out.setCodec("UTF-8");
for (QString word : m_words->toPlainText().split('\n'))
{
out << word.toUtf8() << endl;
}
file.close();
}
void Window::LaunchAboutBox()
{
QMessageBox::about(this, "About exSCA", "<b>exSCA</b><br/>Version 2.0.0<br/>Copyright © Brad Neimann 2017");
}
void Window::LaunchAboutQt()
{
QMessageBox::aboutQt(this, "About Qt");
}<commit_msg>Uncheck window.cpp by default<commit_after>#include <QtCore>
#include <QtWidgets>
#include <random>
#include "window.h"
#include "soundchanges.h"
#include "highlighter.h"
#include "affixerdialog.h"
Window::Window()
{
QWidget *mainwidget = new QWidget;
setCentralWidget(mainwidget);
m_layout = new QHBoxLayout;
m_leftlayout = new QVBoxLayout;
m_midlayout = new QVBoxLayout;
m_syllableseperatorlayout = new QHBoxLayout;
mainwidget->setLayout(m_layout);
QFont font("Courier", 10);
font.setFixedPitch(true);
m_categories = new QPlainTextEdit;
m_categories->setFont(font);
m_leftlayout->addWidget(m_categories, 2);
m_rewrites = new QPlainTextEdit;
m_leftlayout->addWidget(m_rewrites, 1);
m_layout->addLayout(m_leftlayout);
m_rules = new QPlainTextEdit;
m_rules->setFont(font);
m_highlighter = new Highlighter(m_rules->document());
m_layout->addWidget(m_rules);
m_words = new QPlainTextEdit;
m_layout->addWidget(m_words);
m_apply = new QPushButton("Apply");
m_midlayout->addWidget(m_apply);
m_showChangedWords = new QCheckBox("Show changed words");
m_showChangedWords->setChecked(true);
m_midlayout->addWidget(m_showChangedWords);
m_reportChanges = new QCheckBox("Report which rules apply");
m_midlayout->addWidget(m_reportChanges);
m_doBackwards = new QCheckBox("Rewrite on output");
m_midlayout->addWidget(m_doBackwards);
const QChar arrow(0x2192);
m_formatgroup = new QGroupBox("Output format");
m_plainformat = new QRadioButton("output > gloss");
m_arrowformat = new QRadioButton(QString("input %1 output").arg(arrow));
m_squareinputformat = new QRadioButton("output [input]");
m_squareglossformat = new QRadioButton("output [gloss]");
m_arrowglossformat = new QRadioButton(QString("input %1 output [gloss]").arg(arrow));
QVBoxLayout *fbox = new QVBoxLayout;
fbox->addWidget(m_plainformat);
fbox->addWidget(m_arrowformat);
fbox->addWidget(m_squareinputformat);
fbox->addWidget(m_squareglossformat);
fbox->addWidget(m_arrowglossformat);
m_plainformat->setChecked(true);
m_formatgroup->setLayout(fbox);
m_midlayout->addWidget(m_formatgroup);
m_midlayout->addStretch();
m_syllabify = new QLineEdit;
m_midlayout->addWidget(m_syllabify);
m_syllableseperatorlabel = new QLabel("Syllable seperator: ");
m_syllableseperatorlayout->addWidget(m_syllableseperatorlabel);
m_syllableseperator = new QLineEdit;
m_syllableseperator->setMaxLength(1);
// make width equal to 1em so it's clear the textbox only accepts 1 char
// we multiply by 2 because we also need some space on the side
m_syllableseperator->setFixedWidth(m_syllableseperator->fontMetrics().width('M') * 2);
m_syllableseperator->setText("-");
m_syllableseperator->setAlignment(Qt::AlignCenter);
m_syllableseperatorlayout->addWidget(m_syllableseperator);
m_syllableseperatorlayout->addStretch();
m_syllableseperatorlayout->setSpacing(0);
m_midlayout->addLayout(m_syllableseperatorlayout);
m_layout->addLayout(m_midlayout);
m_results = new QTextEdit;
m_results->setReadOnly(true);
m_layout->addWidget(m_results);
m_categorieslist = new QMap<QChar, QList<QChar>>();
connect(m_categories, &QPlainTextEdit::textChanged, this, &Window::UpdateCategories);
connect(m_apply, &QPushButton::clicked, this, &Window::DoSoundChanges);
fileMenu = menuBar()->addMenu("File");
fileMenu->addAction("Open .esc file", this, &Window::OpenEsc);
fileMenu->addAction("Open .lex file", this, &Window::OpenLex);
fileMenu->addAction("Save .esc file", this, &Window::SaveEsc);
fileMenu->addAction("Save .lex file", this, &Window::SaveLex);
toolsMenu = menuBar()->addMenu("Tools");
toolsMenu->addAction("Affixer", this, &Window::LaunchAffixer);
helpMenu = menuBar()->addMenu("Help");
helpMenu->addAction("About", this, &Window::LaunchAboutBox);
helpMenu->addAction("About Qt", this, &Window::LaunchAboutQt);
}
void Window::DoSoundChanges()
{
QStringList result;
QString syllabifyregexp(SoundChanges::PreProcessRegexp(m_syllabify->text(), *m_categorieslist));
QString report;
for (QString word : m_words->toPlainText().split('\n', QString::SkipEmptyParts))
{
QString gloss = "";
bool hasGloss = false;
if (word.split('>').length() > 1)
{
hasGloss = true;
QStringList split = word.split('>');
gloss = split.at(1);
word = split.at(0);
}
QString changed = "";
for (QString subword : word.split(' ', QString::SkipEmptyParts))
{
QString subchanged = ApplyRewrite(subword);
for (QString change : ApplyRewrite(m_rules->toPlainText()).split('\n', QString::SkipEmptyParts))
{
QStringList splitchange = change.replace(QRegularExpression(R"(\*.*)"), "").split(' ', QString::SkipEmptyParts);
if (splitchange.length() == 0) continue;
QString _change;
int prob = 100;
if (splitchange.length() > 1)
{
_change = splitchange.at(1);
switch (splitchange.at(0).at(0).toLatin1())
{
case 'x':
subchanged = SoundChanges::Syllabify(syllabifyregexp, subchanged, m_syllableseperator->text().at(0));
case '?':
bool ok;
int _prob = QString(splitchange.at(0).mid(1)).toInt(&ok);
if (ok)
{
prob = _prob;
}
}
}
else _change = splitchange.at(0);
QString before = subchanged;
subchanged = SoundChanges::ApplyChange(subchanged, _change, *m_categorieslist, prob);
subchanged.remove(m_syllableseperator->text().at(0));
if (subchanged != before)
report.append(QString("<b>%1</b> changed <b>%2</b> to <b>%3</b><br/>").arg(_change, before, subchanged));
}
if (m_doBackwards->isChecked()) subchanged = ApplyRewrite(subchanged, true);
if (m_showChangedWords->isChecked() && subchanged != subword) subchanged = QString("<b>").append(subchanged).append("</b>");
if (changed.length() == 0) changed = subchanged;
else changed += ' ' + subchanged;
}
changed = FormatOutput(word.trimmed(), changed.trimmed(), gloss.trimmed(), hasGloss);
result.append(changed);
}
m_results->setHtml(result.join("<br/>"));
if (m_reportChanges->isChecked())
{
QMessageBox *msgBox = new QMessageBox(this);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->setText(report);
msgBox->setWindowModality(Qt::NonModal);
msgBox->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
msgBox->show();
}
}
void Window::UpdateCategories()
{
bool first = true;
for (QString line : ApplyRewrite(m_categories->toPlainText()).split('\n', QString::SkipEmptyParts))
{
if (!QRegularExpression("^.=.+$").match(line).hasMatch()) continue;
QStringList parts = line.split("=");
if (first) { m_categorieslist = new QMap<QChar, QList<QChar>>; first = false; }
QList<QChar> phonemes;
for (QChar c : parts.at(1))
{
if (m_categorieslist->contains(c)) phonemes.append(m_categorieslist->value(c));
else phonemes.append(c);
}
m_categorieslist->insert(parts.at(0).at(0), phonemes);
}
QString regexp("");
first = true;
for (QChar key : m_categorieslist->keys())
{
if (!first) regexp.append("|");
if (first) first = false;
regexp.append(key);
}
m_highlighter->MakeHighlightingRules(regexp);
m_highlighter->rehighlight();
}
QString Window::ApplyRewrite(QString str, bool backwards)
{
QString rewritten = str;
QString s = m_rewrites->toPlainText();
for (QString line : m_rewrites->toPlainText().split('\n', QString::SkipEmptyParts))
{
QStringList parts = line.split('>');
if (parts.length() != 2) continue;
if (backwards) rewritten.replace(parts.at(1), parts.at(0));
else rewritten.replace(parts.at(0), parts.at(1));
}
return rewritten;
}
QString Window::FormatOutput(QString in, QString out, QString gloss, bool hasGloss)
{
const QChar arrow(0x2192);
if (m_plainformat->isChecked())
{
if (hasGloss) return QString("%1 > %2").arg(out, gloss);
else return out;
}
else if (m_arrowformat->isChecked())
{
return QString("%1 %2 %3").arg(in, arrow, out);
}
else if (m_squareinputformat->isChecked())
{
return QString("%1 [%2]").arg(out, in);
}
else if (m_squareglossformat->isChecked())
{
if (hasGloss) return QString("%1 [%2]").arg(out, gloss);
else return out;
}
else if (m_arrowglossformat->isChecked())
{
if (hasGloss) return QString("%1 %2 %3 [%4]").arg(in, arrow, out, gloss);
else return QString("%1 %2 %3").arg(in, arrow, out);
}
return out;
}
void Window::LaunchAffixer()
{
AffixerDialog *affixer = new AffixerDialog;
affixer->show();
connect(affixer, &AffixerDialog::addText, this, &Window::AddFromAffixer);
}
void Window::AddFromAffixer(QStringList words, AffixerDialog::PlaceToAdd placeToAdd)
{
QString textToAdd = words.join('\n');
switch (placeToAdd)
{
case AffixerDialog::PlaceToAdd::AddToStart:
m_words->setPlainText(textToAdd.append('\n').append(m_words->toPlainText()));
break;
case AffixerDialog::PlaceToAdd::AddToEnd:
m_words->setPlainText(m_words->toPlainText().append('\n').append(textToAdd));
break;
case AffixerDialog::PlaceToAdd::AddAtCursor:
m_words->insertPlainText(QString('\n').append(textToAdd).append('\n'));
break;
case AffixerDialog::PlaceToAdd::Overwrite:
m_words->setPlainText(textToAdd);
break;
}
}
void Window::OpenEsc()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA Files (*.esc);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream in(&file);
in.setCodec("UTF-8");
QStringList cats, rules, rews;
while (!in.atEnd())
{
QString line = in.readLine();
if (line.contains('=')) cats.append(line);
else if (line.contains('>') && !line.contains('/')) rews.append(line);
else rules.append(line);
}
m_categories->setPlainText(cats.join('\n'));
m_rules->setPlainText(rules.join('\n'));
m_rewrites->setPlainText(rews.join('\n'));
file.close();
}
void Window::OpenLex()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA word files (*.lex);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream in(&file);
in.setCodec("UTF-8");
QStringList words;
while (!in.atEnd()) words.append(in.readLine());
m_words->setPlainText(words.join('\n'));
file.close();
}
void Window::SaveEsc()
{
QString fileName = QFileDialog::getSaveFileName(this, "Open .esc File", QString(), "exSCA Files (*.esc);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream out(&file);
out.setCodec("UTF-8");
out << m_categories->toPlainText().toUtf8() << endl;
out << m_rewrites ->toPlainText().toUtf8() << endl;
out << m_rules ->toPlainText().toUtf8() << endl;
file.close();
}
void Window::SaveLex()
{
QString fileName = QFileDialog::getOpenFileName(this, "Open .esc File", QString(), "exSCA word files (*.lex);;All files (*.*)");
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, "Could Not Open File", "The file could not be opened");
return;
}
QTextStream out(&file);
out.setCodec("UTF-8");
for (QString word : m_words->toPlainText().split('\n'))
{
out << word.toUtf8() << endl;
}
file.close();
}
void Window::LaunchAboutBox()
{
QMessageBox::about(this, "About exSCA", "<b>exSCA</b><br/>Version 2.0.0<br/>Copyright © Brad Neimann 2017");
}
void Window::LaunchAboutQt()
{
QMessageBox::aboutQt(this, "About Qt");
}<|endoftext|> |
<commit_before>#include "window.h"
#include <QtGui>
Window::Window() :
_glWidget(this),
_qtimer(this) {
connect(&_qtimer, SIGNAL(timeout()), this, SLOT(updateFPS()));
_qtimer.start(1000);
QHBoxLayout *mainLayout = new QHBoxLayout(this);
mainLayout->addWidget(&_glWidget);
setLayout(mainLayout);
}
void Window::updateFPS() {
setWindowTitle(QString("Particles (%1 FPS)").arg((int)_glWidget.getFPS()));
}
<commit_msg>Fixed includes<commit_after>#include "window.h"
#include <QtGui>
#include <QHBoxLayout>
Window::Window() :
_glWidget(this),
_qtimer(this) {
connect(&_qtimer, SIGNAL(timeout()), this, SLOT(updateFPS()));
_qtimer.start(1000);
QHBoxLayout *mainLayout = new QHBoxLayout(this);
mainLayout->addWidget(&_glWidget);
setLayout(mainLayout);
}
void Window::updateFPS() {
setWindowTitle(QString("Particles (%1 FPS)").arg((int)_glWidget.getFPS()));
}
<|endoftext|> |
<commit_before>#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
//#include "easywsclient/easywsclient.hpp"
//#include "easywsclient/easywsclient.cpp"
#include <assert.h>
#include <stdio.h>
#include <string>
#include <sstream>
//using easywsclient::WebSocket;
//static WebSocket::pointer ws = NULL;
#define PI 3.14159
#define contrastValue 2.7
#define erodeValue 10
#define dilateValue 20
#define epsilonValue 10
const cv::Size imgSize(128, 72);
cv::Mat erodeKernel = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*erodeValue + 1, 2*erodeValue+1 ),
cv::Point( erodeValue, erodeValue ) );
cv::Mat dilateKernel = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilateValue + 1, 2*dilateValue+1 ),
cv::Point( dilateValue, dilateValue ) );
//cv::Scalar red(0, 0, 255);
cv::Mat red(imgSize, CV_8UC3, cv::Scalar(0,0,255));
void processVideo(cv::Mat, cv::Mat&);
std::vector<std::vector<cv::Point> > findBiggestThree(cv::Mat);
double getAngleFromLargestLine(std::vector<std::vector<cv::Point> >);
/*void handle_message(const std::string & message)
{
printf(">>> %s\n", message.c_str());
if (message == "world") { ws->close(); }
}*/
int main(/*int argc, char** argv*/)
{
cv::VideoCapture cap(0);
if(!cap.isOpened()) {
std::cout << "yo this didn't open" << std::endl;
return -1;
}
// ws = WebSocket::from_url("ws://localhost:8126/foo", std::string());
//assert(ws);
//cv::namedWindow("Horizon Tracker",1);
for(;;)
{
cv::Mat frame;
// frame = cv::imread(argv[1]);
cap >> frame;
cv::resize(frame, frame, imgSize, 0, 0, cv::INTER_CUBIC);
cv::Mat canny;
processVideo(frame, canny);
// imshow("Horizon Tracker", canny);
// std::cout << "broken canny" << std::endl;
std::vector<std::vector<cv::Point> > biggestThreeContours = findBiggestThree(canny);
std::cout << "broken contours" << std::endl;
if(biggestThreeContours.size() >= 3) {
double angleFromLine = getAngleFromLargestLine(biggestThreeContours);
std::cout << angleFromLine << std::endl;
}
std::cout << "hi" << std::endl;
//std::ostringstream strs;
//strs << angleFromLine;
// ws->send(strs.str());
//while (ws->getReadyState() != WebSocket::CLOSED) {
// ws->poll();
// ws->dispatch(handle_message);
//std::cout << "i'm stuck" << std::endl;
//}
///int keyCode = cv::waitKey(0);
// if(keyCode >= 0 && keyCode != 255) {
// std::cout << keyCode << std::endl;
// break;
//}/
}
//delete ws;
return 0;
}
void processVideo(cv::Mat src, cv::Mat& dst)
{
src.convertTo(dst, -1, contrastValue, 0);
std::cout << "contrast" << std::endl;
cv::medianBlur(dst, dst, 3);
std::cout << "blur" << std::endl;
cv::Sobel(dst, dst, -1, 1, 1, 7);
cv::inRange(dst, red, red, dst);
cv::dilate(dst, dst, dilateKernel);
cv::erode(dst, dst, erodeKernel, cv::Point(-1, -1), 2);
cv::Canny(dst, dst, 0, 255, 3);
std::cout << "canny" << std::endl;
}
std::vector<std::vector<cv::Point> > findBiggestThree(cv::Mat cannyMatrix)
{
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
std::vector<cv::Point> emptyContour;
std::vector<std::vector<cv::Point> > biggestThree (3, emptyContour);
cv::findContours(cannyMatrix, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cv::Point(0,0));
for (int i = 0; i < contours.size(); i++)
{
if(contours[i].size() > biggestThree[2].size())
{
if(contours[i].size() > biggestThree[1].size())
{
if(contours[i].size() > biggestThree[0].size())
{
biggestThree.insert(biggestThree.begin()+0, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
else {
biggestThree.insert(biggestThree.begin()+1, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
}
else {
biggestThree.insert(biggestThree.begin()+2, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
}
}
return biggestThree;
}
double getAngleFromLargestLine(std::vector<std::vector<cv::Point> > biggestThree)
{
std::vector<std::vector<cv::Point> > approximatedContours;
approximatedContours.resize(3);
cv::approxPolyDP(biggestThree[0], approximatedContours[0], epsilonValue, false);
std::cout << "1" << std::endl;
cv::approxPolyDP(biggestThree[1], approximatedContours[1], epsilonValue, false);
std::cout << "2" << std::endl;
cv::approxPolyDP(biggestThree[2], approximatedContours[2], epsilonValue, false);
std::cout << "3" << std::endl;
//cv::drawContours(dst, biggestThree, -1, cv::Scalar(100, 100, 100), 2);
int largestDistance = 0;
cv::Point startPoint;
cv::Point endPoint;
for(int x = 0; x < 3; x++)
{
for(int i = 0; i < approximatedContours[x].size()-1; i++)
{
int distance = (approximatedContours[x][i].x - approximatedContours[x][i+1].x) + (approximatedContours[x][i].y - approximatedContours[x][i+1].y);
if (distance > largestDistance)
{
largestDistance = distance;
startPoint.x = approximatedContours[x][i].x;
startPoint.y = approximatedContours[x][i].y;
endPoint.x = approximatedContours[x][i+1].x;
endPoint.y = approximatedContours[x][i+1].y;
}
}
}
double opposite = endPoint.y-startPoint.y;
double adjacent = endPoint.x-startPoint.x;
double angle = -atan(opposite/adjacent)*180/PI;
return angle;
}
<commit_msg>added for loop<commit_after>#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
//#include "easywsclient/easywsclient.hpp"
//#include "easywsclient/easywsclient.cpp"
#include <assert.h>
#include <stdio.h>
#include <string>
#include <sstream>
//using easywsclient::WebSocket;
//static WebSocket::pointer ws = NULL;
#define PI 3.14159
#define contrastValue 2.7
#define erodeValue 10
#define dilateValue 20
#define epsilonValue 10
const cv::Size imgSize(128, 72);
cv::Mat erodeKernel = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*erodeValue + 1, 2*erodeValue+1 ),
cv::Point( erodeValue, erodeValue ) );
cv::Mat dilateKernel = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilateValue + 1, 2*dilateValue+1 ),
cv::Point( dilateValue, dilateValue ) );
//cv::Scalar red(0, 0, 255);
cv::Mat red(imgSize, CV_8UC3, cv::Scalar(0,0,255));
void processVideo(cv::Mat, cv::Mat&);
std::vector<std::vector<cv::Point> > findBiggestThree(cv::Mat);
double getAngleFromLargestLine(std::vector<std::vector<cv::Point> >);
/*void handle_message(const std::string & message)
{
printf(">>> %s\n", message.c_str());
if (message == "world") { ws->close(); }
}*/
int main(/*int argc, char** argv*/)
{
cv::VideoCapture cap(0);
if(!cap.isOpened()) {
std::cout << "yo this didn't open" << std::endl;
return -1;
}
// ws = WebSocket::from_url("ws://localhost:8126/foo", std::string());
//assert(ws);
//cv::namedWindow("Horizon Tracker",1);
for(;;)
{
cv::Mat frame;
// frame = cv::imread(argv[1]);
cap >> frame;
cv::resize(frame, frame, imgSize, 0, 0, cv::INTER_CUBIC);
cv::Mat canny;
processVideo(frame, canny);
// imshow("Horizon Tracker", canny);
// std::cout << "broken canny" << std::endl;
std::vector<std::vector<cv::Point> > biggestThreeContours = findBiggestThree(canny);
std::cout << "broken contours" << std::endl;
double angleFromLine = getAngleFromLargestLine(biggestThreeContours);
std::cout << angleFromLine << std::endl;
std::cout << "hi" << std::endl;
//std::ostringstream strs;
//strs << angleFromLine;
// ws->send(strs.str());
//while (ws->getReadyState() != WebSocket::CLOSED) {
// ws->poll();
// ws->dispatch(handle_message);
//std::cout << "i'm stuck" << std::endl;
//}
///int keyCode = cv::waitKey(0);
// if(keyCode >= 0 && keyCode != 255) {
// std::cout << keyCode << std::endl;
// break;
//}/
}
//delete ws;
return 0;
}
void processVideo(cv::Mat src, cv::Mat& dst)
{
src.convertTo(dst, -1, contrastValue, 0);
std::cout << "contrast" << std::endl;
cv::medianBlur(dst, dst, 3);
std::cout << "blur" << std::endl;
cv::Sobel(dst, dst, -1, 1, 1, 7);
cv::inRange(dst, red, red, dst);
cv::dilate(dst, dst, dilateKernel);
cv::erode(dst, dst, erodeKernel, cv::Point(-1, -1), 2);
cv::Canny(dst, dst, 0, 255, 3);
std::cout << "canny" << std::endl;
}
std::vector<std::vector<cv::Point> > findBiggestThree(cv::Mat cannyMatrix)
{
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
std::vector<cv::Point> emptyContour;
std::vector<std::vector<cv::Point> > biggestThree (3, emptyContour);
cv::findContours(cannyMatrix, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cv::Point(0,0));
for (int i = 0; i < contours.size(); i++)
{
if(contours[i].size() > biggestThree[2].size())
{
if(contours[i].size() > biggestThree[1].size())
{
if(contours[i].size() > biggestThree[0].size())
{
biggestThree.insert(biggestThree.begin()+0, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
else {
biggestThree.insert(biggestThree.begin()+1, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
}
else {
biggestThree.insert(biggestThree.begin()+2, contours[i]);
biggestThree.erase(biggestThree.begin()+4);
}
}
}
return biggestThree;
}
double getAngleFromLargestLine(std::vector<std::vector<cv::Point> > biggestThree)
{
std::vector<std::vector<cv::Point> > approximatedContours;
approximatedContours.resize(3);
for(int i = 0; i < 3; i++) {
if(biggestThree[i].size() > 0 ) {
cv::approxPolyDP(biggestThree[i], approximatedContours[i], epsilonValue, false);
std::cout << i << std::endl;
}
}
//cv::drawContours(dst, biggestThree, -1, cv::Scalar(100, 100, 100), 2);
int largestDistance = 0;
cv::Point startPoint;
cv::Point endPoint;
for(int x = 0; x < 3; x++)
{
for(int i = 0; i < approximatedContours[x].size()-1; i++)
{
int distance = (approximatedContours[x][i].x - approximatedContours[x][i+1].x) + (approximatedContours[x][i].y - approximatedContours[x][i+1].y);
if (distance > largestDistance)
{
largestDistance = distance;
startPoint.x = approximatedContours[x][i].x;
startPoint.y = approximatedContours[x][i].y;
endPoint.x = approximatedContours[x][i+1].x;
endPoint.y = approximatedContours[x][i+1].y;
}
}
}
double opposite = endPoint.y-startPoint.y;
double adjacent = endPoint.x-startPoint.x;
double angle = -atan(opposite/adjacent)*180/PI;
return angle;
}
<|endoftext|> |
<commit_before>#include "osg/Impostor"
#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool Impostor_readLocalData(Object& obj, Input& fr);
bool Impostor_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_ImpostorProxy
(
new osg::Impostor,
"Impostor",
"Object Node Impostor LOD Group",
&Impostor_readLocalData,
&Impostor_writeLocalData
);
bool Impostor_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
Impostor& impostor = static_cast<Impostor&>(obj);
if (fr.matchSequence("ImpostorThreshold %f"))
{
float threshold;
fr[1].getFloat(threshold);
impostor.setImpostorThreshold(threshold);
iteratorAdvanced = true;
fr+=2;
}
return iteratorAdvanced;
}
bool Impostor_writeLocalData(const Object& obj, Output& fw)
{
const Impostor& impostor = static_cast<const Impostor&>(obj);
fw.indent() << "ImpostorThreshold "<< impostor.getImpostorThreshold() << std::endl;
return true;
}
<commit_msg>Removed Impostor.cpp<commit_after><|endoftext|> |
<commit_before>#include <fstream>
#include <array>
#include <assert.h>
#include <list>
#include <threadpool.h>
#include <iostream>
#include "Waiter.h"
#include "DoubleXY.h"
#include "GLstate.h"
// Multiplar av 4, because fu
int SIZEX = 1000;
int SIZEY = 600;
static unsigned int FPSMAX = 60;
static const int NRTHREADS = 64;
static std::mutex fliplock;
static const char *GOSPERGLIDER = "...................................."
"...................................."
"...................................."
"...................................."
".......................O.O.........."
".....................O...O.........."
".............O.......O.............."
"............OOOO....O....O........OO"
"...........OO.O.O....O............OO"
"OO........OOO.O..O...O...O.........."
"OO.........OO.O.O......O.O.........."
"............OOOO...................."
".............O......................";
static const char *BIGGLIDER = " OOO "
" O OOO "
" O O "
"OO O "
"O O O O "
"O OO "
" OO "
" O O O OO "
" O OO O "
" O O OO O "
" OO O OO O"
" O O "
" OOOO O O "
" O OO OOOO"
" O OO O "
" OO "
" O OOO "
" O O ";
static const char *RPENTOMINO = " OO"
"OO "
" O ";
static const char *SMALLBOOM = "OOO"
"O O"
"O O";
struct Board {
int sizex, sizey;
Board(int maxx, int maxy) : sizex(maxx), sizey(maxy) {}
std::vector<unsigned char> aliveactive =
std::vector<unsigned char>(sizex * sizey, 0);
std::vector<unsigned char> alivewait =
std::vector<unsigned char>(sizex * sizey, 0);
std::vector<unsigned char> savedstate =
std::vector<unsigned char>(sizex * sizey, 0);
ThreadPool pool;
void loaddefaults() {
input(GOSPERGLIDER, 36, 13, 10, 10);
input(RPENTOMINO, 3, 3, 300, 100);
input(RPENTOMINO, 3, 3, 100, 300);
input(BIGGLIDER, 18, 18, 330, 270);
input(SMALLBOOM, 3, 3, 255, 255);
}
void save() { savedstate = aliveactive; }
void load() { aliveactive = savedstate; }
bool safe_access(int x, int y) {
return (x >= 0 && y >= 0 && x < sizex && y < sizey);
}
bool aliveat(int x, int y) { return aliveactive[y * sizex + x] == 255; }
unsigned char action(int x, int y) {
if (x <= 0 || y <= 0 || x >= sizex - 1 || y >= sizey - 1) {
return 0;
}
int around = 0;
around += aliveat(x - 1, y - 1);
around += aliveat(x, y - 1);
around += aliveat(x + 1, y - 1);
around += aliveat(x - 1, y);
around += aliveat(x + 1, y);
around += aliveat(x - 1, y + 1);
around += aliveat(x, y + 1);
around += aliveat(x + 1, y + 1);
if (aliveat(x, y)) {
return around == 2 || around == 3 ? 255 : 0x7F;
} else {
if (around == 3) {
return 255;
} else {
return aliveactive[y * sizex + x] * 0.97;
}
}
}
void run() {
int each = sizey / NRTHREADS;
for (int i = 0; i < NRTHREADS; ++i) {
pool([=]() {
for (int y = i * each;
y < (i + 1) * each || ((i + 1) == NRTHREADS && y < sizey); y++) {
for (int x = 0; x < sizex; x++) {
alivewait[y * sizex + x] = action(x, y);
}
}
});
}
pool.wait_until_done();
swap(aliveactive, alivewait);
}
void letlive_scaled(DoubleXY &&f, WindowScale const &loc) {
loc.scaled_to_view(&f);
letlive(f.int_x(sizex), f.int_y(sizey));
}
void letdie_scaled(DoubleXY &&f, WindowScale const &loc) {
loc.scaled_to_view(&f);
letdie(f.int_x(sizex), f.int_y(sizey));
}
void letlive(int x, int y) {
if (safe_access(x, y)) {
aliveactive[y * sizex + x] = 255;
}
}
void letdie(int x, int y) {
if (safe_access(x, y)) {
aliveactive[y * sizex + x] = 0;
}
}
void input(const char *input, int width, int height, int xoffs, int yoffs) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++, input++) {
if (*input == 'O') {
letlive(x + xoffs, y + yoffs);
}
}
}
}
};
Board global_b(SIZEX, SIZEY);
std::vector<DoubleXY> line(int x0, int y0, int x1, int y1, int sizex, int sizey) {
std::vector<DoubleXY> ret;
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = (dx > dy ? dx : -dy) / 2;
int err2;
while (true) {
ret.emplace_back(x0, y0, sizex, sizey);
if (x0 == x1 && y0 == y1)
break;
err2 = err;
if (err2 > -dx) {
err -= dy;
x0 += sx;
}
if (err2 < dy) {
err += dx;
y0 += sy;
}
}
return ret;
}
int main(int argc, const char *argv[]) {
{
if (argc == 3) {
SIZEX = atoi(argv[1]);
SIZEY = atoi(argv[2]);
if (!SIZEX || !SIZEY) {
std::cout << "Incorrect input parameters, atoi didn't work on: '"
<< argv[1] << "', '" << argv[2] << "'" << std::endl;
return 1;
}
}
}
GLstate state;
bool active = 1;
bool running = 1;
std::thread boardthread([&active, &running]() {
Waiter runwaiter(1000 / FPSMAX);
while (running) {
if (active) {
std::unique_lock<std::mutex> f(fliplock);
global_b.run();
}
runwaiter.set_ms_tick_length(1000 / FPSMAX);
runwaiter.wait_if_fast();
}
});
int lastx = 0, lasty = 0;
bool lbdown = 0;
bool rbdown = 0;
int windowsizex = SIZEX, windowsizey = SIZEY;
SDL_Event event;
Waiter waiter(16);
while (true) {
{
std::unique_lock<std::mutex> f(fliplock);
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
running = 0;
boardthread.join();
return 0;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_q:
running = 0;
boardthread.join();
return 0;
case SDLK_SPACE:
active = !active;
break;
case SDLK_i:
if (FPSMAX > 2 && FPSMAX <= 10) {
FPSMAX--;
} else if (FPSMAX > 10) {
FPSMAX = FPSMAX * 8 / 10;
}
break;
case SDLK_o:
if (FPSMAX <= 10) {
FPSMAX++;
} else if (FPSMAX > 10) {
FPSMAX = FPSMAX * 12 / 10;
}
break;
case SDLK_d:
for (auto &i : global_b.aliveactive) {
i = 0;
}
break;
case SDLK_r:
global_b.loaddefaults();
break;
case SDLK_f:
{
std::ofstream logfile;
logfile.open("log");
if (!logfile) {
assert(0 && "logfile error");
return 0;
}
for (int y = 0; y < SIZEY; y++) {
for (int x = 0; x < SIZEX; x++) {
logfile << (global_b.aliveactive[y * SIZEX + x] == 255 ? 'O'
: ' ');
}
logfile << std::endl;
}
}
break;
case SDLK_s:
global_b.save();
break;
case SDLK_l:
global_b.load();
break;
case SDLK_PERIOD:
global_b.run();
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
lastx = event.button.x;
lasty = event.button.y;
switch (event.button.button) {
case SDL_BUTTON_LEFT:
global_b.letlive_scaled(DoubleXY(lastx, lasty, windowsizex, windowsizey), state.loc);
lbdown = 1;
break;
case SDL_BUTTON_RIGHT:
global_b.letdie_scaled(DoubleXY(lastx, lasty, windowsizex, windowsizey), state.loc);
rbdown = 1;
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
lbdown = 0;
break;
case SDL_BUTTON_RIGHT:
rbdown = 0;
break;
}
break;
case SDL_MOUSEMOTION:
if (lbdown || rbdown) {
int currx = event.motion.x;
int curry = event.motion.y;
auto xys = line(lastx, lasty, currx, curry, windowsizex, windowsizey);
lastx = currx;
lasty = curry;
for (DoubleXY xy : xys) {
if (lbdown) {
global_b.letlive_scaled(std::move(xy), state.loc);
} else if (rbdown) {
global_b.letdie_scaled(std::move(xy), state.loc);
}
}
}
break;
case SDL_MOUSEWHEEL:
{
int x, y;
SDL_GetMouseState(&x, &y);
DoubleXY f(x, y, windowsizex, windowsizey);
if (event.wheel.y > 0) {
state.zoomin(f.x, f.y);
} else {
state.zoomout(f.x, f.y);
}
}
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
windowsizex = event.window.data1;
windowsizey = event.window.data2;
}
break;
}
}
}
waiter.wait_if_fast();
// draw allways
state.draw(global_b.aliveactive.data(), SIZEX, SIZEY);
}
return 0;
}
<commit_msg>Draw on entire window after resize<commit_after>#include <fstream>
#include <array>
#include <assert.h>
#include <list>
#include <threadpool.h>
#include <iostream>
#include "Waiter.h"
#include "DoubleXY.h"
#include "GLstate.h"
// Multiplar av 4, because fu
int SIZEX = 1000;
int SIZEY = 600;
static unsigned int FPSMAX = 60;
static const int NRTHREADS = 64;
static std::mutex fliplock;
static const char *GOSPERGLIDER = "...................................."
"...................................."
"...................................."
"...................................."
".......................O.O.........."
".....................O...O.........."
".............O.......O.............."
"............OOOO....O....O........OO"
"...........OO.O.O....O............OO"
"OO........OOO.O..O...O...O.........."
"OO.........OO.O.O......O.O.........."
"............OOOO...................."
".............O......................";
static const char *BIGGLIDER = " OOO "
" O OOO "
" O O "
"OO O "
"O O O O "
"O OO "
" OO "
" O O O OO "
" O OO O "
" O O OO O "
" OO O OO O"
" O O "
" OOOO O O "
" O OO OOOO"
" O OO O "
" OO "
" O OOO "
" O O ";
static const char *RPENTOMINO = " OO"
"OO "
" O ";
static const char *SMALLBOOM = "OOO"
"O O"
"O O";
struct Board {
int sizex, sizey;
Board(int maxx, int maxy) : sizex(maxx), sizey(maxy) {}
std::vector<unsigned char> aliveactive =
std::vector<unsigned char>(sizex * sizey, 0);
std::vector<unsigned char> alivewait =
std::vector<unsigned char>(sizex * sizey, 0);
std::vector<unsigned char> savedstate =
std::vector<unsigned char>(sizex * sizey, 0);
ThreadPool pool;
void loaddefaults() {
input(GOSPERGLIDER, 36, 13, 10, 10);
input(RPENTOMINO, 3, 3, 300, 100);
input(RPENTOMINO, 3, 3, 100, 300);
input(BIGGLIDER, 18, 18, 330, 270);
input(SMALLBOOM, 3, 3, 255, 255);
}
void save() { savedstate = aliveactive; }
void load() { aliveactive = savedstate; }
bool safe_access(int x, int y) {
return (x >= 0 && y >= 0 && x < sizex && y < sizey);
}
bool aliveat(int x, int y) { return aliveactive[y * sizex + x] == 255; }
unsigned char action(int x, int y) {
if (x <= 0 || y <= 0 || x >= sizex - 1 || y >= sizey - 1) {
return 0;
}
int around = 0;
around += aliveat(x - 1, y - 1);
around += aliveat(x, y - 1);
around += aliveat(x + 1, y - 1);
around += aliveat(x - 1, y);
around += aliveat(x + 1, y);
around += aliveat(x - 1, y + 1);
around += aliveat(x, y + 1);
around += aliveat(x + 1, y + 1);
if (aliveat(x, y)) {
return around == 2 || around == 3 ? 255 : 0x7F;
} else {
if (around == 3) {
return 255;
} else {
return aliveactive[y * sizex + x] * 0.97;
}
}
}
void run() {
int each = sizey / NRTHREADS;
for (int i = 0; i < NRTHREADS; ++i) {
pool([=]() {
for (int y = i * each;
y < (i + 1) * each || ((i + 1) == NRTHREADS && y < sizey); y++) {
for (int x = 0; x < sizex; x++) {
alivewait[y * sizex + x] = action(x, y);
}
}
});
}
pool.wait_until_done();
swap(aliveactive, alivewait);
}
void letlive_scaled(DoubleXY &&f, WindowScale const &loc) {
loc.scaled_to_view(&f);
letlive(f.int_x(sizex), f.int_y(sizey));
}
void letdie_scaled(DoubleXY &&f, WindowScale const &loc) {
loc.scaled_to_view(&f);
letdie(f.int_x(sizex), f.int_y(sizey));
}
void letlive(int x, int y) {
if (safe_access(x, y)) {
aliveactive[y * sizex + x] = 255;
}
}
void letdie(int x, int y) {
if (safe_access(x, y)) {
aliveactive[y * sizex + x] = 0;
}
}
void input(const char *input, int width, int height, int xoffs, int yoffs) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++, input++) {
if (*input == 'O') {
letlive(x + xoffs, y + yoffs);
}
}
}
}
};
Board global_b(SIZEX, SIZEY);
std::vector<DoubleXY> line(int x0, int y0, int x1, int y1, int sizex, int sizey) {
std::vector<DoubleXY> ret;
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = (dx > dy ? dx : -dy) / 2;
int err2;
while (true) {
ret.emplace_back(x0, y0, sizex, sizey);
if (x0 == x1 && y0 == y1)
break;
err2 = err;
if (err2 > -dx) {
err -= dy;
x0 += sx;
}
if (err2 < dy) {
err += dx;
y0 += sy;
}
}
return ret;
}
int main(int argc, const char *argv[]) {
{
if (argc == 3) {
SIZEX = atoi(argv[1]);
SIZEY = atoi(argv[2]);
if (!SIZEX || !SIZEY) {
std::cout << "Incorrect input parameters, atoi didn't work on: '"
<< argv[1] << "', '" << argv[2] << "'" << std::endl;
return 1;
}
}
}
GLstate state;
bool active = 1;
bool running = 1;
std::thread boardthread([&active, &running]() {
Waiter runwaiter(1000 / FPSMAX);
while (running) {
if (active) {
std::unique_lock<std::mutex> f(fliplock);
global_b.run();
}
runwaiter.set_ms_tick_length(1000 / FPSMAX);
runwaiter.wait_if_fast();
}
});
int lastx = 0, lasty = 0;
bool lbdown = 0;
bool rbdown = 0;
int windowsizex = SIZEX, windowsizey = SIZEY;
SDL_Event event;
Waiter waiter(16);
while (true) {
{
std::unique_lock<std::mutex> f(fliplock);
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
running = 0;
boardthread.join();
return 0;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_q:
running = 0;
boardthread.join();
return 0;
case SDLK_SPACE:
active = !active;
break;
case SDLK_i:
if (FPSMAX > 2 && FPSMAX <= 10) {
FPSMAX--;
} else if (FPSMAX > 10) {
FPSMAX = FPSMAX * 8 / 10;
}
break;
case SDLK_o:
if (FPSMAX <= 10) {
FPSMAX++;
} else if (FPSMAX > 10) {
FPSMAX = FPSMAX * 12 / 10;
}
break;
case SDLK_d:
for (auto &i : global_b.aliveactive) {
i = 0;
}
break;
case SDLK_r:
global_b.loaddefaults();
break;
case SDLK_f:
{
std::ofstream logfile;
logfile.open("log");
if (!logfile) {
assert(0 && "logfile error");
return 0;
}
for (int y = 0; y < SIZEY; y++) {
for (int x = 0; x < SIZEX; x++) {
logfile << (global_b.aliveactive[y * SIZEX + x] == 255 ? 'O'
: ' ');
}
logfile << std::endl;
}
}
break;
case SDLK_s:
global_b.save();
break;
case SDLK_l:
global_b.load();
break;
case SDLK_PERIOD:
global_b.run();
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
lastx = event.button.x;
lasty = event.button.y;
switch (event.button.button) {
case SDL_BUTTON_LEFT:
global_b.letlive_scaled(DoubleXY(lastx, lasty, windowsizex, windowsizey), state.loc);
lbdown = 1;
break;
case SDL_BUTTON_RIGHT:
global_b.letdie_scaled(DoubleXY(lastx, lasty, windowsizex, windowsizey), state.loc);
rbdown = 1;
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
lbdown = 0;
break;
case SDL_BUTTON_RIGHT:
rbdown = 0;
break;
}
break;
case SDL_MOUSEMOTION:
if (lbdown || rbdown) {
int currx = event.motion.x;
int curry = event.motion.y;
auto xys = line(lastx, lasty, currx, curry, windowsizex, windowsizey);
lastx = currx;
lasty = curry;
for (DoubleXY xy : xys) {
if (lbdown) {
global_b.letlive_scaled(std::move(xy), state.loc);
} else if (rbdown) {
global_b.letdie_scaled(std::move(xy), state.loc);
}
}
}
break;
case SDL_MOUSEWHEEL:
{
int x, y;
SDL_GetMouseState(&x, &y);
DoubleXY f(x, y, windowsizex, windowsizey);
if (event.wheel.y > 0) {
state.zoomin(f.x, f.y);
} else {
state.zoomout(f.x, f.y);
}
}
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
windowsizex = event.window.data1;
windowsizey = event.window.data2;
glViewport(0,0,windowsizex, windowsizey);
}
break;
}
}
}
waiter.wait_if_fast();
// draw allways
state.draw(global_b.aliveactive.data(), SIZEX, SIZEY);
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Standard base for most diffusion-dominated PKs, this combines both
domains/meshes of PKPhysicalBase and BDF methods of PKBDFBase.
------------------------------------------------------------------------- */
#ifndef AMANZI_PK_PHYSICAL_BDF_BASE_HH_
#define AMANZI_PK_PHYSICAL_BDF_BASE_HH_
#include "errors.hh"
#include "ResidualDebugger.hh"
#include "pk_default_base.hh"
#include "pk_bdf_base.hh"
#include "pk_physical_base.hh"
#include "Operator.hh"
namespace Amanzi {
class PKPhysicalBDFBase : public PKBDFBase, public PKPhysicalBase {
public:
PKPhysicalBDFBase(const Teuchos::RCP<Teuchos::ParameterList>& plist,
Teuchos::ParameterList& FElist,
const Teuchos::RCP<TreeVector>& solution) :
PKDefaultBase(plist, FElist, solution),
PKPhysicalBase(plist, FElist, solution),
PKBDFBase(plist, FElist, solution) {}
virtual void setup(const Teuchos::Ptr<State>& S);
// initialize. Note both BDFBase and PhysicalBase have initialize()
// methods, so we need a unique overrider.
virtual void initialize(const Teuchos::Ptr<State>& S);
// Default preconditioner is Picard
virtual int ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) {
*Pu = *u;
return 0;
}
// updates the preconditioner, default does nothing
virtual void UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) {}
// Default implementations of BDFFnBase methods.
// -- Compute a norm on u-du and return the result.
virtual double ErrorNorm(Teuchos::RCP<const TreeVector> u,
Teuchos::RCP<const TreeVector> du);
// -- Experimental approach -- calling this indicates that the time
// integration scheme is changing the value of the solution in
// state.
virtual void ChangedSolution();
virtual double BoundaryValue(const Teuchos::RCP<const Amanzi::CompositeVector>& solution, int face_id);
virtual void ApplyBoundaryConditions_(const Teuchos::Ptr<CompositeVector>& u);
// PC operator access
Teuchos::RCP<Operators::Operator> preconditioner() { return preconditioner_; }
// BC access
std::vector<int>& bc_markers() { return bc_markers_; }
std::vector<double>& bc_values() { return bc_values_; }
Teuchos::RCP<Operators::BCs> BCs() { return bc_; }
protected:
// PC
Teuchos::RCP<Operators::Operator> preconditioner_;
// BCs
std::vector<int> bc_markers_;
std::vector<double> bc_values_;
Teuchos::RCP<Operators::BCs> bc_;
// error criteria
Key conserved_key_;
Key cell_vol_key_;
double atol_, rtol_, fluxtol_;
};
} // namespace
#endif
<commit_msg>this need not be here<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon
Standard base for most diffusion-dominated PKs, this combines both
domains/meshes of PKPhysicalBase and BDF methods of PKBDFBase.
------------------------------------------------------------------------- */
#ifndef AMANZI_PK_PHYSICAL_BDF_BASE_HH_
#define AMANZI_PK_PHYSICAL_BDF_BASE_HH_
#include "errors.hh"
#include "pk_default_base.hh"
#include "pk_bdf_base.hh"
#include "pk_physical_base.hh"
#include "Operator.hh"
namespace Amanzi {
class PKPhysicalBDFBase : public PKBDFBase, public PKPhysicalBase {
public:
PKPhysicalBDFBase(const Teuchos::RCP<Teuchos::ParameterList>& plist,
Teuchos::ParameterList& FElist,
const Teuchos::RCP<TreeVector>& solution) :
PKDefaultBase(plist, FElist, solution),
PKPhysicalBase(plist, FElist, solution),
PKBDFBase(plist, FElist, solution) {}
virtual void setup(const Teuchos::Ptr<State>& S);
// initialize. Note both BDFBase and PhysicalBase have initialize()
// methods, so we need a unique overrider.
virtual void initialize(const Teuchos::Ptr<State>& S);
// Default preconditioner is Picard
virtual int ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) {
*Pu = *u;
return 0;
}
// updates the preconditioner, default does nothing
virtual void UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) {}
// Default implementations of BDFFnBase methods.
// -- Compute a norm on u-du and return the result.
virtual double ErrorNorm(Teuchos::RCP<const TreeVector> u,
Teuchos::RCP<const TreeVector> du);
// -- Experimental approach -- calling this indicates that the time
// integration scheme is changing the value of the solution in
// state.
virtual void ChangedSolution();
virtual double BoundaryValue(const Teuchos::RCP<const Amanzi::CompositeVector>& solution, int face_id);
virtual void ApplyBoundaryConditions_(const Teuchos::Ptr<CompositeVector>& u);
// PC operator access
Teuchos::RCP<Operators::Operator> preconditioner() { return preconditioner_; }
// BC access
std::vector<int>& bc_markers() { return bc_markers_; }
std::vector<double>& bc_values() { return bc_values_; }
Teuchos::RCP<Operators::BCs> BCs() { return bc_; }
protected:
// PC
Teuchos::RCP<Operators::Operator> preconditioner_;
// BCs
std::vector<int> bc_markers_;
std::vector<double> bc_values_;
Teuchos::RCP<Operators::BCs> bc_;
// error criteria
Key conserved_key_;
Key cell_vol_key_;
double atol_, rtol_, fluxtol_;
};
} // namespace
#endif
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FilledVectorNode.h"
#include "NodeDefinition.h"
#include "Image.h"
#include "DivNode.h"
#include "../base/ScopeTimer.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
using namespace std;
using namespace boost;
namespace avg {
NodeDefinition FilledVectorNode::createDefinition()
{
return NodeDefinition("filledvector")
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<UTF8String>("filltexhref", "", false,
offsetof(FilledVectorNode, m_FillTexHRef)))
.addArg(Arg<float>("fillopacity", 0, false,
offsetof(FilledVectorNode, m_FillOpacity)))
.addArg(Arg<string>("fillcolor", "FFFFFF", false,
offsetof(FilledVectorNode, m_sFillColorName)))
.addArg(Arg<glm::vec2>("filltexcoord1", glm::vec2(0,0), false,
offsetof(FilledVectorNode, m_FillTexCoord1)))
.addArg(Arg<glm::vec2>("filltexcoord2", glm::vec2(1,1), false,
offsetof(FilledVectorNode, m_FillTexCoord2)))
;
}
FilledVectorNode::FilledVectorNode(const ArgList& args)
: VectorNode(args),
m_pFillShape(new Shape(MaterialInfo(GL_REPEAT, GL_REPEAT, false)))
{
m_FillTexHRef = args.getArgVal<UTF8String>("filltexhref");
setFillTexHRef(m_FillTexHRef);
m_sFillColorName = args.getArgVal<string>("fillcolor");
m_FillColor = colorStringToColor(m_sFillColorName);
}
FilledVectorNode::~FilledVectorNode()
{
}
void FilledVectorNode::connectDisplay()
{
VectorNode::connectDisplay();
m_FillColor = colorStringToColor(m_sFillColorName);
m_pFillShape->moveToGPU();
m_OldOpacity = -1;
}
void FilledVectorNode::disconnect(bool bKill)
{
if (bKill) {
m_pFillShape->discard();
} else {
m_pFillShape->moveToCPU();
}
VectorNode::disconnect(bKill);
}
void FilledVectorNode::checkReload()
{
Node::checkReload(m_FillTexHRef, m_pFillShape->getImage());
if (getState() == Node::NS_CANRENDER) {
m_pFillShape->moveToGPU();
setDrawNeeded();
}
VectorNode::checkReload();
}
const UTF8String& FilledVectorNode::getFillTexHRef() const
{
return m_FillTexHRef;
}
void FilledVectorNode::setFillTexHRef(const UTF8String& href)
{
m_FillTexHRef = href;
checkReload();
setDrawNeeded();
}
void FilledVectorNode::setFillBitmap(BitmapPtr pBmp)
{
m_FillTexHRef = "";
m_pFillShape->setBitmap(pBmp);
setDrawNeeded();
}
const glm::vec2& FilledVectorNode::getFillTexCoord1() const
{
return m_FillTexCoord1;
}
void FilledVectorNode::setFillTexCoord1(const glm::vec2& pt)
{
m_FillTexCoord1 = pt;
setDrawNeeded();
}
const glm::vec2& FilledVectorNode::getFillTexCoord2() const
{
return m_FillTexCoord2;
}
void FilledVectorNode::setFillTexCoord2(const glm::vec2& pt)
{
m_FillTexCoord2 = pt;
setDrawNeeded();
}
float FilledVectorNode::getFillOpacity() const
{
return m_FillOpacity;
}
void FilledVectorNode::setFillOpacity(float opacity)
{
m_FillOpacity = opacity;
setDrawNeeded();
}
void FilledVectorNode::preRender(const VertexArrayPtr& pVA)
{
Node::preRender(pVA);
float curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
VertexDataPtr pShapeVD = m_pFillShape->getVertexData();
if (isDrawNeeded() || curOpacity != m_OldOpacity) {
pShapeVD->reset();
Pixel32 color = getFillColorVal();
calcFillVertexes(pShapeVD, color);
m_OldOpacity = curOpacity;
}
if (isVisible()) {
m_pFillShape->setVertexArray(pVA);
}
VectorNode::preRender(pVA);
}
static ProfilingZoneID RenderProfilingZone("FilledVectorNode::render");
void FilledVectorNode::render()
{
ScopeTimer Timer(RenderProfilingZone);
float curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
if (curOpacity > 0.01) {
m_pFillShape->draw(getParentTransform(), curOpacity);
}
VectorNode::render();
}
void FilledVectorNode::setFillColor(const string& sColor)
{
if (m_sFillColorName != sColor) {
m_sFillColorName = sColor;
m_FillColor = colorStringToColor(m_sFillColorName);
setDrawNeeded();
}
}
const string& FilledVectorNode::getFillColor() const
{
return m_sFillColorName;
}
Pixel32 FilledVectorNode::getFillColorVal() const
{
return m_FillColor;
}
glm::vec2 FilledVectorNode::calcFillTexCoord(const glm::vec2& pt, const glm::vec2& minPt,
const glm::vec2& maxPt)
{
glm::vec2 texPt;
texPt.x = (m_FillTexCoord2.x-m_FillTexCoord1.x)*(pt.x-minPt.x)/(maxPt.x-minPt.x)
+m_FillTexCoord1.x;
texPt.y = (m_FillTexCoord2.y-m_FillTexCoord1.y)*(pt.y-minPt.y)/(maxPt.y-minPt.y)
+m_FillTexCoord1.y;
return texPt;
}
bool FilledVectorNode::isVisible() const
{
return getActive() && (getEffectiveOpacity() > 0.01 ||
getParent()->getEffectiveOpacity()*m_FillOpacity > 0.01);
}
}
<commit_msg>vertexsubmit branch: Fixed FilledVectorNode::isVisible.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "FilledVectorNode.h"
#include "NodeDefinition.h"
#include "Image.h"
#include "DivNode.h"
#include "../base/ScopeTimer.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
using namespace std;
using namespace boost;
namespace avg {
NodeDefinition FilledVectorNode::createDefinition()
{
return NodeDefinition("filledvector")
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<UTF8String>("filltexhref", "", false,
offsetof(FilledVectorNode, m_FillTexHRef)))
.addArg(Arg<float>("fillopacity", 0, false,
offsetof(FilledVectorNode, m_FillOpacity)))
.addArg(Arg<string>("fillcolor", "FFFFFF", false,
offsetof(FilledVectorNode, m_sFillColorName)))
.addArg(Arg<glm::vec2>("filltexcoord1", glm::vec2(0,0), false,
offsetof(FilledVectorNode, m_FillTexCoord1)))
.addArg(Arg<glm::vec2>("filltexcoord2", glm::vec2(1,1), false,
offsetof(FilledVectorNode, m_FillTexCoord2)))
;
}
FilledVectorNode::FilledVectorNode(const ArgList& args)
: VectorNode(args),
m_pFillShape(new Shape(MaterialInfo(GL_REPEAT, GL_REPEAT, false)))
{
m_FillTexHRef = args.getArgVal<UTF8String>("filltexhref");
setFillTexHRef(m_FillTexHRef);
m_sFillColorName = args.getArgVal<string>("fillcolor");
m_FillColor = colorStringToColor(m_sFillColorName);
}
FilledVectorNode::~FilledVectorNode()
{
}
void FilledVectorNode::connectDisplay()
{
VectorNode::connectDisplay();
m_FillColor = colorStringToColor(m_sFillColorName);
m_pFillShape->moveToGPU();
m_OldOpacity = -1;
}
void FilledVectorNode::disconnect(bool bKill)
{
if (bKill) {
m_pFillShape->discard();
} else {
m_pFillShape->moveToCPU();
}
VectorNode::disconnect(bKill);
}
void FilledVectorNode::checkReload()
{
Node::checkReload(m_FillTexHRef, m_pFillShape->getImage());
if (getState() == Node::NS_CANRENDER) {
m_pFillShape->moveToGPU();
setDrawNeeded();
}
VectorNode::checkReload();
}
const UTF8String& FilledVectorNode::getFillTexHRef() const
{
return m_FillTexHRef;
}
void FilledVectorNode::setFillTexHRef(const UTF8String& href)
{
m_FillTexHRef = href;
checkReload();
setDrawNeeded();
}
void FilledVectorNode::setFillBitmap(BitmapPtr pBmp)
{
m_FillTexHRef = "";
m_pFillShape->setBitmap(pBmp);
setDrawNeeded();
}
const glm::vec2& FilledVectorNode::getFillTexCoord1() const
{
return m_FillTexCoord1;
}
void FilledVectorNode::setFillTexCoord1(const glm::vec2& pt)
{
m_FillTexCoord1 = pt;
setDrawNeeded();
}
const glm::vec2& FilledVectorNode::getFillTexCoord2() const
{
return m_FillTexCoord2;
}
void FilledVectorNode::setFillTexCoord2(const glm::vec2& pt)
{
m_FillTexCoord2 = pt;
setDrawNeeded();
}
float FilledVectorNode::getFillOpacity() const
{
return m_FillOpacity;
}
void FilledVectorNode::setFillOpacity(float opacity)
{
m_FillOpacity = opacity;
setDrawNeeded();
}
void FilledVectorNode::preRender(const VertexArrayPtr& pVA)
{
Node::preRender(pVA);
float curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
VertexDataPtr pShapeVD = m_pFillShape->getVertexData();
if (isDrawNeeded() || curOpacity != m_OldOpacity) {
pShapeVD->reset();
Pixel32 color = getFillColorVal();
calcFillVertexes(pShapeVD, color);
m_OldOpacity = curOpacity;
}
if (isVisible()) {
m_pFillShape->setVertexArray(pVA);
}
VectorNode::preRender(pVA);
}
static ProfilingZoneID RenderProfilingZone("FilledVectorNode::render");
void FilledVectorNode::render()
{
ScopeTimer Timer(RenderProfilingZone);
float curOpacity = getParent()->getEffectiveOpacity()*m_FillOpacity;
if (curOpacity > 0.01) {
m_pFillShape->draw(getParentTransform(), curOpacity);
}
VectorNode::render();
}
void FilledVectorNode::setFillColor(const string& sColor)
{
if (m_sFillColorName != sColor) {
m_sFillColorName = sColor;
m_FillColor = colorStringToColor(m_sFillColorName);
setDrawNeeded();
}
}
const string& FilledVectorNode::getFillColor() const
{
return m_sFillColorName;
}
Pixel32 FilledVectorNode::getFillColorVal() const
{
return m_FillColor;
}
glm::vec2 FilledVectorNode::calcFillTexCoord(const glm::vec2& pt, const glm::vec2& minPt,
const glm::vec2& maxPt)
{
glm::vec2 texPt;
texPt.x = (m_FillTexCoord2.x-m_FillTexCoord1.x)*(pt.x-minPt.x)/(maxPt.x-minPt.x)
+m_FillTexCoord1.x;
texPt.y = (m_FillTexCoord2.y-m_FillTexCoord1.y)*(pt.y-minPt.y)/(maxPt.y-minPt.y)
+m_FillTexCoord1.y;
return texPt;
}
bool FilledVectorNode::isVisible() const
{
return getEffectiveActive() && (getEffectiveOpacity() > 0.01 ||
getParent()->getEffectiveOpacity()*m_FillOpacity > 0.01);
}
}
<|endoftext|> |
<commit_before>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "../columns/InterColComm.hpp"
#include "../include/pv_common.h"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../io/BaseConnectionProbe.hpp"
#include "../layers/HyPerLayer.hpp"
#include "../utils/Timer.hpp"
#include "../weightinit/InitWeights.hpp"
#include <stdlib.h>
#ifdef PV_USE_OPENCL
#include "../arch/opencl/CLKernel.hpp"
#include "../arch/opencl/CLBuffer.hpp"
#endif
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class InitWeights;
class InitUniformRandomWeights;
class InitGaussianRandomWeights;
class InitSmartWeights;
class InitCocircWeights;
class BaseConnectionProbe;
class PVParams;
/**
* A HyPerConn identifies a connection between two layers
*/
class HyPerConn {
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename, InitWeights *weightInit);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, InitWeights *weightInit);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, const PVLayerCube * cube, int neighbor);
#ifdef PV_USE_OPENCL
virtual int deliverOpenCL(Publisher * pub);
#endif
virtual int checkpointRead(float *timef);
virtual int checkpointWrite();
virtual int insertProbe(BaseConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWeights(int axonId = 0);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(const char * filename);
virtual int writeWeights(PVPatch *** patches, int numPatches, const char * filename, float timef, bool last);
#ifdef OBSOLETE // Marked obsolete Nov 29, 2011.
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last, int arborId);
#endif // OBSOLETE_NBANDSFORARBORS
virtual int writeTextWeights(const char * filename, int k);
virtual int writeTextWeightsExtra(FILE * fd, int k, int arborID)
{return PV_SUCCESS;}
virtual int writePostSynapticWeights(float time, bool last);
#ifdef OBSOLETE // Marked obsolete Nov 29, 2011.
virtual int writePostSynapticWeights(float time, bool last, int axonID);
#endif // OBSOLETE_NBANDSFORARBORS
int readWeights(const char * filename);
virtual int correctPIndex(int patchIndex);
bool stochasticReleaseFlag;
int (*accumulateFunctionPointer)(int nk, float* RESTRICT v, float a, float* RESTRICT w);
// TODO make a get-method to return this.
virtual PVLayerCube * getPlasticityDecrement() {return NULL;}
inline const char * getName() {return name;}
inline HyPerCol * getParent() {return parent;}
inline HyPerLayer * getPre() {return pre;}
inline HyPerLayer * getPost() {return post;}
inline ChannelType getChannel() {return channel;}
inline InitWeights * getWeightInitializer() {return weightInitializer;}
void setDelay(int axonId, int delay);
inline int getDelay(int arborId = 0) {assert(arborId>=0 && arborId<numAxonalArborLists); return delays[arborId];}
virtual float minWeight(int arborId = 0) {return 0.0;}
virtual float maxWeight(int arborId = 0) {return wMax;}
inline int xPatchSize() {return nxp;}
inline int yPatchSize() {return nyp;}
inline int fPatchSize() {return nfp;}
inline int xPatchStride() {return sxp;}
inline int yPatchStride() {return syp;}
inline int fPatchStride() {return sfp;}
//arbor and weight patch related get/set methods:
inline PVPatch ** weights(int arborId = 0) {return wPatches[arborId];}
virtual PVPatch * getWeights(int kPre, int arborId);
inline PVPatch * getPlasticIncr(int kPre, int arborId) {return plasticityFlag ? dwPatches[arborId][kPre] : NULL;}
inline const PVPatchStrides * getPostExtStrides() {return &postExtStrides;}
inline const PVPatchStrides * getPostNonextStrides() {return &postNonextStrides;}
inline pvdata_t * getPatchDataStart(int arborId) {return wDataStart[arborId];}
inline void setPatchDataStart(int arborId, pvdata_t * pDataStart) {wDataStart[arborId]=pDataStart;}
inline pvdata_t * getPIncrDataStart(int arborId) {return dwDataStart[arborId];}
inline void setPIncrDataStart(int arborId, pvdata_t * pIncrStart) {dwDataStart[arborId]=pIncrStart;}
// inline PVAxonalArbor * axonalArbor(int kPre, int arborId)
// {return &axonalArborList[arborId][kPre];}
virtual int numWeightPatches();
virtual int numDataPatches();
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
inline pvdata_t * get_dWData(int kPre, int arborId) {return dwPatches[arborId][kPre]->data;}
inline pvdata_t * getGSynPatchStart(int kPre, int arborId) {return gSynPatchStart[arborId][kPre];}
inline size_t getAPostOffset(int kPre, int arborId) {return aPostOffset[arborId][kPre];} // {return axonalArbor(kPre,arborId)->offset;}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
virtual int setParams(PVParams * params /*, PVConnParams * p*/);
PVPatch *** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
virtual int initShrinkPatches();
virtual int shrinkPatches(int arborId);
int shrinkPatch(int kExt, int arborId);
bool getShrinkPatches_flag() {return shrinkPatches_flag;}
virtual int initNormalize();
int sumWeights(PVPatch * wp, double * sum, double * sum2, pvdata_t * maxVal);
int scaleWeights(PVPatch * wp, pvdata_t sum, pvdata_t sum2, pvdata_t maxVal);
virtual int checkNormalizeWeights(PVPatch * wp, float sum, float sigma2, float maxVal);
virtual int checkNormalizeArbor(PVPatch ** patches, int numPatches, int arborId);
virtual int normalizeWeights(PVPatch ** patches, int numPatches, int arborId);
virtual int kernelIndexToPatchIndex(int kernelIndex, int * kxPatchIndex = NULL,
int * kyPatchIndex = NULL, int * kfPatchIndex = NULL);
virtual int patchIndexToKernelIndex(int patchIndex, int * kxKernelIndex = NULL,
int * kyKernelIndex = NULL, int * kfKernelIndex = NULL);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
//these were moved to private to ensure use of get/set methods and made in 3D pointers:
//PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
//PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
private:
PVPatch *** wPatches; // list of weight patches, one set per arbor
// PVAxonalArbor ** axonalArborList; // list of axonal arbors for each presynaptic cell in extended layer
pvdata_t *** gSynPatchStart; // gSynPatchStart[arborId][kExt] is a pointer to the start of the patch in the post-synaptic GSyn buffer
size_t ** aPostOffset; // aPostOffset[arborId][kExt] is the index of the start of a patch into an extended post-synaptic layer
int * delays; // delays[arborId] is the delay in timesteps (not units of dt) of the arborId'th arbor
PVPatchStrides postExtStrides; // nx,ny,nf,sx,sy,sf for a patch mapping into an extended post-synaptic layer
PVPatchStrides postNonextStrides; // nx,ny,nf,sx,sy,sf for a patch mapping into a non-extended post-synaptic layer
pvdata_t ** wDataStart; //now that data for all patches are allocated to one continuous block of memory, this pointer saves the starting address of that array
pvdata_t ** dwDataStart; //now that data for all patches are allocated to one continuous block of memory, this pointer saves the starting address of that array
int defaultDelay; //added to save params file defined delay...
protected:
PVPatch *** wPostPatches; // post-synaptic linkage of weights
PVPatch *** dwPatches; // list of weight patches for storing changes to weights
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
ChannelType channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int sxp, syp, sfp; // stride in x,y,features
int numParams;
//PVConnParams * params;
float wMax;
float wMin;
int numProbes;
BaseConnectionProbe ** probes; // probes used to output data
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
bool writeCompressedWeights; // true=write weights with 8-bit precision;
// false=write weights with float precision
int fileType; // type ID for file written by PV::writeWeights
Timer * update_timer;
bool plasticityFlag;
bool normalize_flag;
float normalize_strength;
bool normalize_arbors_individually; // if true, each arbor is normalized individually, otherwise, arbors normalized together
bool normalize_max;
bool normalize_zero_offset;
float normalize_cutoff;
bool shrinkPatches_flag;
//This object handles calculating weights. All the initialize weights methods for all connection classes
//are being moved into subclasses of this object. The default root InitWeights class will create
//2D Gaussian weights. If weight initialization type isn't created in a way supported by Buildandrun,
//this class will try to read the weights from a file or will do a 2D Gaussian.
InitWeights *weightInitializer;
protected:
virtual int setPatchSize(const char * filename);
virtual int setPatchStrides();
virtual int checkPatchSize(int patchSize, int scalePre, int scalePost, char dim);
int calcPatchSize(int n, int kex,
int * kl, int * offset,
int * nxPatch, int * nyPatch,
int * dx, int * dy);
int patchSizeFromFile(const char * filename);
int initialize_base();
virtual int createArbors();
void createArborsOutOfMemory();
int constructWeights(const char * filename);
#ifdef OBSOLETE // Marked obsolete Oct 1, 2011. Made redundant by adding default value to weightInit argument of other initialize method
int initialize(const char * name, HyPerCol * hc, HyPerLayer * pre,
HyPerLayer * post, ChannelType channel, const char * filename);
#endif // OBSOLETE
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename,
InitWeights *weightInit=NULL);
virtual int initPlasticityPatches();
virtual PVPatch *** initializeWeights(PVPatch *** arbors, int numPatches,
const char * filename);
virtual InitWeights * handleMissingInitWeights(PVParams * params);
// virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
// int nyPatch, int nfPatch, int axonId);
// PVPatch ** createWeights(PVPatch ** patches, int axonId);
// virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
// int nyPatch, int nfPatch, int axonId);
virtual pvdata_t * createWeights(PVPatch *** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch, int axonId);
pvdata_t * createWeights(PVPatch *** patches, int axonId);
virtual pvdata_t * allocWeights(PVPatch *** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch, int axonId);
//PVPatch ** allocWeights(PVPatch ** patches);
virtual int checkPVPFileHeader(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors(int arborId);
char * checkpointFilename();
// following is overridden by KernelConn to set kernelPatches
//inline void setWPatches(PVPatch ** patches, int arborId) {wPatches[arborId]=patches;}
virtual int setWPatches(PVPatch ** patches, int arborId) {wPatches[arborId]=patches; return 0;}
virtual int setdWPatches(PVPatch ** patches, int arborId) {dwPatches[arborId]=patches; return 0;}
// inline void setArbor(PVAxonalArbor* arbor, int arborId) {axonalArborList[arborId]=arbor;}
virtual int calc_dW(int axonId = 0);
void connOutOfMemory(const char * funcname);
#ifdef PV_USE_OPENCL
virtual int initializeThreadBuffers(const char * kernelName);
virtual int initializeThreadKernels(const char * kernelName);
CLKernel * krRecvSyn; // CL kernel for layer recvSynapticInput call
cl_event evRecvSyn;
// OpenCL buffers
//
CLBuffer * clGSyn;
CLBuffer * clActivity;
CLBuffer ** clWeights;
// ids of OpenCL arguments that change
//
int clArgIdOffset;
int clArgIdWeights;
#endif
public:
// static member functions
//
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<commit_msg>Make HyPerConn::constructWeights virtual so that CloneKernelConn can override it<commit_after>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "../columns/InterColComm.hpp"
#include "../include/pv_common.h"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../io/BaseConnectionProbe.hpp"
#include "../layers/HyPerLayer.hpp"
#include "../utils/Timer.hpp"
#include "../weightinit/InitWeights.hpp"
#include <stdlib.h>
#ifdef PV_USE_OPENCL
#include "../arch/opencl/CLKernel.hpp"
#include "../arch/opencl/CLBuffer.hpp"
#endif
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class InitWeights;
class InitUniformRandomWeights;
class InitGaussianRandomWeights;
class InitSmartWeights;
class InitCocircWeights;
class BaseConnectionProbe;
class PVParams;
/**
* A HyPerConn identifies a connection between two layers
*/
class HyPerConn {
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename, InitWeights *weightInit);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, InitWeights *weightInit);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, const PVLayerCube * cube, int neighbor);
#ifdef PV_USE_OPENCL
virtual int deliverOpenCL(Publisher * pub);
#endif
virtual int checkpointRead(float *timef);
virtual int checkpointWrite();
virtual int insertProbe(BaseConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWeights(int axonId = 0);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(const char * filename);
virtual int writeWeights(PVPatch *** patches, int numPatches, const char * filename, float timef, bool last);
#ifdef OBSOLETE // Marked obsolete Nov 29, 2011.
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last, int arborId);
#endif // OBSOLETE_NBANDSFORARBORS
virtual int writeTextWeights(const char * filename, int k);
virtual int writeTextWeightsExtra(FILE * fd, int k, int arborID)
{return PV_SUCCESS;}
virtual int writePostSynapticWeights(float time, bool last);
#ifdef OBSOLETE // Marked obsolete Nov 29, 2011.
virtual int writePostSynapticWeights(float time, bool last, int axonID);
#endif // OBSOLETE_NBANDSFORARBORS
int readWeights(const char * filename);
virtual int correctPIndex(int patchIndex);
bool stochasticReleaseFlag;
int (*accumulateFunctionPointer)(int nk, float* RESTRICT v, float a, float* RESTRICT w);
// TODO make a get-method to return this.
virtual PVLayerCube * getPlasticityDecrement() {return NULL;}
inline const char * getName() {return name;}
inline HyPerCol * getParent() {return parent;}
inline HyPerLayer * getPre() {return pre;}
inline HyPerLayer * getPost() {return post;}
inline ChannelType getChannel() {return channel;}
inline InitWeights * getWeightInitializer() {return weightInitializer;}
void setDelay(int axonId, int delay);
inline int getDelay(int arborId = 0) {assert(arborId>=0 && arborId<numAxonalArborLists); return delays[arborId];}
virtual float minWeight(int arborId = 0) {return 0.0;}
virtual float maxWeight(int arborId = 0) {return wMax;}
inline int xPatchSize() {return nxp;}
inline int yPatchSize() {return nyp;}
inline int fPatchSize() {return nfp;}
inline int xPatchStride() {return sxp;}
inline int yPatchStride() {return syp;}
inline int fPatchStride() {return sfp;}
//arbor and weight patch related get/set methods:
inline PVPatch ** weights(int arborId = 0) {return wPatches[arborId];}
virtual PVPatch * getWeights(int kPre, int arborId);
inline PVPatch * getPlasticIncr(int kPre, int arborId) {return plasticityFlag ? dwPatches[arborId][kPre] : NULL;}
inline const PVPatchStrides * getPostExtStrides() {return &postExtStrides;}
inline const PVPatchStrides * getPostNonextStrides() {return &postNonextStrides;}
inline pvdata_t * getPatchDataStart(int arborId) {return wDataStart[arborId];}
inline void setPatchDataStart(int arborId, pvdata_t * pDataStart) {wDataStart[arborId]=pDataStart;}
inline pvdata_t * getPIncrDataStart(int arborId) {return dwDataStart[arborId];}
inline void setPIncrDataStart(int arborId, pvdata_t * pIncrStart) {dwDataStart[arborId]=pIncrStart;}
// inline PVAxonalArbor * axonalArbor(int kPre, int arborId)
// {return &axonalArborList[arborId][kPre];}
virtual int numWeightPatches();
virtual int numDataPatches();
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
inline pvdata_t * get_dWData(int kPre, int arborId) {return dwPatches[arborId][kPre]->data;}
inline pvdata_t * getGSynPatchStart(int kPre, int arborId) {return gSynPatchStart[arborId][kPre];}
inline size_t getAPostOffset(int kPre, int arborId) {return aPostOffset[arborId][kPre];} // {return axonalArbor(kPre,arborId)->offset;}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
virtual int setParams(PVParams * params /*, PVConnParams * p*/);
PVPatch *** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
virtual int initShrinkPatches();
virtual int shrinkPatches(int arborId);
int shrinkPatch(int kExt, int arborId);
bool getShrinkPatches_flag() {return shrinkPatches_flag;}
virtual int initNormalize();
int sumWeights(PVPatch * wp, double * sum, double * sum2, pvdata_t * maxVal);
int scaleWeights(PVPatch * wp, pvdata_t sum, pvdata_t sum2, pvdata_t maxVal);
virtual int checkNormalizeWeights(PVPatch * wp, float sum, float sigma2, float maxVal);
virtual int checkNormalizeArbor(PVPatch ** patches, int numPatches, int arborId);
virtual int normalizeWeights(PVPatch ** patches, int numPatches, int arborId);
virtual int kernelIndexToPatchIndex(int kernelIndex, int * kxPatchIndex = NULL,
int * kyPatchIndex = NULL, int * kfPatchIndex = NULL);
virtual int patchIndexToKernelIndex(int patchIndex, int * kxKernelIndex = NULL,
int * kyKernelIndex = NULL, int * kfKernelIndex = NULL);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
//these were moved to private to ensure use of get/set methods and made in 3D pointers:
//PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
//PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
private:
PVPatch *** wPatches; // list of weight patches, one set per arbor
// PVAxonalArbor ** axonalArborList; // list of axonal arbors for each presynaptic cell in extended layer
pvdata_t *** gSynPatchStart; // gSynPatchStart[arborId][kExt] is a pointer to the start of the patch in the post-synaptic GSyn buffer
size_t ** aPostOffset; // aPostOffset[arborId][kExt] is the index of the start of a patch into an extended post-synaptic layer
int * delays; // delays[arborId] is the delay in timesteps (not units of dt) of the arborId'th arbor
PVPatchStrides postExtStrides; // nx,ny,nf,sx,sy,sf for a patch mapping into an extended post-synaptic layer
PVPatchStrides postNonextStrides; // nx,ny,nf,sx,sy,sf for a patch mapping into a non-extended post-synaptic layer
pvdata_t ** wDataStart; //now that data for all patches are allocated to one continuous block of memory, this pointer saves the starting address of that array
pvdata_t ** dwDataStart; //now that data for all patches are allocated to one continuous block of memory, this pointer saves the starting address of that array
int defaultDelay; //added to save params file defined delay...
protected:
PVPatch *** wPostPatches; // post-synaptic linkage of weights
PVPatch *** dwPatches; // list of weight patches for storing changes to weights
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
ChannelType channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int sxp, syp, sfp; // stride in x,y,features
int numParams;
//PVConnParams * params;
float wMax;
float wMin;
int numProbes;
BaseConnectionProbe ** probes; // probes used to output data
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
bool writeCompressedWeights; // true=write weights with 8-bit precision;
// false=write weights with float precision
int fileType; // type ID for file written by PV::writeWeights
Timer * update_timer;
bool plasticityFlag;
bool normalize_flag;
float normalize_strength;
bool normalize_arbors_individually; // if true, each arbor is normalized individually, otherwise, arbors normalized together
bool normalize_max;
bool normalize_zero_offset;
float normalize_cutoff;
bool shrinkPatches_flag;
//This object handles calculating weights. All the initialize weights methods for all connection classes
//are being moved into subclasses of this object. The default root InitWeights class will create
//2D Gaussian weights. If weight initialization type isn't created in a way supported by Buildandrun,
//this class will try to read the weights from a file or will do a 2D Gaussian.
InitWeights *weightInitializer;
protected:
virtual int setPatchSize(const char * filename);
virtual int setPatchStrides();
virtual int checkPatchSize(int patchSize, int scalePre, int scalePost, char dim);
int calcPatchSize(int n, int kex,
int * kl, int * offset,
int * nxPatch, int * nyPatch,
int * dx, int * dy);
int patchSizeFromFile(const char * filename);
int initialize_base();
virtual int createArbors();
void createArborsOutOfMemory();
virtual int constructWeights(const char * filename);
#ifdef OBSOLETE // Marked obsolete Oct 1, 2011. Made redundant by adding default value to weightInit argument of other initialize method
int initialize(const char * name, HyPerCol * hc, HyPerLayer * pre,
HyPerLayer * post, ChannelType channel, const char * filename);
#endif // OBSOLETE
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post,
ChannelType channel, const char * filename,
InitWeights *weightInit=NULL);
virtual int initPlasticityPatches();
virtual PVPatch *** initializeWeights(PVPatch *** arbors, int numPatches,
const char * filename);
virtual InitWeights * handleMissingInitWeights(PVParams * params);
// virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
// int nyPatch, int nfPatch, int axonId);
// PVPatch ** createWeights(PVPatch ** patches, int axonId);
// virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
// int nyPatch, int nfPatch, int axonId);
virtual pvdata_t * createWeights(PVPatch *** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch, int axonId);
pvdata_t * createWeights(PVPatch *** patches, int axonId);
virtual pvdata_t * allocWeights(PVPatch *** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch, int axonId);
//PVPatch ** allocWeights(PVPatch ** patches);
virtual int checkPVPFileHeader(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors(int arborId);
char * checkpointFilename();
// following is overridden by KernelConn to set kernelPatches
//inline void setWPatches(PVPatch ** patches, int arborId) {wPatches[arborId]=patches;}
virtual int setWPatches(PVPatch ** patches, int arborId) {wPatches[arborId]=patches; return 0;}
virtual int setdWPatches(PVPatch ** patches, int arborId) {dwPatches[arborId]=patches; return 0;}
// inline void setArbor(PVAxonalArbor* arbor, int arborId) {axonalArborList[arborId]=arbor;}
virtual int calc_dW(int axonId = 0);
void connOutOfMemory(const char * funcname);
#ifdef PV_USE_OPENCL
virtual int initializeThreadBuffers(const char * kernelName);
virtual int initializeThreadKernels(const char * kernelName);
CLKernel * krRecvSyn; // CL kernel for layer recvSynapticInput call
cl_event evRecvSyn;
// OpenCL buffers
//
CLBuffer * clGSyn;
CLBuffer * clActivity;
CLBuffer ** clWeights;
// ids of OpenCL arguments that change
//
int clArgIdOffset;
int clArgIdWeights;
#endif
public:
// static member functions
//
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<|endoftext|> |
<commit_before>// System Includes
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <math.h>
// Foreign includes
#include "readproc.h"
#include "sysinfo.h"
#include "escape.h"
// Local Includes
#include "Screen.h"
#include "MatrixColumn.h"
#include "PSModule.h"
PSModule::PSModule()
{
pthread_mutex_init(&_lock, NULL);
pthread_cond_init(&_cond, NULL);
}
PSModule::~PSModule()
{
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
// AbstractModule Interface specification
void PSModule::processchar (int c)
{
pthread_mutex_lock(&_lock);
_charqueue.push_back(c);
pthread_cond_signal(&_cond);
pthread_mutex_unlock(&_lock);
}
AbstractModule * PSModule::execute(Screen & scr, std::vector<MatrixColumn *> & MClist)
{
// FILE * log = fopen ("PSMatrix.log", "w+");
// Seed the MC maps
int i = 0;
for (std::vector<MatrixColumn *>::iterator MCitr = MClist.begin();
MCitr != MClist.end();
MCitr++)
{
// Mark odd columns as unassigned (NULL)
if (++i % 2)
_MC_Proc_map.insert(std::pair < MatrixColumn *, Proc * > (*MCitr, NULL));
}
bool firstloop = true;
///////////////////////
// Main processing loop
///////////////////////
struct timeval oldtimev;
struct timeval timev;
_terminate = false;
while (!_terminate)
{
// Figure out the elapsed time
gettimeofday(&timev, NULL);
float elapsed = (float) (timev.tv_sec - oldtimev.tv_sec)
+ (float) (timev.tv_usec - oldtimev.tv_usec) / 1000000.0;
oldtimev.tv_sec = timev.tv_sec;
oldtimev.tv_usec = timev.tv_usec;
float timescale = 100.0f / ((float)Hertz * (float)elapsed);
// Clear speed sorted list
_cpu_Proc_map.clear();
// Scan the list and mark everyone as old and dead
for (std::map<int, Proc>::iterator procitr = _pid_Proc_map.begin();
procitr != _pid_Proc_map.end();
procitr++)
{
//fprintf (log, "Mark OldDead: %d\n",procitr->first);
assert (procitr->first == procitr->second._ptsk->tid);
procitr->second._pnew = false;
procitr->second._palive = false;
procitr->second._cpu = 0;
}
// Do proc list processing
PROCTAB* PT = openproc(PROC_FILLARG|PROC_FILLCOM|PROC_FILLMEM|PROC_FILLSTAT);
proc_t * ptsk;
while ( (ptsk = readproc(PT, NULL)) )
{
if (ptsk->cmdline == NULL)
{
free (ptsk);
continue;
}
// Look up proc in Full list
std::map <int, Proc>::iterator procitr = _pid_Proc_map.find(ptsk->tid);
// if doesn't exist
if (procitr == _pid_Proc_map.end())
{
procitr = _pid_Proc_map.insert(std::pair<int, Proc>(ptsk->tid,Proc(ptsk))).first;
//fprintf (log, "Mark New: %d\n",procitr->first);
} else
// if exists
{
//fprintf (log, "Mark Alive: %d\n",procitr->first);
// marked as alive
procitr->second._palive = true;
// do speed calc
procitr->second._tics = ptsk->utime - procitr->second._ptsk->utime;
procitr->second._tics += ptsk->stime - procitr->second._ptsk->stime;
procitr->second._cpu = (float) procitr->second._tics * timescale;
procitr->second._ptsk->utime = ptsk->utime;
procitr->second._ptsk->stime = ptsk->stime;
// delete this ptsk as we already have one
free ((void*)*ptsk->cmdline);
free (ptsk);
}
// insert in Cpu list
_cpu_Proc_map.insert (std::pair<float, Proc *> (procitr->second._cpu, &procitr->second));
}
closeproc(PT);
// OK, if this is our first time through the loop then we don't
// need to do any of the following, so skip it.
if (firstloop)
{
firstloop = false;
continue;
}
// Regenerate the LRU and pid sorted MColumn list
_LRU_MC_map.clear();
_pid_MC_map.clear();
for (std::map<MatrixColumn *, Proc *>::iterator MCitr = _MC_Proc_map.begin();
MCitr != _MC_Proc_map.end();
MCitr++)
{
if (MCitr->second == NULL)
{
//fprintf (log, "MC NULL: %p\n",MCitr->first);
// If is no associated proc, give it a negative cpu
// so it will be picked up before zero cpu procs
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(),MCitr->first));
} else if (!MCitr->second->_palive)
{
//fprintf (log, "MC DIED: %p : %d\n",MCitr->first,MCitr->second->_ptsk->tid);
// If proc is dead, do a reset and flash fill of
// the column, set the proc pointer to null
// and give it zero cpu
char buf[1024];
char cmd[1024];
int cmdlen = 1024;
escape_command(cmd,MCitr->second->_ptsk,1024,&cmdlen,ESC_ARGS);
snprintf (buf, 1024, "%d %s *** ",
MCitr->second->_ptsk->tid,
cmd);
MCitr->first->resetLRU();
MCitr->first->add_setattr_event(true,false,false,scr.curs_attr_reverse() | scr.curs_attr_red());
MCitr->first->add_clear_event(false, false, false);
MCitr->first->add_delay_event(false,false,false,5);
MCitr->first->add_setattr_event(false,false,false,scr.curs_attr_bold() | scr.curs_attr_red());
MCitr->first->add_setstring_event(false,false,false,buf);
MCitr->first->add_stringfill_event(false,false,false);
MCitr->second = NULL;
// Make it just a little less likely to be picked up
// than a halted running process, so we force walk about
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(),MCitr->first));
} else
{
//fprintf (log, "MC ALIVE: %p : %d : %f\n",MCitr->first,MCitr->second->_ptsk->tid, MCitr->second->_cpu);
// Then adjust the update rate accordingly
MCitr->first->add_setattr_event(false,false,false,
scr.curs_attr_green());
MCitr->first->add_stringdrop_event(false,true,false,
MCitr->second->_cpu*0.1,-1,true,
scr.curs_attr_bold() | scr.curs_attr_white());
// If the process is sleeping, don't reset the column's LRU
if (MCitr->second->_cpu > 0)
MCitr->first->resetLRU();
// Proc is alive so put it in both sorted lists
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(), MCitr->first));
_pid_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->second->_ptsk->tid, MCitr->first));
}
}
// Cull dead processes
for (std::map<int, Proc>::iterator procitr = _pid_Proc_map.begin();
procitr != _pid_Proc_map.end(); )
{
// If dead then remove
std::map<int, Proc>::iterator deaditr = procitr;
procitr++;
if (!deaditr->second._palive)
{
//fprintf (log, "PROC DEAD: %d\n",procitr->first);
// Safe to do this as we're guaranteed not to be
// in the cpu sorted list because we're dead
free ((void*)*(deaditr->second._ptsk)->cmdline);
free (deaditr->second._ptsk);
_pid_Proc_map.erase(deaditr);
}
}
// OK, go through the top CPU users
int MCcount = _MC_Proc_map.size();
for (std::map<float, Proc*>::iterator procitr = _cpu_Proc_map.end();
(procitr != _cpu_Proc_map.begin()) && (MCcount);
)
{
procitr--;
MCcount--;
//fprintf (log, "EXAMINING: %d : %f\n",procitr->second->_ptsk->tid, procitr->first);
// Are we down in the zero cpu processes?
if ((procitr->second->_cpu <= 0) && (!procitr->second->_pnew))
// Then to avoid bottom feeder thrashing
// we get out.
break;
// Is this pid already in the MC list?
if (_pid_MC_map.end() != _pid_MC_map.find(procitr->second->_ptsk->tid))
// Then it's already been dealt with, so skip it
continue;
// OK, so get the LRU column
std::map<int, MatrixColumn *>::iterator LRUMCitr =
_LRU_MC_map.end();
assert (LRUMCitr != _LRU_MC_map.begin());
LRUMCitr--;
// Look it up in the MC sorted proc list and make the association
std::map<MatrixColumn *, Proc *>::iterator MCProcitr =
_MC_Proc_map.find(LRUMCitr->second);
assert (MCProcitr != _MC_Proc_map.end());
MCProcitr->second = procitr->second;
// Now pop the lowest speed MC
_LRU_MC_map.erase(LRUMCitr--);
// Set the string
char buf[1024];
char cmd[1024];
int cmdlen = 1024;
escape_command(cmd,procitr->second->_ptsk,1024,&cmdlen,ESC_ARGS);
snprintf (buf, 1024, "%d %s *** ",
procitr->second->_ptsk->tid,
cmd);
int newattr = scr.curs_attr_bold();
if (procitr->second->_pnew)
{
newattr |= scr.curs_attr_green();
} else {
newattr |= scr.curs_attr_blue();
}
// Brand new processes get a full speed drop
MCProcitr->first->resetLRU();
MCProcitr->first->add_setattr_event(true,false,false, newattr);
MCProcitr->first->add_clear_event(false,false,false);
MCProcitr->first->add_setstring_event(false,false,false,buf);
MCProcitr->first->add_stringdrop_event(false,false,false,
1,(int) scr.maxy() < (int) strlen(buf) ? scr.maxy() : strlen(buf),false, scr.curs_attr_bold() | scr.curs_attr_white());
}
// OK, now do the checkin for input and sleepin thing
struct timespec timeout;
struct timeval now;
gettimeofday (&now, NULL);
timeout.tv_sec = now.tv_sec + 1;
timeout.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock(&_lock);
pthread_cond_timedwait(&_cond,
&_lock,
&timeout);
std::deque<char> _curchars;
if (!_charqueue.empty())
{
_curchars = _charqueue;
_charqueue.clear();
}
pthread_mutex_unlock(&_lock);
while (!_curchars.empty())
{
if (_curchars.front() == 'x')
_terminate = true;
_curchars.pop_front();
}
}
return NULL;
}
<commit_msg> Add dead process clear.<commit_after>// System Includes
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <math.h>
// Foreign includes
#include "readproc.h"
#include "sysinfo.h"
#include "escape.h"
// Local Includes
#include "Screen.h"
#include "MatrixColumn.h"
#include "PSModule.h"
PSModule::PSModule()
{
pthread_mutex_init(&_lock, NULL);
pthread_cond_init(&_cond, NULL);
}
PSModule::~PSModule()
{
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
// AbstractModule Interface specification
void PSModule::processchar (int c)
{
pthread_mutex_lock(&_lock);
_charqueue.push_back(c);
pthread_cond_signal(&_cond);
pthread_mutex_unlock(&_lock);
}
AbstractModule * PSModule::execute(Screen & scr, std::vector<MatrixColumn *> & MClist)
{
// FILE * log = fopen ("PSMatrix.log", "w+");
// Seed the MC maps
int i = 0;
for (std::vector<MatrixColumn *>::iterator MCitr = MClist.begin();
MCitr != MClist.end();
MCitr++)
{
// Mark odd columns as unassigned (NULL)
if (++i % 2)
_MC_Proc_map.insert(std::pair < MatrixColumn *, Proc * > (*MCitr, NULL));
}
bool firstloop = true;
///////////////////////
// Main processing loop
///////////////////////
struct timeval oldtimev;
struct timeval timev;
_terminate = false;
while (!_terminate)
{
// Figure out the elapsed time
gettimeofday(&timev, NULL);
float elapsed = (float) (timev.tv_sec - oldtimev.tv_sec)
+ (float) (timev.tv_usec - oldtimev.tv_usec) / 1000000.0;
oldtimev.tv_sec = timev.tv_sec;
oldtimev.tv_usec = timev.tv_usec;
float timescale = 100.0f / ((float)Hertz * (float)elapsed);
// Clear speed sorted list
_cpu_Proc_map.clear();
// Scan the list and mark everyone as old and dead
for (std::map<int, Proc>::iterator procitr = _pid_Proc_map.begin();
procitr != _pid_Proc_map.end();
procitr++)
{
//fprintf (log, "Mark OldDead: %d\n",procitr->first);
assert (procitr->first == procitr->second._ptsk->tid);
procitr->second._pnew = false;
procitr->second._palive = false;
procitr->second._cpu = 0;
}
// Do proc list processing
PROCTAB* PT = openproc(PROC_FILLARG|PROC_FILLCOM|PROC_FILLMEM|PROC_FILLSTAT);
proc_t * ptsk;
while ( (ptsk = readproc(PT, NULL)) )
{
if (ptsk->cmdline == NULL)
{
free (ptsk);
continue;
}
// Look up proc in Full list
std::map <int, Proc>::iterator procitr = _pid_Proc_map.find(ptsk->tid);
// if doesn't exist
if (procitr == _pid_Proc_map.end())
{
procitr = _pid_Proc_map.insert(std::pair<int, Proc>(ptsk->tid,Proc(ptsk))).first;
//fprintf (log, "Mark New: %d\n",procitr->first);
} else
// if exists
{
//fprintf (log, "Mark Alive: %d\n",procitr->first);
// marked as alive
procitr->second._palive = true;
// do speed calc
procitr->second._tics = ptsk->utime - procitr->second._ptsk->utime;
procitr->second._tics += ptsk->stime - procitr->second._ptsk->stime;
procitr->second._cpu = (float) procitr->second._tics * timescale;
procitr->second._ptsk->utime = ptsk->utime;
procitr->second._ptsk->stime = ptsk->stime;
// delete this ptsk as we already have one
free ((void*)*ptsk->cmdline);
free (ptsk);
}
// insert in Cpu list
_cpu_Proc_map.insert (std::pair<float, Proc *> (procitr->second._cpu, &procitr->second));
}
closeproc(PT);
// OK, if this is our first time through the loop then we don't
// need to do any of the following, so skip it.
if (firstloop)
{
firstloop = false;
continue;
}
// Regenerate the LRU and pid sorted MColumn list
_LRU_MC_map.clear();
_pid_MC_map.clear();
for (std::map<MatrixColumn *, Proc *>::iterator MCitr = _MC_Proc_map.begin();
MCitr != _MC_Proc_map.end();
MCitr++)
{
if (MCitr->second == NULL)
{
//fprintf (log, "MC NULL: %p\n",MCitr->first);
// If is no associated proc, give it a negative cpu
// so it will be picked up before zero cpu procs
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(),MCitr->first));
} else if (!MCitr->second->_palive)
{
//fprintf (log, "MC DIED: %p : %d\n",MCitr->first,MCitr->second->_ptsk->tid);
// If proc is dead, do a reset and flash fill of
// the column, set the proc pointer to null
// and give it zero cpu
char buf[1024];
char cmd[1024];
int cmdlen = 1024;
escape_command(cmd,MCitr->second->_ptsk,1024,&cmdlen,ESC_ARGS);
snprintf (buf, 1024, "%d %s *** ",
MCitr->second->_ptsk->tid,
cmd);
MCitr->first->resetLRU();
MCitr->first->add_setattr_event(true,false,false,scr.curs_attr_reverse() | scr.curs_attr_red());
MCitr->first->add_clear_event(false, false, false);
MCitr->first->add_delay_event(false,false,false,5);
MCitr->first->add_setattr_event(false,false,false,scr.curs_attr_bold() | scr.curs_attr_red());
MCitr->first->add_setstring_event(false,false,false,buf);
MCitr->first->add_stringfill_event(false,false,false);
MCitr->second = NULL;
// Make it just a little less likely to be picked up
// than a halted running process, so we force walk about
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(),MCitr->first));
} else
{
//fprintf (log, "MC ALIVE: %p : %d : %f\n",MCitr->first,MCitr->second->_ptsk->tid, MCitr->second->_cpu);
// Then adjust the update rate accordingly
MCitr->first->add_setattr_event(false,false,false,
scr.curs_attr_green());
MCitr->first->add_stringdrop_event(false,true,false,
MCitr->second->_cpu*0.1,-1,true,
scr.curs_attr_bold() | scr.curs_attr_white());
// If the process is sleeping, don't reset the column's LRU
if (MCitr->second->_cpu > 0)
MCitr->first->resetLRU();
// Proc is alive so put it in both sorted lists
_LRU_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->first->getLRU(), MCitr->first));
_pid_MC_map.insert(std::pair < int, MatrixColumn * > (MCitr->second->_ptsk->tid, MCitr->first));
}
}
// Cull dead processes
for (std::map<int, Proc>::iterator procitr = _pid_Proc_map.begin();
procitr != _pid_Proc_map.end(); )
{
// If dead then remove
std::map<int, Proc>::iterator deaditr = procitr;
procitr++;
if (!deaditr->second._palive)
{
//fprintf (log, "PROC DEAD: %d\n",procitr->first);
// Safe to do this as we're guaranteed not to be
// in the cpu sorted list because we're dead
free ((void*)*(deaditr->second._ptsk)->cmdline);
free (deaditr->second._ptsk);
_pid_Proc_map.erase(deaditr);
}
}
// OK, go through the top CPU users
int MCcount = _MC_Proc_map.size();
for (std::map<float, Proc*>::iterator procitr = _cpu_Proc_map.end();
(procitr != _cpu_Proc_map.begin()) && (MCcount);
)
{
procitr--;
MCcount--;
//fprintf (log, "EXAMINING: %d : %f\n",procitr->second->_ptsk->tid, procitr->first);
// Are we down in the zero cpu processes?
if ((procitr->second->_cpu <= 0) && (!procitr->second->_pnew))
// Then to avoid bottom feeder thrashing
// we get out.
break;
// Is this pid already in the MC list?
if (_pid_MC_map.end() != _pid_MC_map.find(procitr->second->_ptsk->tid))
// Then it's already been dealt with, so skip it
continue;
// OK, so get the LRU column
std::map<int, MatrixColumn *>::iterator LRUMCitr =
_LRU_MC_map.end();
assert (LRUMCitr != _LRU_MC_map.begin());
LRUMCitr--;
// Look it up in the MC sorted proc list and make the association
std::map<MatrixColumn *, Proc *>::iterator MCProcitr =
_MC_Proc_map.find(LRUMCitr->second);
assert (MCProcitr != _MC_Proc_map.end());
MCProcitr->second = procitr->second;
// Now pop the lowest speed MC
_LRU_MC_map.erase(LRUMCitr--);
// Set the string
char buf[1024];
char cmd[1024];
int cmdlen = 1024;
escape_command(cmd,procitr->second->_ptsk,1024,&cmdlen,ESC_ARGS);
snprintf (buf, 1024, "%d %s *** ",
procitr->second->_ptsk->tid,
cmd);
int newattr = scr.curs_attr_bold();
if (procitr->second->_pnew)
{
newattr |= scr.curs_attr_green();
} else {
newattr |= scr.curs_attr_blue();
}
// Brand new processes get a full speed drop
MCProcitr->first->resetLRU();
MCProcitr->first->add_setattr_event(true,false,false, newattr);
MCProcitr->first->add_clear_event(false,false,false);
MCProcitr->first->add_setstring_event(false,false,false,buf);
MCProcitr->first->add_stringdrop_event(false,false,false,
1,(int) scr.maxy() < (int) strlen(buf) ? scr.maxy() : strlen(buf),false, scr.curs_attr_bold() | scr.curs_attr_white());
}
// OK, now do the checkin for input and sleepin thing
struct timespec timeout;
struct timeval now;
gettimeofday (&now, NULL);
timeout.tv_sec = now.tv_sec + 1;
timeout.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock(&_lock);
pthread_cond_timedwait(&_cond,
&_lock,
&timeout);
std::deque<char> _curchars;
if (!_charqueue.empty())
{
_curchars = _charqueue;
_charqueue.clear();
}
pthread_mutex_unlock(&_lock);
while (!_curchars.empty())
{
// Exit char
if (_curchars.front() == 'x')
_terminate = true;
// Clear dead processes
if (_curchars.front() == 'd')
{
for (std::map<MatrixColumn *, Proc *>::iterator MCitr = _MC_Proc_map.begin();
MCitr != _MC_Proc_map.end();
MCitr++)
{
if (MCitr->second)
continue;
float speed = (float) random() / (float) RAND_MAX + 0.2;
MCitr->first->resetLRU();
MCitr->first->add_setattr_event(false,false,false, scr.curs_attr_green());
MCitr->first->add_setstring_event(false,false,false," ");
MCitr->first->add_stringdrop_event(false,false,false,
speed,(int) scr.maxy(),false, scr.curs_attr_white());
}
}
_curchars.pop_front();
}
}
return NULL;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) DataStax, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CASS_PREPARE_HPP_INCLUDED__
#define __CASS_PREPARE_HPP_INCLUDED__
#include "callback.hpp"
#include "macros.hpp"
#include "memory.hpp"
#include <uv.h>
namespace cass {
template<class T>
class LoopWatcher {
public:
typedef cass::Callback<void, T*> Callback;
typedef typename T::HandleType HandleType;
LoopWatcher()
: handle_(NULL)
, state_(CLOSED) { }
~LoopWatcher() {
close_handle();
}
/**
* Start the handle.
*
* @param loop The event loop that will process the handle.
* @param callback A callback that handles events.
*/
int start(uv_loop_t* loop, const Callback& callback) {
int rc = 0;
if (handle_ == NULL) {
handle_ = Memory::allocate<HandleType>();
handle_->loop = NULL;
handle_->data = this;
}
if (state_ == CLOSED) {
rc = T::init_handle(loop, handle_);
if (rc != 0) return rc;
state_ = STOPPED;
}
if (state_ == STOPPED) {
rc = T::start_handle(handle_, on_run);
if (rc != 0) return rc;
state_ = STARTED;
}
callback_ = callback;
return 0;
}
/**
* Stop the handle.
*/
void stop() {
if (state_ == STARTED) {
state_ = STOPPED;
T::stop_handle(handle_);
}
}
/**
* Close the handle.
*/
void close_handle() {
if (handle_ != NULL) {
if (state_ == CLOSED) { // The handle was allocate, but initialization failed.
Memory::deallocate(handle_);
} else { // If initialized or started then close the handle properly.
uv_close(reinterpret_cast<uv_handle_t*>(handle_), on_close);
}
state_ = CLOSED;
handle_ = NULL;
}
}
public:
bool is_running() const { return state_ == STARTED; }
uv_loop_t* loop() { return handle_ ? handle_->loop : NULL; }
private:
static void on_run(HandleType* handle) {
T* watcher = static_cast<T*>(handle->data);
watcher->callback_(watcher);
}
static void on_close(uv_handle_t* handle) {
Memory::deallocate(reinterpret_cast<HandleType*>(handle));
}
private:
enum State {
CLOSED,
STOPPED,
STARTED
};
private:
HandleType* handle_;
State state_;
Callback callback_;
private:
DISALLOW_COPY_AND_ASSIGN(LoopWatcher);
};
/**
* A wrapper for uv_prepare. This is useful for processing that needs to be
* done before the event loop goes back into waiting.
*/
class Prepare : public LoopWatcher<Prepare> {
private:
friend class LoopWatcher<Prepare>;
typedef uv_prepare_t HandleType;
typedef uv_prepare_cb CallbackType;
int init_handle(uv_loop_t* loop, HandleType* handle) {
return uv_prepare_init(loop, handle);
}
int start_handle(HandleType* handle, CallbackType callback) {
return uv_prepare_start(handle, callback);
}
void stop_handle(HandleType* handle) {
uv_prepare_stop(handle);
}
};
} // namespace cass
#endif
<commit_msg>Loop watchers compiling<commit_after>/*
Copyright (c) DataStax, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CASS_PREPARE_HPP_INCLUDED__
#define __CASS_PREPARE_HPP_INCLUDED__
#include "callback.hpp"
#include "macros.hpp"
#include "memory.hpp"
#include <uv.h>
namespace cass {
template<class Type, class HType>
class LoopWatcher {
public:
typedef cass::Callback<void, Type*> Callback;
typedef HType HandleType;
LoopWatcher()
: handle_(NULL)
, state_(CLOSED) { }
~LoopWatcher() {
close_handle();
}
/**
* Start the handle.
*
* @param loop The event loop that will process the handle.
* @param callback A callback that handles events.
*/
int start(uv_loop_t* loop, const Callback& callback) {
int rc = 0;
if (handle_ == NULL) {
handle_ = Memory::allocate<HandleType>();
handle_->loop = NULL;
handle_->data = this;
}
if (state_ == CLOSED) {
rc = Type::init_handle(loop, handle_);
if (rc != 0) return rc;
state_ = STOPPED;
}
if (state_ == STOPPED) {
rc = Type::start_handle(handle_, on_run);
if (rc != 0) return rc;
state_ = STARTED;
}
callback_ = callback;
return 0;
}
/**
* Stop the handle.
*/
void stop() {
if (state_ == STARTED) {
state_ = STOPPED;
Type::stop_handle(handle_);
}
}
/**
* Close the handle.
*/
void close_handle() {
if (handle_ != NULL) {
if (state_ == CLOSED) { // The handle was allocate, but initialization failed.
Memory::deallocate(handle_);
} else { // If initialized or started then close the handle properly.
uv_close(reinterpret_cast<uv_handle_t*>(handle_), on_close);
}
state_ = CLOSED;
handle_ = NULL;
}
}
public:
bool is_running() const { return state_ == STARTED; }
uv_loop_t* loop() { return handle_ ? handle_->loop : NULL; }
private:
static void on_run(HandleType* handle) {
Type* watcher = static_cast<Type*>(handle->data);
watcher->callback_(watcher);
}
static void on_close(uv_handle_t* handle) {
Memory::deallocate(reinterpret_cast<HandleType*>(handle));
}
private:
enum State {
CLOSED,
STOPPED,
STARTED
};
private:
HandleType* handle_;
State state_;
Callback callback_;
private:
DISALLOW_COPY_AND_ASSIGN(LoopWatcher);
};
/**
* A wrapper for uv_prepare. This is useful for running a callback right before
* the event loop begins polling.
*/
class Prepare : public LoopWatcher<Prepare, uv_prepare_t> {
private:
typedef uv_prepare_cb HandleCallback;
friend class LoopWatcher<Prepare, HandleType>;
static int init_handle(uv_loop_t* loop, HandleType* handle) {
return uv_prepare_init(loop, handle);
}
static int start_handle(HandleType* handle, HandleCallback callback) {
return uv_prepare_start(handle, callback);
}
static void stop_handle(HandleType* handle) {
uv_prepare_stop(handle);
}
};
/**
* A wrapper for uv_check. This is useful for running a callback right after
* the event loop returns from polling.
*/
class Check : public LoopWatcher<Check, uv_check_t> {
private:
typedef uv_check_cb HandleCallback;
friend class LoopWatcher<Check, HandleType>;
static int init_handle(uv_loop_t* loop, HandleType* handle) {
return uv_check_init(loop, handle);
}
static int start_handle(HandleType* handle, HandleCallback callback) {
return uv_check_start(handle, callback);
}
static void stop_handle(HandleType* handle) {
uv_check_stop(handle);
}
};
/**
* A wrapper for uv_idle. This is useful for running a callback once per loop
* iteration, and happens right before prepare handles are run. This prevents
* the loop from blocking.
*/
class Idle : public LoopWatcher<Idle, uv_idle_t> {
private:
typedef uv_idle_cb HandleCallback;
friend class LoopWatcher<Idle, HandleType>;
static int init_handle(uv_loop_t* loop, HandleType* handle) {
return uv_idle_init(loop, handle);
}
static int start_handle(HandleType* handle, HandleCallback callback) {
return uv_idle_start(handle, callback);
}
static void stop_handle(HandleType* handle) {
uv_idle_stop(handle);
}
};
} // namespace cass
#endif
<|endoftext|> |
<commit_before>// Vsevolod Ivanov
#include <string>
#include <iostream>
#include <opendht.h>
#include <opendht/log.h>
#include <opendht/dht_proxy_client.h>
int main(int argc, char * argv[])
{
auto hash = dht::InfoHash::get(argv[1]);
std::shared_ptr<dht::Logger> logger = dht::log::getStdLogger();
dht::DhtProxyClient client([](){}, "127.0.0.1:8080", "client01", logger);
// start a listener
client.listen(hash, [&](const std::vector<dht::Sp<dht::Value>>& values,
bool expired){
std::stringstream ss; ss << "[listen::cb] values = ";
for (const auto &value: values)
ss << value->toString() << " ";
logger->d(ss.str().c_str());
return true;
});
// send two posts
dht::Value value {"slenderman"};
client.put(hash, std::move(value), [&](bool ok){
logger->d("[put1::donecb] ok=%i", ok);
});
dht::Value value2 {"spidergurl"};
client.put(hash, std::move(value2), [&](bool ok){
logger->d("[put2::donecb] ok=%i", ok);
});
// schedule one get
client.get(hash, [&](const dht::Sp<dht::Value>& value){
logger->d("[get1::cb] value=%s", value->toString().c_str());
return true;
},[&](bool ok){
logger->d("[get1::donecb] ok=%i", ok);
});
while (true)
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}
<commit_msg>cpp/opendht: call periodic in async client<commit_after>// Vsevolod Ivanov
#include <string>
#include <iostream>
#include <opendht.h>
#include <opendht/log.h>
#include <opendht/dht_proxy_client.h>
int main(int argc, char * argv[])
{
auto hash = dht::InfoHash::get(argv[1]);
std::shared_ptr<dht::Logger> logger = dht::log::getStdLogger();
dht::DhtProxyClient client([](){}, "127.0.0.1:8080", "client01", logger);
// start a listener
auto ltoken = client.listen(hash, [&](
const std::vector<dht::Sp<dht::Value>>& values, bool expired)
{
std::stringstream ss; ss << "[listen::cb] values = ";
for (const auto &value: values)
ss << value->toString() << " ";
logger->d(ss.str().c_str());
return true;
});
// do a first subscribe
// ...
// send two posts
dht::Value value {"slenderman"};
client.put(hash, std::move(value), [&](bool ok){
logger->d("[put1::donecb] ok=%i", ok);
});
dht::Value value2 {"spidergurl"};
client.put(hash, std::move(value2), [&](bool ok){
logger->d("[put2::donecb] ok=%i", ok);
});
// schedule one get
client.get(hash, [&](const dht::Sp<dht::Value>& value){
logger->d("[get1::cb] value=%s", value->toString().c_str());
return true;
},[&](bool ok){
logger->d("[get1::donecb] ok=%i", ok);
});
while (true){
std::this_thread::sleep_for(std::chrono::seconds(10));
client.periodic(nullptr, 0, nullptr, 0);
}
return 0;
}
<|endoftext|> |
<commit_before>// $Id$
# ifndef CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
# define CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin atomic_eigen_mat_mul.hpp$$
$spell
Eigen
$$
$section Atomic Eigen Matrix Multiply Class$$
$nospell
$head Start Class Definition$$
$srccode%cpp% */
# include <cppad/cppad.hpp>
# include <Eigen/Core>
/* %$$
$head Publice Types$$
$srccode%cpp% */
namespace { // BEGIN_EMPTY_NAMESPACE
template <class Base>
class atomic_eigen_mat_mul : public CppAD::atomic_base<Base> {
public:
// -----------------------------------------------------------
// type of elements during calculation of derivatives
typedef Base scalar;
// type of elements during taping
typedef CppAD::AD<scalar> ad_scalar;
// type of matrix during calculation of derivatives
typedef Eigen::Matrix<
scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix;
// type of matrix during taping
typedef Eigen::Matrix<
ad_scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ad_matrix;
/* %$$
$head Public Constructor$$
$srccode%cpp% */
// constructor
atomic_eigen_mat_mul(
// number of rows in left operand
const size_t nr_left ,
// number of rows in left and columns in right operand
const size_t n_middle ,
// number of columns in right operand
const size_t nc_right
) :
CppAD::atomic_base<Base>(
"atom_eigen_mat_mul" ,
CppAD::atomic_base<Base>::set_sparsity_enum
) ,
nr_left_( nr_left ) ,
n_middle_( n_middle ) ,
nc_right_( nc_right ) ,
nx_( (nr_left + nc_right) * n_middle_ ) ,
ny_( nr_left * nc_right )
{ }
/* %$$
$head Public Pack$$
$srccode%cpp% */
template <class Matrix, class Vector>
void pack(
Vector& packed ,
const Matrix& left ,
const Matrix& right )
{ assert( packed.size() == nx_ );
assert( rows( left ) == nr_left_ );
assert( cols( left ) == n_middle_ );
assert( rows( right ) == n_middle_ );
assert( cols( right ) == nc_right_ );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
assert( n_left + n_right == nx_ );
//
for(size_t i = 0; i < n_left; i++)
packed[i] = left.data()[i];
for(size_t i = 0; i < n_right; i++)
packed[ i + n_left ] = right.data()[i];
//
return;
}
/* %$$
$head Public Unpack$$
$srccode%cpp% */
template <class Matrix, class Vector>
void unpack(
const Vector& packed ,
Matrix& result )
{ assert( packed.size() == ny_ );
assert( rows( result ) == nr_left_ );
assert( cols( result ) == nc_right_ );
//
size_t n_result = nr_left_ * nc_right_;
assert( n_result == ny_ );
//
for(size_t i = 0; i < n_result; i++)
result.data()[i] = packed[ i ];
//
return;
}
/* %$$
$head Private Variables$$
$srccode%cpp% */
private:
// -------------------------------------------------------------
// number of of rows in left operand and result
const size_t nr_left_;
// number of of columns in left operand and rows in right operand
const size_t n_middle_;
// number of columns in right operand and result
const size_t nc_right_;
// size of the domain space
const size_t nx_;
// size of the range space
const size_t ny_;
// -------------------------------------------------------------
// one forward mode vector of matrices for left, right, and result
CppAD::vector<matrix> f_left_, f_right_, f_result_;
// one reverse mode vector of matrices for left, right, and result
CppAD::vector<matrix> r_left_, r_right_, r_result_;
// -------------------------------------------------------------
/* %$$
$head Private rows$$
$srccode%cpp% */
// convert from int to size_t
static size_t rows(const matrix& x)
{ return size_t( x.rows() ); }
static size_t rows(const ad_matrix& x)
{ return size_t( x.rows() ); }
/* %$$
$head Private cols$$
$srccode%cpp% */
// convert from int to size_t
static size_t cols(const matrix& x)
{ return size_t( x.cols() ); }
static size_t cols(const ad_matrix& x)
{ return size_t( x.cols() ); }
/* %$$
$head Private forward$$
$srccode%cpp% */
// forward mode routine called by CppAD
virtual bool forward(
// lowest order Taylor coefficient we are evaluating
size_t p ,
// highest order Taylor coefficient we are evaluating
size_t q ,
// which components of x are variables
const CppAD::vector<bool>& vx ,
// which components of y are variables
CppAD::vector<bool>& vy ,
// tx [ j * (q+1) + k ] is x_j^k
const CppAD::vector<scalar>& tx ,
// ty [ i * (q+1) + k ] is y_i^k
CppAD::vector<scalar>& ty
)
{ size_t n_order = q + 1;
assert( vx.size() == 0 || nx_ == vx.size() );
assert( vx.size() == 0 || ny_ == vy.size() );
assert( nx_ * n_order == tx.size() );
assert( ny_ * n_order == ty.size() );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
size_t n_result = nr_left_ * nc_right_;
assert( n_left + n_right == nx_ );
assert( n_result == ny_ );
//
// -------------------------------------------------------------------
// make sure f_left_, f_right_, and f_result_ are large enough
assert( f_left_.size() == f_right_.size() );
assert( f_left_.size() == f_result_.size() );
if( f_left_.size() < n_order )
{ f_left_.resize(n_order);
f_right_.resize(n_order);
f_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ f_left_[k].resize(nr_left_, n_middle_);
f_right_[k].resize(n_middle_, nc_right_);
f_result_[k].resize(nr_left_, nc_right_);
}
}
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ i * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ (i + n_left) * n_order + k ];
}
// -------------------------------------------------------------------
// result for each order
for(size_t k = 0; k < n_order; k++)
{ // result[k] = sum_ell left[ell] * right[k-ell]
f_result_[k] = matrix::Zero(nr_left_, nc_right_);
for(size_t ell = 0; ell <= k; ell++)
f_result_[k] += f_left_[ell] * f_right_[k-ell];
}
// -------------------------------------------------------------------
// pack result_ into ty
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
ty[ i * n_order + k ] = f_result_[k].data()[i];
}
// check if we are compute vy
if( vx.size() == 0 )
return true;
// compute variable information for y; i.e., vy
// (note that the constant zero times a variable is a constant)
scalar zero(0.0);
assert( n_order == 1 );
for(size_t i = 0; i < nr_left_; i++)
{ for(size_t j = 0; j < nc_right_; j++)
{ bool var = false;
for(size_t ell = 0; ell < n_middle_; ell++)
{ size_t index = i * n_middle_ + ell;
bool var_left = vx[index];
bool nz_left = var_left | (f_left_[0](i, ell) != zero);
index = nr_left_ * n_middle_;
index += ell * nc_right_ + j;
bool var_right = vx[index];
bool nz_right = var_right | (f_right_[0](ell, j) != zero);
var |= var_left & nz_right;
var |= nz_left & var_right;
}
size_t index = i * nc_right_ + j;
vy[index] = var;
}
}
return true;
}
/* %$$
$head reverse$$
$srccode%cpp% */
// reverse mode routine called by CppAD
virtual bool reverse(
// highest order Taylor coefficient that we are computing deritive of
size_t q ,
// forward mode Taylor coefficients for x variables
const CppAD::vector<double>& tx ,
// forward mode Taylor coefficients for y variables
const CppAD::vector<double>& ty ,
// upon return, derivative of G[ F[ {x_j^k} ] ] w.r.t {x_j^k}
CppAD::vector<double>& px ,
// derivative of G[ {y_i^k} ] w.r.t. {y_i^k}
const CppAD::vector<double>& py
)
{ size_t n_order = q + 1;
assert( nx_ * n_order == tx.size() );
assert( ny_ * n_order == ty.size() );
assert( px.size() == tx.size() );
assert( py.size() == ty.size() );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
size_t n_result = nr_left_ * nc_right_;
assert( n_left + n_right == nx_ );
assert( n_result == ny_ );
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ i * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ (i + n_left) * n_order + k ];
}
// -------------------------------------------------------------------
// make sure r_left_, r_right_, and r_result_ are large enough
assert( r_left_.size() == r_right_.size() );
assert( r_left_.size() == r_result_.size() );
if( r_left_.size() < n_order )
{ r_left_.resize(n_order);
r_right_.resize(n_order);
r_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ r_left_[k].resize(nr_left_, n_middle_);
r_right_[k].resize(n_middle_, nc_right_);
r_result_[k].resize(nr_left_, nc_right_);
}
}
// -------------------------------------------------------------------
// unpack result_ from py
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
r_result_[k].data()[i] = py[ i * n_order + k ];
}
// -------------------------------------------------------------------
// initialize r_left_ and r_right_ as zero
for(size_t k = 0; k < n_order; k++)
{ r_left_[k] = matrix::Zero(nr_left_, n_middle_);
r_right_[k] = matrix::Zero(n_middle_, nc_right_);
}
// -------------------------------------------------------------------
// matrix reverse mode calculation
for(size_t k1 = n_order; k1 > 0; k1--)
{ size_t k = k1 - 1;
for(size_t ell = 0; ell <= k; ell++)
{ // nr x nm = nr x nc * nc * nm
r_left_[ell] += r_result_[k] * f_right_[k-ell].transpose();
// nm x nc = nm x nr * nr * nc
r_right_[k-ell] += f_left_[ell].transpose() * r_result_[k];
}
}
// -------------------------------------------------------------------
// pack r_left and r_right int px
for(size_t k = 0; k < n_order; k++)
{ // pack left values for this order
for(size_t i = 0; i < n_left; i++)
px[ i * n_order + k ] = r_left_[k].data()[i];
//
// pack right values for this order
for(size_t i = 0; i < n_right; i++)
px[ (i + n_left) * n_order + k] = r_right_[k].data()[i];
}
//
return true;
}
/* %$$
$head End Class Definition$$
$srccode%cpp% */
}; // End of atomic_eigen_mat_mul class
} // END_EMPTY_NAMESPACE
/* %$$
$$ $comment end nospell$$
$end
*/
# endif
<commit_msg>eigen_mat_mul.hpp: move resize in reverse to beginning, fix reverse heading.<commit_after>// $Id$
# ifndef CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
# define CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin atomic_eigen_mat_mul.hpp$$
$spell
Eigen
$$
$section Atomic Eigen Matrix Multiply Class$$
$nospell
$head Start Class Definition$$
$srccode%cpp% */
# include <cppad/cppad.hpp>
# include <Eigen/Core>
/* %$$
$head Publice Types$$
$srccode%cpp% */
namespace { // BEGIN_EMPTY_NAMESPACE
template <class Base>
class atomic_eigen_mat_mul : public CppAD::atomic_base<Base> {
public:
// -----------------------------------------------------------
// type of elements during calculation of derivatives
typedef Base scalar;
// type of elements during taping
typedef CppAD::AD<scalar> ad_scalar;
// type of matrix during calculation of derivatives
typedef Eigen::Matrix<
scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix;
// type of matrix during taping
typedef Eigen::Matrix<
ad_scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ad_matrix;
/* %$$
$head Public Constructor$$
$srccode%cpp% */
// constructor
atomic_eigen_mat_mul(
// number of rows in left operand
const size_t nr_left ,
// number of rows in left and columns in right operand
const size_t n_middle ,
// number of columns in right operand
const size_t nc_right
) :
CppAD::atomic_base<Base>(
"atom_eigen_mat_mul" ,
CppAD::atomic_base<Base>::set_sparsity_enum
) ,
nr_left_( nr_left ) ,
n_middle_( n_middle ) ,
nc_right_( nc_right ) ,
nx_( (nr_left + nc_right) * n_middle_ ) ,
ny_( nr_left * nc_right )
{ }
/* %$$
$head Public Pack$$
$srccode%cpp% */
template <class Matrix, class Vector>
void pack(
Vector& packed ,
const Matrix& left ,
const Matrix& right )
{ assert( packed.size() == nx_ );
assert( rows( left ) == nr_left_ );
assert( cols( left ) == n_middle_ );
assert( rows( right ) == n_middle_ );
assert( cols( right ) == nc_right_ );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
assert( n_left + n_right == nx_ );
//
for(size_t i = 0; i < n_left; i++)
packed[i] = left.data()[i];
for(size_t i = 0; i < n_right; i++)
packed[ i + n_left ] = right.data()[i];
//
return;
}
/* %$$
$head Public Unpack$$
$srccode%cpp% */
template <class Matrix, class Vector>
void unpack(
const Vector& packed ,
Matrix& result )
{ assert( packed.size() == ny_ );
assert( rows( result ) == nr_left_ );
assert( cols( result ) == nc_right_ );
//
size_t n_result = nr_left_ * nc_right_;
assert( n_result == ny_ );
//
for(size_t i = 0; i < n_result; i++)
result.data()[i] = packed[ i ];
//
return;
}
/* %$$
$head Private Variables$$
$srccode%cpp% */
private:
// -------------------------------------------------------------
// number of of rows in left operand and result
const size_t nr_left_;
// number of of columns in left operand and rows in right operand
const size_t n_middle_;
// number of columns in right operand and result
const size_t nc_right_;
// size of the domain space
const size_t nx_;
// size of the range space
const size_t ny_;
// -------------------------------------------------------------
// one forward mode vector of matrices for left, right, and result
CppAD::vector<matrix> f_left_, f_right_, f_result_;
// one reverse mode vector of matrices for left, right, and result
CppAD::vector<matrix> r_left_, r_right_, r_result_;
// -------------------------------------------------------------
/* %$$
$head Private rows$$
$srccode%cpp% */
// convert from int to size_t
static size_t rows(const matrix& x)
{ return size_t( x.rows() ); }
static size_t rows(const ad_matrix& x)
{ return size_t( x.rows() ); }
/* %$$
$head Private cols$$
$srccode%cpp% */
// convert from int to size_t
static size_t cols(const matrix& x)
{ return size_t( x.cols() ); }
static size_t cols(const ad_matrix& x)
{ return size_t( x.cols() ); }
/* %$$
$head Private forward$$
$srccode%cpp% */
// forward mode routine called by CppAD
virtual bool forward(
// lowest order Taylor coefficient we are evaluating
size_t p ,
// highest order Taylor coefficient we are evaluating
size_t q ,
// which components of x are variables
const CppAD::vector<bool>& vx ,
// which components of y are variables
CppAD::vector<bool>& vy ,
// tx [ j * (q+1) + k ] is x_j^k
const CppAD::vector<scalar>& tx ,
// ty [ i * (q+1) + k ] is y_i^k
CppAD::vector<scalar>& ty
)
{ size_t n_order = q + 1;
assert( vx.size() == 0 || nx_ == vx.size() );
assert( vx.size() == 0 || ny_ == vy.size() );
assert( nx_ * n_order == tx.size() );
assert( ny_ * n_order == ty.size() );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
size_t n_result = nr_left_ * nc_right_;
assert( n_left + n_right == nx_ );
assert( n_result == ny_ );
//
// -------------------------------------------------------------------
// make sure f_left_, f_right_, and f_result_ are large enough
assert( f_left_.size() == f_right_.size() );
assert( f_left_.size() == f_result_.size() );
if( f_left_.size() < n_order )
{ f_left_.resize(n_order);
f_right_.resize(n_order);
f_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ f_left_[k].resize(nr_left_, n_middle_);
f_right_[k].resize(n_middle_, nc_right_);
f_result_[k].resize(nr_left_, nc_right_);
}
}
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ i * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ (i + n_left) * n_order + k ];
}
// -------------------------------------------------------------------
// result for each order
for(size_t k = 0; k < n_order; k++)
{ // result[k] = sum_ell left[ell] * right[k-ell]
f_result_[k] = matrix::Zero(nr_left_, nc_right_);
for(size_t ell = 0; ell <= k; ell++)
f_result_[k] += f_left_[ell] * f_right_[k-ell];
}
// -------------------------------------------------------------------
// pack result_ into ty
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
ty[ i * n_order + k ] = f_result_[k].data()[i];
}
// check if we are compute vy
if( vx.size() == 0 )
return true;
// ------------------------------------------------------------------
// compute variable information for y; i.e., vy
// (note that the constant zero times a variable is a constant)
scalar zero(0.0);
assert( n_order == 1 );
for(size_t i = 0; i < nr_left_; i++)
{ for(size_t j = 0; j < nc_right_; j++)
{ bool var = false;
for(size_t ell = 0; ell < n_middle_; ell++)
{ size_t index = i * n_middle_ + ell;
bool var_left = vx[index];
bool nz_left = var_left | (f_left_[0](i, ell) != zero);
index = nr_left_ * n_middle_;
index += ell * nc_right_ + j;
bool var_right = vx[index];
bool nz_right = var_right | (f_right_[0](ell, j) != zero);
var |= var_left & nz_right;
var |= nz_left & var_right;
}
size_t index = i * nc_right_ + j;
vy[index] = var;
}
}
return true;
}
/* %$$
$head Private reverse$$
$srccode%cpp% */
// reverse mode routine called by CppAD
virtual bool reverse(
// highest order Taylor coefficient that we are computing deritive of
size_t q ,
// forward mode Taylor coefficients for x variables
const CppAD::vector<double>& tx ,
// forward mode Taylor coefficients for y variables
const CppAD::vector<double>& ty ,
// upon return, derivative of G[ F[ {x_j^k} ] ] w.r.t {x_j^k}
CppAD::vector<double>& px ,
// derivative of G[ {y_i^k} ] w.r.t. {y_i^k}
const CppAD::vector<double>& py
)
{ size_t n_order = q + 1;
assert( nx_ * n_order == tx.size() );
assert( ny_ * n_order == ty.size() );
assert( px.size() == tx.size() );
assert( py.size() == ty.size() );
//
size_t n_left = nr_left_ * n_middle_;
size_t n_right = n_middle_ * nc_right_;
size_t n_result = nr_left_ * nc_right_;
assert( n_left + n_right == nx_ );
assert( n_result == ny_ );
//
// -------------------------------------------------------------------
// make sure r_left_, r_right_, and r_result_ are large enough
assert( r_left_.size() == r_right_.size() );
assert( r_left_.size() == r_result_.size() );
if( r_left_.size() < n_order )
{ r_left_.resize(n_order);
r_right_.resize(n_order);
r_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ r_left_[k].resize(nr_left_, n_middle_);
r_right_[k].resize(n_middle_, nc_right_);
r_result_[k].resize(nr_left_, nc_right_);
}
}
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ i * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ (i + n_left) * n_order + k ];
}
// -------------------------------------------------------------------
// unpack result_ from py
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
r_result_[k].data()[i] = py[ i * n_order + k ];
}
// -------------------------------------------------------------------
// initialize r_left_ and r_right_ as zero
for(size_t k = 0; k < n_order; k++)
{ r_left_[k] = matrix::Zero(nr_left_, n_middle_);
r_right_[k] = matrix::Zero(n_middle_, nc_right_);
}
// -------------------------------------------------------------------
// matrix reverse mode calculation
for(size_t k1 = n_order; k1 > 0; k1--)
{ size_t k = k1 - 1;
for(size_t ell = 0; ell <= k; ell++)
{ // nr x nm = nr x nc * nc * nm
r_left_[ell] += r_result_[k] * f_right_[k-ell].transpose();
// nm x nc = nm x nr * nr * nc
r_right_[k-ell] += f_left_[ell].transpose() * r_result_[k];
}
}
// -------------------------------------------------------------------
// pack r_left and r_right int px
for(size_t k = 0; k < n_order; k++)
{ // pack left values for this order
for(size_t i = 0; i < n_left; i++)
px[ i * n_order + k ] = r_left_[k].data()[i];
//
// pack right values for this order
for(size_t i = 0; i < n_right; i++)
px[ (i + n_left) * n_order + k] = r_right_[k].data()[i];
}
//
return true;
}
/* %$$
$head End Class Definition$$
$srccode%cpp% */
}; // End of atomic_eigen_mat_mul class
} // END_EMPTY_NAMESPACE
/* %$$
$$ $comment end nospell$$
$end
*/
# endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <boost/test/unit_test.hpp>
#include <pkmnsim/enums.hpp>
#include <pkmnsim/team_pokemon.hpp>
#include <pokelib/pokelib.h>
#include "../lib/library_bridge.hpp"
#include "../lib/conversions/pokemon.hpp"
/*
* Test Pokemon-sim <-> PokeLib-NC conversion.
*/
BOOST_AUTO_TEST_CASE(pkmnsim_to_pokelib)
{
pkmnsim::team_pokemon::sptr pkmnsim_pkmn = pkmnsim::team_pokemon::make(pkmnsim::Species::PIKACHU,
pkmnsim::Games::DIAMOND,
20,
pkmnsim::Moves::THUNDER,
pkmnsim::Moves::AGILITY,
pkmnsim::Moves::VOLT_TACKLE,
pkmnsim::Moves::SHOCK_WAVE);
PokeLib::Pokemon pokelib_pkmn = pkmnsim::conversions::team_pokemon_to_pokelib_pokemon(pkmnsim_pkmn);
pkmnsim::dict<unsigned int, unsigned int> stats = pkmnsim_pkmn->get_stats();
pkmnsim::dict<unsigned int, unsigned int> EVs = pkmnsim_pkmn->get_EVs();
pkmnsim::dict<unsigned int, unsigned int> IVs = pkmnsim_pkmn->get_IVs();
uint32_t* IVint = &(pokelib_pkmn.pkm->pkm.IVint);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Effort Values" << std::endl;
std::cout << " * HP: " << EVs[pkmnsim::Stats::HP] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_hp) << std::endl;
std::cout << " * Attack: " << EVs[pkmnsim::Stats::ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_atk) << std::endl;
std::cout << " * Defense: " << EVs[pkmnsim::Stats::DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_def) << std::endl;
std::cout << " * Speed: " << EVs[pkmnsim::Stats::SPEED] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_spd) << std::endl;
std::cout << " * Special Attack: " << EVs[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_satk) << std::endl;
std::cout << " * Special Defense: " << EVs[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_sdef) << std::endl;
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_hp, EVs[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_atk, EVs[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_def, EVs[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_spd, EVs[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_satk, EVs[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_sdef, EVs[pkmnsim::Stats::SPECIAL_DEFENSE]);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Individual Values" << std::endl;
std::cout << " * HP: " << IVs[pkmnsim::Stats::HP] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::HP)) << std::endl;
std::cout << " * Attack: " << IVs[pkmnsim::Stats::ATTACK] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::ATTACK)) << std::endl;
std::cout << " * Defense: " << IVs[pkmnsim::Stats::DEFENSE] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::DEFENSE)) << std::endl;
std::cout << " * Speed: " << IVs[pkmnsim::Stats::SPEED] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPEED)) << std::endl;
std::cout << " * Special Attack: " << IVs[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_ATTACK)) << std::endl;
std::cout << " * Special Defense: " << IVs[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_DEFENSE)) << std::endl;
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::HP)), IVs[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::ATTACK)), IVs[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::DEFENSE)), IVs[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPEED)), IVs[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_ATTACK)), IVs[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_DEFENSE)), IVs[pkmnsim::Stats::SPECIAL_DEFENSE]);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Stats" << std::endl;
std::cout << " * HP: " << stats[pkmnsim::Stats::HP] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_max_hp) << std::endl;
std::cout << " * Attack: " << stats[pkmnsim::Stats::ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_atk) << std::endl;
std::cout << " * Defense: " << stats[pkmnsim::Stats::DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_def) << std::endl;
std::cout << " * Speed: " << stats[pkmnsim::Stats::SPEED] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_spd) << std::endl;
std::cout << " * Special Attack: " << stats[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_satk) << std::endl;
std::cout << " * Special Defense: " << stats[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_sdef) << std::endl;
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_max_hp, stats[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_atk, stats[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_def, stats[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_spd, stats[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_satk, stats[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_sdef, stats[pkmnsim::Stats::SPECIAL_DEFENSE]);
}
<commit_msg>pokelib-nc_test: change team_pokemon level to 50 for easier Bulbapedia reference<commit_after>/*
* Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <boost/test/unit_test.hpp>
#include <pkmnsim/enums.hpp>
#include <pkmnsim/team_pokemon.hpp>
#include <pokelib/pokelib.h>
#include "../lib/library_bridge.hpp"
#include "../lib/conversions/pokemon.hpp"
/*
* Test Pokemon-sim <-> PokeLib-NC conversion.
*/
BOOST_AUTO_TEST_CASE(pkmnsim_to_pokelib)
{
pkmnsim::team_pokemon::sptr pkmnsim_pkmn = pkmnsim::team_pokemon::make(pkmnsim::Species::PIKACHU,
pkmnsim::Games::DIAMOND,
50,
pkmnsim::Moves::THUNDER,
pkmnsim::Moves::AGILITY,
pkmnsim::Moves::VOLT_TACKLE,
pkmnsim::Moves::SHOCK_WAVE);
PokeLib::Pokemon pokelib_pkmn = pkmnsim::conversions::team_pokemon_to_pokelib_pokemon(pkmnsim_pkmn);
pkmnsim::dict<unsigned int, unsigned int> stats = pkmnsim_pkmn->get_stats();
pkmnsim::dict<unsigned int, unsigned int> EVs = pkmnsim_pkmn->get_EVs();
pkmnsim::dict<unsigned int, unsigned int> IVs = pkmnsim_pkmn->get_IVs();
uint32_t* IVint = &(pokelib_pkmn.pkm->pkm.IVint);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Effort Values" << std::endl;
std::cout << " * HP: " << EVs[pkmnsim::Stats::HP] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_hp) << std::endl;
std::cout << " * Attack: " << EVs[pkmnsim::Stats::ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_atk) << std::endl;
std::cout << " * Defense: " << EVs[pkmnsim::Stats::DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_def) << std::endl;
std::cout << " * Speed: " << EVs[pkmnsim::Stats::SPEED] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_spd) << std::endl;
std::cout << " * Special Attack: " << EVs[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_satk) << std::endl;
std::cout << " * Special Defense: " << EVs[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.ev_sdef) << std::endl;
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_hp, EVs[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_atk, EVs[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_def, EVs[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_spd, EVs[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_satk, EVs[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.ev_sdef, EVs[pkmnsim::Stats::SPECIAL_DEFENSE]);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Individual Values" << std::endl;
std::cout << " * HP: " << IVs[pkmnsim::Stats::HP] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::HP)) << std::endl;
std::cout << " * Attack: " << IVs[pkmnsim::Stats::ATTACK] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::ATTACK)) << std::endl;
std::cout << " * Defense: " << IVs[pkmnsim::Stats::DEFENSE] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::DEFENSE)) << std::endl;
std::cout << " * Speed: " << IVs[pkmnsim::Stats::SPEED] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPEED)) << std::endl;
std::cout << " * Special Attack: " << IVs[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_ATTACK)) << std::endl;
std::cout << " * Special Defense: " << IVs[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_DEFENSE)) << std::endl;
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::HP)), IVs[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::ATTACK)), IVs[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::DEFENSE)), IVs[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPEED)), IVs[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_ATTACK)), IVs[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(int(pkmnsim::modern_get_IV(IVint, pkmnsim::Stats::SPECIAL_DEFENSE)), IVs[pkmnsim::Stats::SPECIAL_DEFENSE]);
std::cout << std::endl << "LibPKMNsim -> PokeLib-NC Stats" << std::endl;
std::cout << " * HP: " << stats[pkmnsim::Stats::HP] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_max_hp) << std::endl;
std::cout << " * Attack: " << stats[pkmnsim::Stats::ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_atk) << std::endl;
std::cout << " * Defense: " << stats[pkmnsim::Stats::DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_def) << std::endl;
std::cout << " * Speed: " << stats[pkmnsim::Stats::SPEED] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_spd) << std::endl;
std::cout << " * Special Attack: " << stats[pkmnsim::Stats::SPECIAL_ATTACK] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_satk) << std::endl;
std::cout << " * Special Defense: " << stats[pkmnsim::Stats::SPECIAL_DEFENSE] << " -> " << int(pokelib_pkmn.pkm->pkm.battle_sdef) << std::endl;
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_max_hp, stats[pkmnsim::Stats::HP]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_atk, stats[pkmnsim::Stats::ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_def, stats[pkmnsim::Stats::DEFENSE]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_spd, stats[pkmnsim::Stats::SPEED]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_satk, stats[pkmnsim::Stats::SPECIAL_ATTACK]);
BOOST_CHECK_EQUAL(pokelib_pkmn.pkm->pkm.battle_sdef, stats[pkmnsim::Stats::SPECIAL_DEFENSE]);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/command_line.h"
#include "core/filesystem/path.h"
#include "device/device_options.h"
#include <stdlib.h>
namespace crown
{
static void help(const char* msg = NULL)
{
printf(
"The Flexible Game Engine\n"
"Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.\n"
"License: https://github.com/dbartolini/crown/blob/master/LICENSE\n"
"\n"
"Complete documentation available at https://dbartolini.github.io/crown/html\n"
"\n"
"Usage:\n"
" crown [options]\n"
"\n"
"Options:\n"
" -h --help Display this help.\n"
" -v --version Display engine version.\n"
" --source-dir <path> Use <path> as the source directory for resource compilation.\n"
" --data-dir <path> Use <path> as the destination directory for compiled resources.\n"
" --boot-dir <path> Boot the engine with the 'boot.config' from given <path>.\n"
" --compile Do a full compile of the resources.\n"
" --platform <platform> Compile resources for the given <platform>.\n"
" linux\n"
" windows\n"
" android\n"
" --continue Run the engine after resource compilation.\n"
" --console-port <port> Set port of the console.\n"
" --wait-console Wait for a console connection before starting up.\n"
" --parent-window <handle> Set the parent window <handle> of the main window.\n"
" --server Run the engine in server mode.\n"
);
if (msg)
printf("Error: %s\n", msg);
}
DeviceOptions::DeviceOptions(Allocator& a, int argc, const char** argv)
: _argc(argc)
, _argv(argv)
, _source_dir(a)
, _map_source_dir_name(NULL)
, _map_source_dir_prefix(a)
, _data_dir(a)
, _boot_dir(NULL)
, _platform(NULL)
, _lua_string(a)
, _wait_console(false)
, _do_compile(false)
, _do_continue(false)
, _server(false)
, _parent_window(0)
, _console_port(CROWN_DEFAULT_CONSOLE_PORT)
, _window_x(0)
, _window_y(0)
, _window_width(CROWN_DEFAULT_WINDOW_WIDTH)
, _window_height(CROWN_DEFAULT_WINDOW_HEIGHT)
{
}
int DeviceOptions::parse()
{
CommandLine cl(_argc, _argv);
if (cl.has_option("help", 'h'))
{
help();
return EXIT_FAILURE;
}
if (cl.has_option("version", 'v'))
{
printf(CROWN_VERSION);
return EXIT_FAILURE;
}
path::reduce(_source_dir, cl.get_parameter(0, "source-dir"));
path::reduce(_data_dir, cl.get_parameter(0, "data-dir"));
_map_source_dir_name = cl.get_parameter(0, "map-source-dir");
if (_map_source_dir_name)
{
path::reduce(_map_source_dir_prefix, cl.get_parameter(1, "map-source-dir"));
if (_map_source_dir_prefix.empty())
{
help("Mapped source directory must be specified.");
return EXIT_FAILURE;
}
}
_do_compile = cl.has_option("compile");
if (_do_compile)
{
_platform = cl.get_parameter(0, "platform");
if (!_platform)
{
help("Platform must be specified.");
return EXIT_FAILURE;
}
else if (true
&& strcmp(_platform, "android") != 0
&& strcmp(_platform, "linux") != 0
&& strcmp(_platform, "windows") != 0
)
{
help("Unknown platform.");
return EXIT_FAILURE;
}
if (_source_dir.empty())
{
help("Source dir must be specified.");
return EXIT_FAILURE;
}
if (_data_dir.empty())
{
help("Data dir must be specified.");
return EXIT_FAILURE;
}
}
_server = cl.has_option("server");
if (_server)
{
if (_source_dir.empty())
{
help("Source dir must be specified.");
return EXIT_FAILURE;
}
}
if (!_data_dir.empty())
{
if (!path::is_absolute(_data_dir.c_str()))
{
help("Data dir must be absolute.");
return EXIT_FAILURE;
}
}
if (!_source_dir.empty())
{
if (!path::is_absolute(_source_dir.c_str()))
{
help("Source dir must be absolute.");
return EXIT_FAILURE;
}
}
if (!_map_source_dir_prefix.empty())
{
if (!path::is_absolute(_map_source_dir_prefix.c_str()))
{
help("Mapped source dir must be absolute.");
return EXIT_FAILURE;
}
}
_do_continue = cl.has_option("continue");
_boot_dir = cl.get_parameter(0, "boot-dir");
if (_boot_dir)
{
if (!path::is_relative(_boot_dir))
{
help("Boot dir must be relative.");
return EXIT_FAILURE;
}
}
_wait_console = cl.has_option("wait-console");
const char* parent = cl.get_parameter(0, "parent-window");
if (parent)
{
if (sscanf(parent, "%u", &_parent_window) != 1)
{
help("Parent window is invalid.");
return EXIT_FAILURE;
}
}
const char* port = cl.get_parameter(0, "console-port");
if (port)
{
if (sscanf(port, "%hu", &_console_port) != 1)
{
help("Console port is invalid.");
return EXIT_FAILURE;
}
}
const char* ls = cl.get_parameter(0, "lua-string");
if (ls)
_lua_string = ls;
return EXIT_SUCCESS;
}
} // namespace crown
<commit_msg>Compile data for the platform the executable is built for<commit_after>/*
* Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/command_line.h"
#include "core/filesystem/path.h"
#include "device/device_options.h"
#include <stdlib.h>
namespace crown
{
static void help(const char* msg = NULL)
{
printf(
"The Flexible Game Engine\n"
"Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.\n"
"License: https://github.com/dbartolini/crown/blob/master/LICENSE\n"
"\n"
"Complete documentation available at https://dbartolini.github.io/crown/html\n"
"\n"
"Usage:\n"
" crown [options]\n"
"\n"
"Options:\n"
" -h --help Display this help.\n"
" -v --version Display engine version.\n"
" --source-dir <path> Use <path> as the source directory for resource compilation.\n"
" --data-dir <path> Use <path> as the destination directory for compiled resources.\n"
" --boot-dir <path> Boot the engine with the 'boot.config' from given <path>.\n"
" --compile Do a full compile of the resources.\n"
" --platform <platform> Compile resources for the given <platform>.\n"
" linux\n"
" windows\n"
" android\n"
" --continue Run the engine after resource compilation.\n"
" --console-port <port> Set port of the console.\n"
" --wait-console Wait for a console connection before starting up.\n"
" --parent-window <handle> Set the parent window <handle> of the main window.\n"
" --server Run the engine in server mode.\n"
);
if (msg)
printf("Error: %s\n", msg);
}
DeviceOptions::DeviceOptions(Allocator& a, int argc, const char** argv)
: _argc(argc)
, _argv(argv)
, _source_dir(a)
, _map_source_dir_name(NULL)
, _map_source_dir_prefix(a)
, _data_dir(a)
, _boot_dir(NULL)
, _platform(NULL)
, _lua_string(a)
, _wait_console(false)
, _do_compile(false)
, _do_continue(false)
, _server(false)
, _parent_window(0)
, _console_port(CROWN_DEFAULT_CONSOLE_PORT)
, _window_x(0)
, _window_y(0)
, _window_width(CROWN_DEFAULT_WINDOW_WIDTH)
, _window_height(CROWN_DEFAULT_WINDOW_HEIGHT)
{
}
int DeviceOptions::parse()
{
CommandLine cl(_argc, _argv);
if (cl.has_option("help", 'h'))
{
help();
return EXIT_FAILURE;
}
if (cl.has_option("version", 'v'))
{
printf(CROWN_VERSION);
return EXIT_FAILURE;
}
path::reduce(_source_dir, cl.get_parameter(0, "source-dir"));
path::reduce(_data_dir, cl.get_parameter(0, "data-dir"));
_map_source_dir_name = cl.get_parameter(0, "map-source-dir");
if (_map_source_dir_name)
{
path::reduce(_map_source_dir_prefix, cl.get_parameter(1, "map-source-dir"));
if (_map_source_dir_prefix.empty())
{
help("Mapped source directory must be specified.");
return EXIT_FAILURE;
}
}
_do_compile = cl.has_option("compile");
if (_do_compile)
{
_platform = cl.get_parameter(0, "platform");
// Compile for platform the executable is built for.
if (!_platform)
_platform = CROWN_PLATFORM_NAME;
if (true
&& strcmp(_platform, "android") != 0
&& strcmp(_platform, "linux") != 0
&& strcmp(_platform, "windows") != 0
)
{
help("Cannot compile for the given platform.");
return EXIT_FAILURE;
}
if (_source_dir.empty())
{
help("Source dir must be specified.");
return EXIT_FAILURE;
}
if (_data_dir.empty())
{
help("Data dir must be specified.");
return EXIT_FAILURE;
}
}
_server = cl.has_option("server");
if (_server)
{
if (_source_dir.empty())
{
help("Source dir must be specified.");
return EXIT_FAILURE;
}
}
if (!_data_dir.empty())
{
if (!path::is_absolute(_data_dir.c_str()))
{
help("Data dir must be absolute.");
return EXIT_FAILURE;
}
}
if (!_source_dir.empty())
{
if (!path::is_absolute(_source_dir.c_str()))
{
help("Source dir must be absolute.");
return EXIT_FAILURE;
}
}
if (!_map_source_dir_prefix.empty())
{
if (!path::is_absolute(_map_source_dir_prefix.c_str()))
{
help("Mapped source dir must be absolute.");
return EXIT_FAILURE;
}
}
_do_continue = cl.has_option("continue");
_boot_dir = cl.get_parameter(0, "boot-dir");
if (_boot_dir)
{
if (!path::is_relative(_boot_dir))
{
help("Boot dir must be relative.");
return EXIT_FAILURE;
}
}
_wait_console = cl.has_option("wait-console");
const char* parent = cl.get_parameter(0, "parent-window");
if (parent)
{
if (sscanf(parent, "%u", &_parent_window) != 1)
{
help("Parent window is invalid.");
return EXIT_FAILURE;
}
}
const char* port = cl.get_parameter(0, "console-port");
if (port)
{
if (sscanf(port, "%hu", &_console_port) != 1)
{
help("Console port is invalid.");
return EXIT_FAILURE;
}
}
const char* ls = cl.get_parameter(0, "lua-string");
if (ls)
_lua_string = ls;
return EXIT_SUCCESS;
}
} // namespace crown
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/program_options.hpp>
#include "dirMultiNaiveBayes.hpp"
#include "niwBaseMeasure.hpp"
#include "typedef.h"
#include "timer.hpp"
namespace po = boost::program_options;
int main(int argc, char **argv){
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("K,K", po::value<int>(), "number of initial clusters ")
("T,T", po::value<int>(), "iterations")
("v,v", po::value<bool>(), "verbose output")
("input,i", po::value<string>(),
"path to input dataset .csv file (rows: dimensions; cols: different "
"datapoints)")
("output,o", po::value<string>(),
"path to output labels .csv file (rows: time; cols: different "
"datapoints)")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
uint NumObs = 2; //num observations (number of components of multi-dimention data)
uint K=2; //num clusters
uint T=100; //iterations
uint M=2; //num docs
vector<uint> N(NumObs, 100) ; //num data points (total)
vector<uint> D(NumObs, 2); //dimention of data
bool verbose = false;
if (vm.count("K"))
K = vm["K"].as<int>();
if (vm.count("T"))
T = vm["T"].as<int>();
if (vm.count("v"))
verbose = vm["v"].as<bool>();
string pathIn ="";
string pathOut ="";
if(vm.count("input"))
pathIn = vm["input"].as<string>();
if(vm.count("output"))
pathOut= vm["output"].as<string>();
vector<vector< Matrix<double, Dynamic, Dynamic> > > x;
x.reserve(NumObs);
if (!pathIn.compare(""))
{
cout<<"making some data up" <<endl;
for (uint n=0; n<NumObs; ++n)
{
vector<Matrix<double, Dynamic, Dynamic> > temp;
temp.reserve(M);
uint Ndoc=M;
uint Nword=int(N[n]/M);
for(uint i=0; i<Ndoc; ++i)
{
MatrixXd xdoc(D[n],Nword);
for(uint w=0; w<Nword; ++w)
{
if(i<Ndoc/2)
xdoc.col(w) << (NumObs*(n%2))*VectorXd::Ones(D[n]);
else
xdoc.col(w) << (NumObs*(n%2)+1)*VectorXd::Ones(D[n]);
}
temp.push_back(xdoc);
}
x.push_back(temp);
}
}else{
cout<<"loading data from "<<pathIn<<endl;
ifstream fin(pathIn.data(),ifstream::in);
if (!fin.good()) {
cout << "could not open file...returning" << endl;
return(-1);
}
//read data
fin>>NumObs;
N.clear(); N.reserve(NumObs);
D.clear(); D.reserve(NumObs);
for(uint32_t n=0; n<NumObs; ++n)
{
vector< Matrix<double, Dynamic, Dynamic> > xiter;
uint Niter, Diter;
fin>>Niter;
fin>>M;
fin>>Diter;
N.push_back(Niter);
D.push_back(Diter);
MatrixXd data(Diter,Niter);
VectorXu words(M);
for (uint j=0; j<M; ++j)
fin>>words(j);
for (uint j=1; j<(Diter+1); ++j)
for (uint i=0; i<Niter; ++i)
fin>>data(j-1,i);
uint count = 0;
for (uint j=0; j<M; ++j)
{
xiter.push_back(data.middleCols(count,words[j]));
count+=words[j];
}
x.push_back(xiter);
}
fin.close();
}
VectorXd alpha = 10.0*VectorXd::Ones(K);
boost::mt19937 rndGen(9191);
Dir<Catd,double> dir(alpha,&rndGen);
vector<boost::shared_ptr<BaseMeasure<double> > > niwSampled;
niwSampled.reserve(NumObs);
//creates thetas
for(uint m=0;m<NumObs ; ++m)
{
double nu = D[m]+1;
double kappa = D[m]+1;
MatrixXd Delta = 0.1*MatrixXd::Identity(D[m],D[m]);
Delta *= nu;
VectorXd theta = VectorXd::Zero(D[m]);
NIW<double> niw(Delta,theta,nu,kappa,&rndGen);
boost::shared_ptr<NiwSampled<double> > tempBase( new NiwSampled<double>(niw));
niwSampled.push_back(boost::shared_ptr<BaseMeasure<double> >(tempBase));
}
Timer tlocal;
tlocal.tic();
DirMultiNaiveBayes<double> naive_samp(dir,niwSampled);
cout << "multiObsNaiveBayesian Clustering:" << endl;
cout << "Ndocs=" << M << endl;
cout << "NumComp=" << NumObs << endl;
cout << "NumData,Dim= ";
for(uint n=0; n<NumObs; ++n)
cout << "[" << N[n] << ", " << D[n] << "]; ";
cout << endl;
cout << "Num Cluster = " << K << ", (" << T << " iterations)." << endl;
naive_samp.initialize( x );
naive_samp.inferAll(T,verbose);
if (pathOut.compare(""))
{
ofstream fout(pathOut.data(),ofstream::out);
streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer
cout.rdbuf(fout.rdbuf()); //redirect std::cout to fout1 buffer
naive_samp.dump(fout,fout);
std::cout.rdbuf(coutbuf); //reset to standard output again
fout.close();
}
tlocal.displayElapsedTimeAuto();
return(0);
};
<commit_msg>added the command line option -b to specify which template class to use for cluster component (only NIW_sampled right now)<commit_after>#include <iostream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp> //case insensitve string comparison
#include "dirMultiNaiveBayes.hpp"
#include "niwBaseMeasure.hpp"
#include "typedef.h"
#include "timer.hpp"
namespace po = boost::program_options;
using boost::iequals;
int main(int argc, char **argv){
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("K,K", po::value<int>(), "number of initial clusters ")
("T,T", po::value<int>(), "iterations")
("v,v", po::value<bool>(), "verbose output")
("input,i", po::value<string>(),
"path to input dataset .csv file (rows: dimensions; cols: different "
"datapoints)")
("output,o", po::value<string>(),
"path to output labels .csv file (rows: time; cols: different "
"datapoints)")
("b,b", po::value<std::vector<string> >()->multitoken(),
"base class to use for components (must be the same size as M in the data). "
"valid values: NiwSampled, NiwTangent, [default: NiwSampled].");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
uint NumObs = 2; //num observations (number of components of multi-dimention data)
uint K=2; //num clusters
uint T=100; //iterations
uint M=2; //num docs
vector<uint> N(NumObs, 100) ; //num data points (total)
vector<uint> D(NumObs, 2); //dimention of data
vector<string> baseDist; //base distributions for each component
bool verbose = false;
if (vm.count("K"))
K = vm["K"].as<int>();
if (vm.count("T"))
T = vm["T"].as<int>();
if (vm.count("v"))
verbose = vm["v"].as<bool>();
string pathIn ="";
string pathOut ="";
if(vm.count("input"))
pathIn = vm["input"].as<string>();
if(vm.count("output"))
pathOut= vm["output"].as<string>();
vector<vector< Matrix<double, Dynamic, Dynamic> > > x;
x.reserve(NumObs);
if (!pathIn.compare(""))
{
cout<<"making some data up" <<endl;
for (uint n=0; n<NumObs; ++n)
{
vector<Matrix<double, Dynamic, Dynamic> > temp;
temp.reserve(M);
uint Ndoc=M;
uint Nword=int(N[n]/M);
for(uint i=0; i<Ndoc; ++i)
{
MatrixXd xdoc(D[n],Nword);
for(uint w=0; w<Nword; ++w)
{
if(i<Ndoc/2)
xdoc.col(w) << (NumObs*(n%2))*VectorXd::Ones(D[n]);
else
xdoc.col(w) << (NumObs*(n%2)+1)*VectorXd::Ones(D[n]);
}
temp.push_back(xdoc);
}
x.push_back(temp);
}
}else{
cout<<"loading data from "<<pathIn<<endl;
ifstream fin(pathIn.data(),ifstream::in);
if (!fin.good()) {
cout << "could not open file...returning" << endl;
return(-1);
}
//read data
fin>>NumObs;
N.clear(); N.reserve(NumObs);
D.clear(); D.reserve(NumObs);
for(uint32_t n=0; n<NumObs; ++n)
{
vector< Matrix<double, Dynamic, Dynamic> > xiter;
uint Niter, Diter;
fin>>Niter;
fin>>M;
fin>>Diter;
N.push_back(Niter);
D.push_back(Diter);
MatrixXd data(Diter,Niter);
VectorXu words(M);
for (uint j=0; j<M; ++j)
fin>>words(j);
for (uint j=1; j<(Diter+1); ++j)
for (uint i=0; i<Niter; ++i)
fin>>data(j-1,i);
uint count = 0;
for (uint j=0; j<M; ++j)
{
xiter.push_back(data.middleCols(count,words[j]));
count+=words[j];
}
x.push_back(xiter);
}
fin.close();
}
if(vm.count("b")) {
baseDist.clear();
baseDist = vm["b"].as<vector<string>>();
if(uint(baseDist.size())!=NumObs) {
cerr << "Error specified number of base distributions not equal number of data components" << endl;
cerr << "#bases =" << baseDist.size() << ", #data components=" << NumObs << "." << endl;
cerr << "exiting" << endl;
return(-1);
}
} else {
baseDist.clear();
baseDist = vector<string>(NumObs, "NiwSampled");
}
VectorXd alpha = 10.0*VectorXd::Ones(K);
boost::mt19937 rndGen(9191);
Dir<Catd,double> dir(alpha,&rndGen);
vector<boost::shared_ptr<BaseMeasure<double> > > niwSampled;
niwSampled.reserve(NumObs);
//creates thetas
for(uint m=0;m<NumObs ; ++m)
{
if(iequals(baseDist[m], "NiwSampled")) { //sampled normal inversed wishart
double nu = D[m]+1;
double kappa = D[m]+1;
MatrixXd Delta = 0.1*MatrixXd::Identity(D[m],D[m]);
Delta *= nu;
VectorXd theta = VectorXd::Zero(D[m]);
NIW<double> niw(Delta,theta,nu,kappa,&rndGen);
boost::shared_ptr<NiwSampled<double> > tempBase( new NiwSampled<double>(niw));
niwSampled.push_back(boost::shared_ptr<BaseMeasure<double> >(tempBase));
} else if(iequals(baseDist[m], "NiwTangent")) {
cerr << "NiwTangent base not coded yet... fix me" << endl;
return(-1);
} else {
cerr << "error with base distributions (check help) ... returning." << endl;
return(-1);
}
}
Timer tlocal;
tlocal.tic();
DirMultiNaiveBayes<double> naive_samp(dir,niwSampled);
cout << "multiObsNaiveBayesian Clustering:" << endl;
cout << "Ndocs=" << M << endl;
cout << "NumComp=" << NumObs << endl;
cout << "NumData,Dim= ";
for(uint n=0; n<NumObs; ++n)
cout << "[" << N[n] << ", " << D[n] << "]; ";
cout << endl;
cout << "Num Cluster = " << K << ", (" << T << " iterations)." << endl;
naive_samp.initialize( x );
naive_samp.inferAll(T,verbose);
if (pathOut.compare(""))
{
ofstream fout(pathOut.data(),ofstream::out);
streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer
cout.rdbuf(fout.rdbuf()); //redirect std::cout to fout1 buffer
naive_samp.dump(fout,fout);
std::cout.rdbuf(coutbuf); //reset to standard output again
fout.close();
}
tlocal.displayElapsedTimeAuto();
return(0);
};
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.