commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
09eb5474ddff018b485249df03a361b4ddf6545c
|
BB10-Cordova/LowLatencyAudio/plugin/src/blackberry10/native/src/pgaudio_js.cpp
|
BB10-Cordova/LowLatencyAudio/plugin/src/blackberry10/native/src/pgaudio_js.cpp
|
/*
* Copyright 2013 Research In Motion Limited.
*
* 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 "pgaudio_js.hpp"
#include <QDir>
#include <qdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <sstream>
using namespace std;
/**
* Default constructor.
*/
PGaudio::PGaudio(const std::string& id) : m_id(id)
{
// Initalize the ALUT and creates OpenAL context on default device
// Input 0,0 so it grabs the native device as default and creates the context automatically
alutInit(0, 0);
}
/**
* Destructor.
*/
PGaudio::~PGaudio()
{
ALuint bufferID = 0;
ALuint sources = 0;
QString name;
// Stop and unload all files before deleting the sources and buffers
for (int bufferIndex = 0; bufferIndex < m_soundBuffersHash.size(); bufferIndex++) {
name = m_soundBuffersHash.key(bufferIndex);
unload(name);
}
// Clear the QHash for sound buffer ID
m_sourceIndexHash.clear();
m_soundBuffersHash.clear();
// Exit the ALUT.
alutExit();
}
/**
* This method returns the list of objects implemented by this native
* extension.
*/
char* onGetObjList()
{
static char name[] = "PGaudio";
return name;
}
/**
* This method is used by JNext to instantiate the object when
* an object is created on the JavaScript server side.
*/
JSExt* onCreateObject(const string& className, const string& id)
{
if (className == "PGaudio")
return new PGaudio(id);
return 0;
}
/**
* Method used by JNext to determine if the object can be deleted.
*/
bool PGaudio::CanDelete()
{
return true;
}
// Preload function. Takes in three parameters, the path to sound file, sound file name, how many voices it contains.
string PGaudio::preload(QString path, QString fileName, int voices)
{
QString applicationDirectory;
char cwd[PATH_MAX];
ALuint bufferID;
ALuint source;
// Check to see if the file has already been preloaded
// Append the applications directory to the www's sound files directory.
if (m_soundBuffersHash[fileName])
return "Already preloaded " + fileName.toStdString();
// First, we get the complete application directory in which we will load sounds from then
// we convert to QString since it is more convenient when working with directories.
// Append the applications directory to the www's sound files directory.
getcwd(cwd, PATH_MAX);
applicationDirectory = QString(cwd).append("/app/native/").append(path);
// Create OpenAL buffers from all files in the sound directory.
QDir dir(applicationDirectory);
// Incorrect path check
if (!dir.exists())
return "Not loaded. Could not find path " + path.toStdString();
// Set a filter for file listing, only files should be listed.
dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
if (!dir.exists(fileName))
return "Could not find " + fileName.toStdString() + " in given path.";
// Create the Unique Buffer ID from the path
bufferID = alutCreateBufferFromFile(applicationDirectory.append(fileName).toStdString().c_str());
// Create sources and buffers corresponding to each unique file name.
m_soundBuffersHash[fileName] = bufferID;
for (int i = 0; i < voices; i++) {
// Generate the sources, one by one, and store them into m_sourceIndexHash, our hash, using insert Multi hashing
// Also assign the bufferID to the sources
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, bufferID);
m_sourceIndexHash.insertMulti(fileName, source);
}
return "loaded " + fileName.toStdString();
}
string PGaudio::unload(QString fileName)
{
// Stop all sources before unloading.
stop(fileName);
// Get corresponding buffers, voices and sources from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// Loop to make sure every source is deleted incase it had multiple voices.
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i)
alDeleteSources(1, &sources.at(i));
// Delete sources and buffers.
alDeleteBuffers(1, &bufferID);
m_sourceIndexHash.remove(fileName);
// Re-initalize the buffers.
m_soundBuffersHash[fileName] = 0;
return "Unloading " + fileName.toStdString();
}
// Function to stop playing sounds. Takes in sound file name.
string PGaudio::stop(QString fileName)
{
// Loop and stop every sound with corresponding fileName.
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i)
alSourceStop(sources.at(i));
// Stopped playing source.
return "Stopped " + fileName.toStdString();
}
// Function to get Duration. Takes in sound file name.
float PGaudio::getDuration(QString fileName)
{
ALuint bufferID = m_soundBuffersHash[fileName];
if (!bufferID)
return 0;
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
ALuint source = sources.at(sources.size() - 1);
ALint bufferSize, frequency, bitsPerSample, channels;
alGetBufferi(bufferID, AL_SIZE, &bufferSize);
alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
alGetBufferi(bufferID, AL_CHANNELS, &channels);
alGetBufferi(bufferID, AL_BITS, &bitsPerSample);
float result = ((double)bufferSize) / (frequency * channels * (bitsPerSample / 8));
return result;
}
// Function to play single sound. Takes in one parameter, the sound file name.
string PGaudio::play(QString fileName)
{
float currentTime = 0, furthestTime = 0;
ALuint replayingSource = 0;
// Get corresponding buffer from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// Check to see if it has been preloaded.
if (!bufferID)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
// Iterate through a list of sources associated with with the file and play the sound if it is not currently playing
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i) {
ALenum state;
alGetSourcef(sources.at(i), AL_SEC_OFFSET, ¤tTime);
alGetSourcei(sources.at(i), AL_SOURCE_STATE, &state);
if (state != AL_PLAYING) {
alSourcePlay(sources.at(i));
return "Playing " + fileName.toStdString();
}
if (currentTime > furthestTime) {
furthestTime = currentTime;
replayingSource = sources.at(i);
}
}
// Continue cycling through and overwrite the sources if all sources are currently being used
alSourcePlay(replayingSource);
return "Every single voice is currenty being played, now overwriting previous ones";
}
// Function to loop sound. Takes in one parameter, the sound file name.
string PGaudio::loop(QString fileName)
{
// Get corresponding buffers and sources from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// If sound file has been preloaded loop sound
if (!bufferID)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
// Get the source from which the sound will be played.
ALuint source;
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
source = sources.at(sources.size() - 1);
if (alIsSource(source) == AL_TRUE) {
// Loop the source.
alSourcei(source, AL_LOOPING, AL_TRUE);
// Check to see if the sound is already looping or not, if not, loop sound.
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING) {
alSourcePlay(source);
return "Looping " + fileName.toStdString();
}
return fileName.toStdString() + " is already playing";
}
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
}
/**
* It will be called from JNext JavaScript side with passed string.
* This method implements the interface for the JavaScript to native binding
* for invoking native code. This method is triggered when JNext.invoke is
* called on the JavaScript side with this native objects id.
*/
string PGaudio::InvokeMethod(const string& command)
{
// parse command and args from string
int indexOfFirstSpace = command.find_first_of(" ");
string strCommand = command.substr(0, indexOfFirstSpace);
string strValue = command.substr(indexOfFirstSpace + 1, command.length());
// Convert input file name from string to QString
QString fileName = QString::fromStdString(strValue);
// Determine which function should be executed
// Play with given fileName.
if (strCommand == "play")
return play(fileName);
// Loop with given fileName.
if (strCommand == "load") {
// parse path from strValue, end up with fileAndVoice
int indexOfSecondSpace = strValue.find_first_of(" ");
string pathToSounds = strValue.substr(0, indexOfSecondSpace);
string fileAndVoice = strValue.substr(indexOfSecondSpace + 1, strValue.length());
// parse file and voices from fileAndVoices
int indexOfThirdSpace = fileAndVoice.find_first_of(" ");
string file = fileAndVoice.substr(0, indexOfThirdSpace);
string voiceString = fileAndVoice.substr(indexOfThirdSpace + 1, fileAndVoice.length());
// Convert from strings to QString, used as parameters in functions
QString path = QString::fromStdString(pathToSounds);
QString name = QString::fromStdString(file);
int voice = atoi(voiceString.c_str());
// Preload with given path, fileName, and voice
return preload(path, name, voice);
}
// Loops the source
if (strCommand == "loop")
return loop(fileName);
// Unloads the source
if (strCommand == "unload")
return unload(fileName);
// Stop the source.
if (strCommand == "stop")
return stop(fileName);
// Get duration
if (strCommand == "getDuration"){
float result = getDuration(fileName);
if (!result)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
ostringstream buffer;
buffer << result;
string str = buffer.str();
return str;
}
return "Command not found, choose either: load, unload, play ,loop, or stop";
}
|
/*
* Copyright 2013 Research In Motion Limited.
*
* 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 <QDir>
#include <qdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <pthread.h>
#include <time.h>
#include "pgaudio_js.hpp"
using namespace std;
bool isUsed = false;
void *useCheck(void *x_void_ptr){
int *x_ptr = (int *)x_void_ptr;
usleep(*x_ptr * 1000000);
if(isUsed == false)
alutExit();
return NULL;
}
/**
* Default constructor.
*/
PGaudio::PGaudio(const std::string& id) : m_id(id)
{
// Initalize the ALUT and creates OpenAL context on default device
// Input 0,0 so it grabs the native device as default and creates the context automatically
alutInit(0, 0);
}
/**
* Destructor.
*/
PGaudio::~PGaudio()
{
ALuint bufferID = 0;
ALuint sources = 0;
QString name;
// Stop and unload all files before deleting the sources and buffers
for (int bufferIndex = 0; bufferIndex < m_soundBuffersHash.size(); bufferIndex++) {
name = m_soundBuffersHash.key(bufferIndex);
unload(name);
}
// Clear the QHash for sound buffer ID
m_sourceIndexHash.clear();
m_soundBuffersHash.clear();
// Exit the ALUT.
alutExit();
}
/**
* This method returns the list of objects implemented by this native
* extension.
*/
char* onGetObjList()
{
static char name[] = "PGaudio";
return name;
}
/**
* This method is used by JNext to instantiate the object when
* an object is created on the JavaScript server side.
*/
JSExt* onCreateObject(const string& className, const string& id)
{
if (className == "PGaudio")
return new PGaudio(id);
return 0;
}
/**
* Method used by JNext to determine if the object can be deleted.
*/
bool PGaudio::CanDelete()
{
return true;
}
// Preload function. Takes in three parameters, the path to sound file, sound file name, how many voices it contains.
string PGaudio::preload(QString path, QString fileName, int voices)
{
QString applicationDirectory;
char cwd[PATH_MAX];
ALuint bufferID;
ALuint source;
// Check to see if the file has already been preloaded
// Append the applications directory to the www's sound files directory.
if (m_soundBuffersHash[fileName])
return "Already preloaded " + fileName.toStdString();
// First, we get the complete application directory in which we will load sounds from then
// we convert to QString since it is more convenient when working with directories.
// Append the applications directory to the www's sound files directory.
getcwd(cwd, PATH_MAX);
applicationDirectory = QString(cwd).append("/app/native/").append(path);
// Create OpenAL buffers from all files in the sound directory.
QDir dir(applicationDirectory);
// Incorrect path check
if (!dir.exists())
return "Not loaded. Could not find path " + path.toStdString();
// Set a filter for file listing, only files should be listed.
dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
if (!dir.exists(fileName))
return "Could not find " + fileName.toStdString() + " in given path.";
// Create the Unique Buffer ID from the path
bufferID = alutCreateBufferFromFile(applicationDirectory.append(fileName).toStdString().c_str());
// Create sources and buffers corresponding to each unique file name.
m_soundBuffersHash[fileName] = bufferID;
for (int i = 0; i < voices; i++) {
// Generate the sources, one by one, and store them into m_sourceIndexHash, our hash, using insert Multi hashing
// Also assign the bufferID to the sources
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, bufferID);
m_sourceIndexHash.insertMulti(fileName, source);
}
//this->~PGaudio(); calling destructor to kill this object, not used in this case
int x = 3;
pthread_t useCheck_thread;
// create a thread to check if the preloaded audio file if being used or not. If not, kill the audio device channel
if(pthread_create(&useCheck_thread, NULL, useCheck, &x)) {
fprintf(stderr, "Error creating thread\n");
return NULL;
}
return "File: <" + fileName.toStdString() + "> is loaded";
}
string PGaudio::unload(QString fileName){
isUsed = true;
// Stop all sources before unloading.
stop(fileName);
// Get corresponding buffers, voices and sources from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// Loop to make sure every source is deleted incase it had multiple voices.
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i)
alDeleteSources(1, &sources.at(i));
// Delete sources and buffers.
alDeleteBuffers(1, &bufferID);
m_sourceIndexHash.remove(fileName);
// Re-initalize the buffers.
m_soundBuffersHash[fileName] = 0;
alutExit();
return "Unloading " + fileName.toStdString();
}
// Function to stop playing sounds. Takes in sound file name.
string PGaudio::stop(QString fileName){
isUsed = true;
// Loop and stop every sound with corresponding fileName.
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i)
alSourceStop(sources.at(i));
// Stopped playing source.
return "Stopped " + fileName.toStdString();
}
// Function to get Duration. Takes in sound file name.
float PGaudio::getDuration(QString fileName){
isUsed = true;
ALuint bufferID = m_soundBuffersHash[fileName];
if (!bufferID)
return 0;
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
ALuint source = sources.at(sources.size() - 1);
ALint bufferSize, frequency, bitsPerSample, channels;
alGetBufferi(bufferID, AL_SIZE, &bufferSize);
alGetBufferi(bufferID, AL_FREQUENCY, &frequency);
alGetBufferi(bufferID, AL_CHANNELS, &channels);
alGetBufferi(bufferID, AL_BITS, &bitsPerSample);
float result = ((double)bufferSize) / (frequency * channels * (bitsPerSample / 8));
return result;
}
// Function to play single sound. Takes in one parameter, the sound file name.
string PGaudio::play(QString fileName){
isUsed = true;
float currentTime = 0, furthestTime = 0;
ALuint replayingSource = 0;
// Get corresponding buffer from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// Check to see if it has been preloaded.
if (!bufferID)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
// Iterate through a list of sources associated with with the file and play the sound if it is not currently playing
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
for (int i = 0; i < sources.size(); ++i) {
ALenum state;
alGetSourcef(sources.at(i), AL_SEC_OFFSET, ¤tTime);
alGetSourcei(sources.at(i), AL_SOURCE_STATE, &state);
if (state != AL_PLAYING) {
alSourcePlay(sources.at(i));
return "Playing " + fileName.toStdString();
}
if (currentTime > furthestTime) {
furthestTime = currentTime;
replayingSource = sources.at(i);
}
}
// Continue cycling through and overwrite the sources if all sources are currently being used
alSourcePlay(replayingSource);
return "Every single voice is currenty being played, now overwriting previous ones";
}
// Function to loop sound. Takes in one parameter, the sound file name.
string PGaudio::loop(QString fileName){
isUsed = true;
// Get corresponding buffers and sources from the unique file name.
ALuint bufferID = m_soundBuffersHash[fileName];
// If sound file has been preloaded loop sound
if (!bufferID)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
// Get the source from which the sound will be played.
ALuint source;
QList<ALuint> sources = m_sourceIndexHash.values(fileName);
source = sources.at(sources.size() - 1);
if (alIsSource(source) == AL_TRUE) {
// Loop the source.
alSourcei(source, AL_LOOPING, AL_TRUE);
// Check to see if the sound is already looping or not, if not, loop sound.
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING) {
alSourcePlay(source);
return "Looping " + fileName.toStdString();
}
return fileName.toStdString() + " is already playing";
}
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
}
/**
* It will be called from JNext JavaScript side with passed string.
* This method implements the interface for the JavaScript to native binding
* for invoking native code. This method is triggered when JNext.invoke is
* called on the JavaScript side with this native objects id.
*/
string PGaudio::InvokeMethod(const string& command)
{
// parse command and args from string
int indexOfFirstSpace = command.find_first_of(" ");
string strCommand = command.substr(0, indexOfFirstSpace);
string strValue = command.substr(indexOfFirstSpace + 1, command.length());
// Convert input file name from string to QString
QString fileName = QString::fromStdString(strValue);
// Determine which function should be executed
// Play with given fileName.
if (strCommand == "play")
return play(fileName);
// Loop with given fileName.
if (strCommand == "load") {
// parse path from strValue, end up with fileAndVoice
int indexOfSecondSpace = strValue.find_first_of(" ");
string pathToSounds = strValue.substr(0, indexOfSecondSpace);
string fileAndVoice = strValue.substr(indexOfSecondSpace + 1, strValue.length());
// parse file and voices from fileAndVoices
int indexOfThirdSpace = fileAndVoice.find_first_of(" ");
string file = fileAndVoice.substr(0, indexOfThirdSpace);
string voiceString = fileAndVoice.substr(indexOfThirdSpace + 1, fileAndVoice.length());
// Convert from strings to QString, used as parameters in functions
QString path = QString::fromStdString(pathToSounds);
QString name = QString::fromStdString(file);
int voice = atoi(voiceString.c_str());
// Preload with given path, fileName, and voice
return preload(path, name, voice);
}
// Loops the source
if (strCommand == "loop")
return loop(fileName);
// Unloads the source
if (strCommand == "unload")
return unload(fileName);
// Stop the source.
if (strCommand == "stop")
return stop(fileName);
// Get duration
if (strCommand == "getDuration"){
float result = getDuration(fileName);
if (!result)
return "Could not find the file " + fileName.toStdString() + " . Maybe it hasn't been loaded.";
ostringstream buffer;
buffer << result;
string str = buffer.str();
return str;
}
return "Command not found, choose either: load, unload, play ,loop, or stop";
}
|
update src cpp
|
update src cpp
added a timer thread for audio file use check
|
C++
|
apache-2.0
|
timwindsor/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs
|
48eeeb7aaa9fffb08d0eebf5505c0945172c082c
|
partition/src/engpar_balancer.cpp
|
partition/src/engpar_balancer.cpp
|
#include "engpar_balancer.h"
#include "engpar_queue.h"
#include <PCU.h>
#include "../engpar.h"
#include <engpar_support.h>
namespace engpar {
wgt_t getMaxWeight(agi::Ngraph* g, int dimension) {
wgt_t w = getWeight(g,dimension);
return PCU_Max_Double(w);
}
wgt_t getAvgWeight(agi::Ngraph* g, int dimension) {
wgt_t w = getWeight(g,dimension);
return PCU_Add_Double(w) / PCU_Comm_Peers();
}
Balancer::Balancer(agi::Ngraph* g, double f, int v, const char* n) :
agi::Balancer(g,v,n) {
input = new Input(g);
input->step_factor = f;
times[0]=0;
times[1]=0;
}
Balancer::Balancer(Input* input_, int v, const char* n) :
agi::Balancer(input_->g,v,n), input(input_) {
times[0]=0;
times[1]=0;
}
bool Balancer::runStep(double tolerance) {
double time[2];
time[0] = PCU_Time();
Sides* sides = makeSides(input);
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(), sides->print("Sides").c_str());
Weights* targetWeights = makeWeights(input, sides,target_dimension);
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(),
targetWeights->print("Weights").c_str());
Weights** completedWs = NULL;
if (completed_dimensions.size()>0) {
completedWs= new Weights*[completed_dimensions.size()];
for (unsigned int i=0;i<completed_dimensions.size();i++) {
completedWs[i] = makeWeights(input,sides,completed_dimensions[i]);
}
}
Targets* targets = makeTargets(input,sides,targetWeights,
completedWs,completed_weights);
delete sides;
if (completedWs) {
for (unsigned int i=0;i<completed_dimensions.size();i++)
delete completedWs[i];
delete [] completedWs;
}
delete targetWeights;
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(), targets->print("Targets").c_str());
Queue* pq;
if (input->useDistanceQueue) {
pq = createDistanceQueue(input->g);
}
else
pq = createIterationQueue(input->g);
Selector* selector = makeSelector(input,pq,&completed_dimensions,
&completed_weights);
agi::Migration* plan = new agi::Migration;
wgt_t planW = 0.0;
for (unsigned int cavSize=2;cavSize<=12;cavSize+=2) {
planW += selector->select(targets,plan,planW,cavSize,target_dimension);
}
if (completed_dimensions.size()>0) {
int sizes[2];
sizes[0] = plan->size();
Midd* midd = selector->trim(targets,plan);
selector->cancel(plan,midd);
sizes[1]=plan->size();
PCU_Add_Ints(sizes,2);
if (verbosity>=2&&!PCU_Comm_Self())
printf("Plan was trimmed from %d to %d vertices\n",sizes[0],sizes[1]);
}
delete pq;
delete targets;
delete selector;
time[0] = PCU_Time()-time[0];
int numMigrate = plan->size();
numMigrate = PCU_Add_Int(numMigrate);
if (verbosity>=3) {
int* counts = new int[PCU_Comm_Peers()];
for (int i=0;i<PCU_Comm_Peers();i++)
counts[i] = 0;
agi::Migration::iterator itr;
for (itr = plan->begin();itr!=plan->end();itr++)
counts[itr->second]++;
for (int i=0;i<PCU_Comm_Peers();i++)
if (counts[i]>0)
printf("%d sending %d to %d\n",PCU_Comm_Self(),counts[i],i);
}
time[1] = PCU_Time();
if (numMigrate>0)
input->g->migrate(plan);
time[1] = PCU_Time()-time[1];
PCU_Max_Doubles(time,2);
if (!PCU_Comm_Self()) {
if (verbosity>=1) {
printf("Step took %f seconds\n",time[0]);
printf("Migrating %d vertices took %f seconds\n",numMigrate,time[1]);
}
times[0]+=time[0];
times[1]+=time[1];
}
if (numMigrate==0)
return false;
double imb = EnGPar_Get_Imbalance(getWeight(input->g,target_dimension));
//Check for completition of criteria
return imb>tolerance;
}
void Balancer::balance(double) {
if (EnGPar_Is_Log_Open()) {
char message[1000];
sprintf(message,"balance() : \n");
//Log the input parameters
sprintf(message,"%s priorities :",message);
for (unsigned int i=0;i<input->priorities.size();i++)
sprintf(message,"%s %d",message,input->priorities[i]);
sprintf(message,"%s\n",message);
if (input->tolerances.size()>0) {
sprintf(message,"%s tolerances :",message);
for (unsigned int i=0;i<input->tolerances.size();i++)
sprintf(message,"%s %f",message,input->tolerances[i]);
sprintf(message,"%s\n",message);
}
sprintf(message,"%s maxIterations : %d\n",message,input->maxIterations);
sprintf(message,"%s maxIterationsPerType : %d\n",
message,input->maxIterationsPerType);
sprintf(message,"%s step_factor : %f\n",message,input->step_factor);
sprintf(message,"%s sides_edge_type : %d\n",message,input->sides_edge_type);
sprintf(message,"%s selection_edge_type : %d\n",
message,input->selection_edge_type);
sprintf(message,"%s countGhosts : %d\n",message,input->countGhosts);
EnGPar_Log_Function(message);
}
//Setup the original owners arrays before balancing
input->g->setOriginalOwners();
unsigned int index=0;
target_dimension = input->priorities[index];
double tol=1.1;
if (input->tolerances.size()>index)
tol = input->tolerances[index];
if (1 == PCU_Comm_Peers()) {
printf("EnGPar ran in serial, nothing to do exiting...\n");
return;
}
if (!PCU_Comm_Self()&&verbosity>=0)
printf("Starting criteria type %d with imbalances: ",target_dimension);
printImbalances(input->g);
int step = 0;
int inner_steps=0;
double time = PCU_Time();
double targetTime=PCU_Time();
while (step++<input->maxIterations) {
if (!runStep(tol)||inner_steps++>=input->maxIterationsPerType) {
completed_dimensions.push_back(target_dimension);
double maxW = getMaxWeight(input->g,target_dimension);
double tgtMaxW = getAvgWeight(input->g,target_dimension)*tol;
maxW = ( maxW < tgtMaxW ) ? tgtMaxW : maxW;
completed_weights.push_back(maxW);
targetTime = PCU_Time()-targetTime;
targetTime = PCU_Max_Double(targetTime);
if (verbosity>=0&&!PCU_Comm_Self()) {
printf("Completed criteria type %d in %f seconds\n",target_dimension,
targetTime);
}
targetTime=PCU_Time();
index++;
if (index==input->priorities.size())
break;
inner_steps=0;
target_dimension=input->priorities[index];
if (input->tolerances.size()>index)
tol = input->tolerances[index];
if (!PCU_Comm_Self()&&verbosity>=0)
printf("Starting criteria type %d with imbalances: ",target_dimension);
printImbalances(input->g);
}
}
time = PCU_Time()-time;
time = PCU_Max_Double(time);
if (!PCU_Comm_Self()) {
if (verbosity>=0) {
if(step==input->maxIterations)
printf("EnGPar ran to completion in %d iterations in %f seconds\n",
input->maxIterations, time);
else
printf("EnGPar converged in %d iterations in %f seconds\n",step,
time);
}
if (verbosity>=1)
printf("Migration took %f%% of the total time\n",times[1]/time*100);
}
if (EnGPar_Is_Log_Open())
EnGPar_End_Function();
}
agi::Balancer* makeBalancer(Input* in,int v_) {
if (EnGPar_Is_Log_Open()) {
char message[25];
sprintf(message,"makeBalancer\n");
EnGPar_Log_Function(message);
EnGPar_End_Function();
}
return new Balancer(in,v_,"balancer");
}
}
|
#include "engpar_balancer.h"
#include "engpar_queue.h"
#include <PCU.h>
#include "../engpar.h"
#include <engpar_support.h>
namespace engpar {
wgt_t getMaxWeight(agi::Ngraph* g, int dimension) {
wgt_t w = getWeight(g,dimension);
return PCU_Max_Double(w);
}
wgt_t getAvgWeight(agi::Ngraph* g, int dimension) {
wgt_t w = getWeight(g,dimension);
return PCU_Add_Double(w) / PCU_Comm_Peers();
}
Balancer::Balancer(agi::Ngraph* g, double f, int v, const char* n) :
agi::Balancer(g,v,n) {
input = new Input(g);
input->step_factor = f;
times[0]=0;
times[1]=0;
}
Balancer::Balancer(Input* input_, int v, const char* n) :
agi::Balancer(input_->g,v,n), input(input_) {
times[0]=0;
times[1]=0;
}
bool Balancer::runStep(double tolerance) {
double time[2];
time[0] = PCU_Time();
Sides* sides = makeSides(input);
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(), sides->print("Sides").c_str());
Weights* targetWeights = makeWeights(input, sides,target_dimension);
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(),
targetWeights->print("Weights").c_str());
Weights** completedWs = NULL;
if (completed_dimensions.size()>0) {
completedWs= new Weights*[completed_dimensions.size()];
for (unsigned int i=0;i<completed_dimensions.size();i++) {
completedWs[i] = makeWeights(input,sides,completed_dimensions[i]);
}
}
Targets* targets = makeTargets(input,sides,targetWeights,
completedWs,completed_weights);
delete sides;
if (completedWs) {
for (unsigned int i=0;i<completed_dimensions.size();i++)
delete completedWs[i];
delete [] completedWs;
}
delete targetWeights;
if (verbosity>=3)
printf("%d: %s\n",PCU_Comm_Self(), targets->print("Targets").c_str());
Queue* pq;
if (input->useDistanceQueue) {
pq = createDistanceQueue(input->g);
}
else
pq = createIterationQueue(input->g);
Selector* selector = makeSelector(input,pq,&completed_dimensions,
&completed_weights);
agi::Migration* plan = new agi::Migration;
wgt_t planW = 0.0;
for (unsigned int cavSize=2;cavSize<=12;cavSize+=2) {
planW += selector->select(targets,plan,planW,cavSize,target_dimension);
}
if (completed_dimensions.size()>0) {
int sizes[2];
sizes[0] = plan->size();
Midd* midd = selector->trim(targets,plan);
selector->cancel(plan,midd);
sizes[1]=plan->size();
PCU_Add_Ints(sizes,2);
if (verbosity>=2&&!PCU_Comm_Self())
printf("Plan was trimmed from %d to %d vertices\n",sizes[0],sizes[1]);
}
delete pq;
delete targets;
delete selector;
time[0] = PCU_Time()-time[0];
int numMigrate = plan->size();
numMigrate = PCU_Add_Int(numMigrate);
if (verbosity>=3) {
int* counts = new int[PCU_Comm_Peers()];
for (int i=0;i<PCU_Comm_Peers();i++)
counts[i] = 0;
agi::Migration::iterator itr;
for (itr = plan->begin();itr!=plan->end();itr++)
counts[itr->second]++;
for (int i=0;i<PCU_Comm_Peers();i++)
if (counts[i]>0)
printf("%d sending %d to %d\n",PCU_Comm_Self(),counts[i],i);
}
time[1] = PCU_Time();
if (numMigrate>0)
input->g->migrate(plan);
time[1] = PCU_Time()-time[1];
PCU_Max_Doubles(time,2);
if (!PCU_Comm_Self()) {
if (verbosity>=1) {
printf("Step took %f seconds\n",time[0]);
printf("Migrating %d vertices took %f seconds\n",numMigrate,time[1]);
}
times[0]+=time[0];
times[1]+=time[1];
}
if (numMigrate==0)
return false;
double imb = EnGPar_Get_Imbalance(getWeight(input->g,target_dimension));
//Check for completition of criteria
return imb>tolerance;
}
void Balancer::balance(double) {
if (EnGPar_Is_Log_Open()) {
char message[1000];
sprintf(message,"balance() : \n");
//Log the input parameters
sprintf(message,"%s priorities :",message);
for (unsigned int i=0;i<input->priorities.size();i++)
sprintf(message,"%s %d",message,input->priorities[i]);
sprintf(message,"%s\n",message);
if (input->tolerances.size()>0) {
sprintf(message,"%s tolerances :",message);
for (unsigned int i=0;i<input->tolerances.size();i++)
sprintf(message,"%s %f",message,input->tolerances[i]);
sprintf(message,"%s\n",message);
}
sprintf(message,"%s maxIterations : %d\n",message,input->maxIterations);
sprintf(message,"%s maxIterationsPerType : %d\n",
message,input->maxIterationsPerType);
sprintf(message,"%s step_factor : %f\n",message,input->step_factor);
sprintf(message,"%s sides_edge_type : %d\n",message,input->sides_edge_type);
sprintf(message,"%s selection_edge_type : %d\n",
message,input->selection_edge_type);
sprintf(message,"%s countGhosts : %d\n",message,input->countGhosts);
EnGPar_Log_Function(message);
}
//Setup the original owners arrays before balancing
input->g->setOriginalOwners();
unsigned int index=0;
target_dimension = input->priorities[index];
double tol=1.1;
if (input->tolerances.size()>index)
tol = input->tolerances[index];
if (1 == PCU_Comm_Peers()) {
printf("EnGPar ran in serial, nothing to do exiting...\n");
return;
}
if (!PCU_Comm_Self()&&verbosity>=0)
printf("Starting criteria type %d with imbalances: ",target_dimension);
printImbalances(input->g);
int step = 0;
int inner_steps=0;
double time = PCU_Time();
double targetTime=PCU_Time();
while (step++<input->maxIterations) {
if (!runStep(tol)||inner_steps++>=input->maxIterationsPerType) {
completed_dimensions.push_back(target_dimension);
double maxW = getMaxWeight(input->g,target_dimension);
double tgtMaxW = getAvgWeight(input->g,target_dimension)*tol;
maxW = ( maxW < tgtMaxW ) ? tgtMaxW : maxW;
completed_weights.push_back(maxW);
targetTime = PCU_Time()-targetTime;
targetTime = PCU_Max_Double(targetTime);
if (verbosity>=0&&!PCU_Comm_Self()) {
printf("Completed criteria type %d in %d steps and took %f seconds\n",
target_dimension, inner_steps+1, targetTime);
}
targetTime=PCU_Time();
index++;
if (index==input->priorities.size())
break;
inner_steps=0;
target_dimension=input->priorities[index];
if (input->tolerances.size()>index)
tol = input->tolerances[index];
if (!PCU_Comm_Self()&&verbosity>=0)
printf("Starting criteria type %d with imbalances: ",target_dimension);
printImbalances(input->g);
}
}
time = PCU_Time()-time;
time = PCU_Max_Double(time);
if (!PCU_Comm_Self()) {
if (verbosity>=0) {
if(step==input->maxIterations)
printf("EnGPar ran to completion in %d iterations in %f seconds\n",
input->maxIterations, time);
else
printf("EnGPar converged in %d iterations in %f seconds\n",step,
time);
}
if (verbosity>=1)
printf("Migration took %f%% of the total time\n",times[1]/time*100);
}
if (EnGPar_Is_Log_Open())
EnGPar_End_Function();
}
agi::Balancer* makeBalancer(Input* in,int v_) {
if (EnGPar_Is_Log_Open()) {
char message[25];
sprintf(message,"makeBalancer\n");
EnGPar_Log_Function(message);
EnGPar_End_Function();
}
return new Balancer(in,v_,"balancer");
}
}
|
Add step counter to criteria completition
|
Add step counter to criteria completition
|
C++
|
bsd-3-clause
|
SCOREC/EnGPar,SCOREC/EnGPar,SCOREC/EnGPar
|
ffa22d5f55afd4509804a19962d2b9438d458716
|
tests/numerics/dense_matrix_test.C
|
tests/numerics/dense_matrix_test.C
|
// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
// libmesh includes
#include <libmesh/dense_matrix.h>
#include <libmesh/dense_vector.h>
#ifdef LIBMESH_HAVE_PETSC
#include "libmesh/petsc_macro.h"
#endif
#ifdef LIBMESH_USE_REAL_NUMBERS
using namespace libMesh;
class DenseMatrixTest : public CppUnit::TestCase
{
public:
void setUp() {}
void tearDown() {}
CPPUNIT_TEST_SUITE(DenseMatrixTest);
CPPUNIT_TEST(testSVD);
CPPUNIT_TEST_SUITE_END();
private:
void testSVD()
{
DenseMatrix<Number> U, VT;
DenseVector<Number> sigma;
DenseMatrix<Number> A;
A.resize(3, 2);
A(0,0) = 1.0; A(0,1) = 2.0;
A(1,0) = 3.0; A(1,1) = 4.0;
A(2,0) = 5.0; A(2,1) = 6.0;
A.svd(sigma, U, VT);
// Solution for this case is (verified with numpy)
DenseMatrix<Number> true_U(3,2), true_VT(2,2);
DenseVector<Number> true_sigma(2);
true_U(0,0) = -2.298476964000715e-01; true_U(0,1) = 8.834610176985250e-01;
true_U(1,0) = -5.247448187602936e-01; true_U(1,1) = 2.407824921325463e-01;
true_U(2,0) = -8.196419411205157e-01; true_U(2,1) = -4.018960334334318e-01;
true_VT(0,0) = -6.196294838293402e-01; true_VT(0,1) = -7.848944532670524e-01;
true_VT(1,0) = -7.848944532670524e-01; true_VT(1,1) = 6.196294838293400e-01;
true_sigma(0) = 9.525518091565109e+00;
true_sigma(1) = 5.143005806586446e-01;
for (unsigned i=0; i<U.m(); ++i)
for (unsigned j=0; j<U.n(); ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(U(i,j), true_U(i,j), 1.e-12);
for (unsigned i=0; i<VT.m(); ++i)
for (unsigned j=0; j<VT.n(); ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(VT(i,j), true_VT(i,j), 1.e-12);
for (unsigned i=0; i<sigma.size(); ++i)
CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), 1.e-12);
}
};
// Only run the test if we expect it can actually work!
#ifdef LIBMESH_HAVE_PETSC
#if !PETSC_VERSION_LESS_THAN(3,1,0)
CPPUNIT_TEST_SUITE_REGISTRATION(DenseMatrixTest);
#endif
#endif
#endif // LIBMESH_USE_REAL_NUMBERS
|
// Ignore unused parameter warnings coming from cppunit headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
// libmesh includes
#include <libmesh/dense_matrix.h>
#include <libmesh/dense_vector.h>
#ifdef LIBMESH_HAVE_PETSC
#include "libmesh/petsc_macro.h"
#endif
#ifdef LIBMESH_USE_REAL_NUMBERS
using namespace libMesh;
class DenseMatrixTest : public CppUnit::TestCase
{
public:
void setUp() {}
void tearDown() {}
CPPUNIT_TEST_SUITE(DenseMatrixTest);
CPPUNIT_TEST(testSVD);
CPPUNIT_TEST_SUITE_END();
private:
void testSVD()
{
DenseMatrix<Number> U, VT;
DenseVector<Number> sigma;
DenseMatrix<Number> A;
A.resize(3, 2);
A(0,0) = 1.0; A(0,1) = 2.0;
A(1,0) = 3.0; A(1,1) = 4.0;
A(2,0) = 5.0; A(2,1) = 6.0;
A.svd(sigma, U, VT);
// Solution for this case is (verified with numpy)
DenseMatrix<Number> true_U(3,2), true_VT(2,2);
DenseVector<Number> true_sigma(2);
true_U(0,0) = -2.298476964000715e-01; true_U(0,1) = 8.834610176985250e-01;
true_U(1,0) = -5.247448187602936e-01; true_U(1,1) = 2.407824921325463e-01;
true_U(2,0) = -8.196419411205157e-01; true_U(2,1) = -4.018960334334318e-01;
true_VT(0,0) = -6.196294838293402e-01; true_VT(0,1) = -7.848944532670524e-01;
true_VT(1,0) = -7.848944532670524e-01; true_VT(1,1) = 6.196294838293400e-01;
true_sigma(0) = 9.525518091565109e+00;
true_sigma(1) = 5.143005806586446e-01;
for (unsigned i=0; i<U.m(); ++i)
for (unsigned j=0; j<U.n(); ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(U(i,j), true_U(i,j), TOLERANCE*TOLERANCE);
for (unsigned i=0; i<VT.m(); ++i)
for (unsigned j=0; j<VT.n(); ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(VT(i,j), true_VT(i,j), TOLERANCE*TOLERANCE);
for (unsigned i=0; i<sigma.size(); ++i)
CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), TOLERANCE*TOLERANCE);
}
};
// Only run the test if we expect it can actually work!
#ifdef LIBMESH_HAVE_PETSC
#if !PETSC_VERSION_LESS_THAN(3,1,0)
CPPUNIT_TEST_SUITE_REGISTRATION(DenseMatrixTest);
#endif
#endif
#endif // LIBMESH_USE_REAL_NUMBERS
|
Use lower tolerance testing single-precision SVD
|
Use lower tolerance testing single-precision SVD
|
C++
|
lgpl-2.1
|
dschwen/libmesh,pbauman/libmesh,balborian/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,dschwen/libmesh,hrittich/libmesh,jwpeterson/libmesh,svallaghe/libmesh,roystgnr/libmesh,friedmud/libmesh,libMesh/libmesh,libMesh/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,pbauman/libmesh,balborian/libmesh,90jrong/libmesh,90jrong/libmesh,balborian/libmesh,benkirk/libmesh,giorgiobornia/libmesh,hrittich/libmesh,friedmud/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,friedmud/libmesh,pbauman/libmesh,balborian/libmesh,pbauman/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,balborian/libmesh,90jrong/libmesh,roystgnr/libmesh,balborian/libmesh,pbauman/libmesh,vikramvgarg/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,libMesh/libmesh,svallaghe/libmesh,coreymbryant/libmesh,svallaghe/libmesh,90jrong/libmesh,giorgiobornia/libmesh,friedmud/libmesh,aeslaughter/libmesh,coreymbryant/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,hrittich/libmesh,hrittich/libmesh,balborian/libmesh,dschwen/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,capitalaslash/libmesh,roystgnr/libmesh,libMesh/libmesh,friedmud/libmesh,dschwen/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,dschwen/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,90jrong/libmesh,capitalaslash/libmesh,90jrong/libmesh,balborian/libmesh,aeslaughter/libmesh,pbauman/libmesh,svallaghe/libmesh,friedmud/libmesh,pbauman/libmesh,dschwen/libmesh,hrittich/libmesh,pbauman/libmesh,friedmud/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,benkirk/libmesh,capitalaslash/libmesh,libMesh/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,pbauman/libmesh,aeslaughter/libmesh,hrittich/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,benkirk/libmesh,coreymbryant/libmesh,benkirk/libmesh,dschwen/libmesh,benkirk/libmesh,hrittich/libmesh,balborian/libmesh,vikramvgarg/libmesh,aeslaughter/libmesh,dschwen/libmesh,roystgnr/libmesh,benkirk/libmesh,roystgnr/libmesh,roystgnr/libmesh,coreymbryant/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,benkirk/libmesh,benkirk/libmesh,BalticPinguin/libmesh,libMesh/libmesh,90jrong/libmesh,svallaghe/libmesh,coreymbryant/libmesh,90jrong/libmesh,coreymbryant/libmesh,friedmud/libmesh,hrittich/libmesh,svallaghe/libmesh,svallaghe/libmesh,libMesh/libmesh,svallaghe/libmesh,aeslaughter/libmesh,friedmud/libmesh,aeslaughter/libmesh,90jrong/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,benkirk/libmesh,svallaghe/libmesh,coreymbryant/libmesh,libMesh/libmesh,vikramvgarg/libmesh,balborian/libmesh,hrittich/libmesh,vikramvgarg/libmesh
|
090d66f2ee7ce354d64a2a19dfd1f97e96edfce1
|
tests/opencv_laplace_8uc1/main.cpp
|
tests/opencv_laplace_8uc1/main.cpp
|
//
// Copyright (c) 2012, University of Erlangen-Nuremberg
// Copyright (c) 2012, Siemens AG
// 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <iostream>
#include <vector>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef OpenCV
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#endif
#include "hipacc.hpp"
// variables set by Makefile
//#define SIZE_X 3
//#define SIZE_Y 3
//#define WIDTH 4096
//#define HEIGHT 4096
//#define CPU
//#define CONST_MASK
#define USE_LAMBDA
//#define RUN_UNDEF
using namespace hipacc;
using namespace hipacc::math;
// get time in milliseconds
double time_ms () {
struct timeval tv;
gettimeofday (&tv, NULL);
return ((double)(tv.tv_sec) * 1e+3 + (double)(tv.tv_usec) * 1e-3);
}
// Laplace filter reference
void laplace_filter(unsigned char *in, unsigned char *out, int *filter, int
size, int width, int height) {
const int size_x = size;
const int size_y = size;
int anchor_x = size_x >> 1;
int anchor_y = size_y >> 1;
#ifdef OpenCV
int upper_x = width-size_x+anchor_x;
int upper_y = height-size_y+anchor_y;
#else
int upper_x = width-anchor_x;
int upper_y = height-anchor_y;
#endif
for (int y=anchor_y; y<upper_y; ++y) {
for (int x=anchor_x; x<upper_x; ++x) {
int sum = 0;
for (int yf = -anchor_y; yf<=anchor_y; yf++) {
for (int xf = -anchor_x; xf<=anchor_x; xf++) {
sum += filter[(yf+anchor_y)*size_x + xf+anchor_x]*in[(y+yf)*width + x + xf];
}
}
sum = min(sum, 255);
sum = max(sum, 0);
out[y*width + x] = sum;
}
}
}
// Laplace filter in HIPAcc
class LaplaceFilter : public Kernel<unsigned char> {
private:
Accessor<unsigned char> &Input;
Mask<int> &cMask;
const int size;
public:
LaplaceFilter(IterationSpace<unsigned char> &IS, Accessor<unsigned char>
&Input, Mask<int> &cMask, const int size) :
Kernel(IS),
Input(Input),
cMask(cMask),
size(size)
{ addAccessor(&Input); }
#ifdef USE_LAMBDA
void kernel() {
int sum = convolve(cMask, HipaccSUM, [&] () -> int {
return cMask() * Input(cMask);
});
sum = min(sum, 255);
sum = max(sum, 0);
output() = (unsigned char) (sum);
}
#else
void kernel() {
const int anchor = size >> 1;
int sum = 0;
for (int yf = -anchor; yf<=anchor; yf++) {
for (int xf = -anchor; xf<=anchor; xf++) {
sum += cMask(xf, yf)*Input(xf, yf);
}
}
sum = min(sum, 255);
sum = max(sum, 0);
output() = (unsigned char) (sum);
}
#endif
};
/*************************************************************************
* Main function *
*************************************************************************/
int main(int argc, const char **argv) {
double time0, time1, dt, min_dt;
const int width = WIDTH;
const int height = HEIGHT;
const int size_x = SIZE_X;
const int size_y = SIZE_Y;
const int offset_x = size_x >> 1;
const int offset_y = size_y >> 1;
std::vector<float> timings;
float timing = 0.0f;
// only filter kernel sizes 3x3 and 5x5 supported
if (size_x != size_y || !(size_x == 3 || size_x == 5)) {
fprintf(stderr, "Wrong filter kernel size. Currently supported values: 3x3 and 5x5!\n");
exit(EXIT_FAILURE);
}
// convolution filter mask
#ifdef CONST_MASK
const
#endif
int mask[] = {
#if SIZE_X==1
0, 1, 0,
1, -4, 1,
0, 1, 0,
#endif
#if SIZE_X==3
2, 0, 2,
0, -8, 0,
2, 0, 2,
#endif
#if SIZE_X==5
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, -24, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
#endif
};
// host memory for image of of width x height pixels
unsigned char *host_in = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *host_out = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *reference_in = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *reference_out = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
// initialize data
for (int y=0; y<height; ++y) {
for (int x=0; x<width; ++x) {
host_in[y*width + x] = (unsigned char)(y*width + x) % 256;
reference_in[y*width + x] = (unsigned char)(y*width + x) % 256;
host_out[y*width + x] = 0;
reference_out[y*width + x] = 0;
}
}
// input and output image of width x height pixels
Image<unsigned char> IN(width, height);
Image<unsigned char> OUT(width, height);
// filter mask
Mask<int> M(size_x, size_y);
M = mask;
IterationSpace<unsigned char> IsOut(OUT);
IN = host_in;
OUT = host_out;
#ifndef OpenCV
fprintf(stderr, "Calculating Laplace filter ...\n");
// BOUNDARY_UNDEFINED
#ifdef RUN_UNDEF
BoundaryCondition<unsigned char> BcInUndef(IN, size_x, BOUNDARY_UNDEFINED);
Accessor<unsigned char> AccInUndef(BcInUndef);
LaplaceFilter LFU(IsOut, AccInUndef, M, size_x);
LFU.execute();
timing = hipaccGetLastKernelTiming();
#endif
timings.push_back(timing);
fprintf(stderr, "HIPACC (UNDEFINED): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_CLAMP
BoundaryCondition<unsigned char> BcInClamp(IN, size_x, BOUNDARY_CLAMP);
Accessor<unsigned char> AccInClamp(BcInClamp);
LaplaceFilter LFC(IsOut, AccInClamp, M, size_x);
LFC.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (CLAMP): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_REPEAT
BoundaryCondition<unsigned char> BcInRepeat(IN, size_x, BOUNDARY_REPEAT);
Accessor<unsigned char> AccInRepeat(BcInRepeat);
LaplaceFilter LFR(IsOut, AccInRepeat, M, size_x);
LFR.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (REPEAT): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_MIRROR
BoundaryCondition<unsigned char> BcInMirror(IN, size_x, BOUNDARY_MIRROR);
Accessor<unsigned char> AccInMirror(BcInMirror);
LaplaceFilter LFM(IsOut, AccInMirror, M, size_x);
LFM.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (MIRROR): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_CONSTANT
BoundaryCondition<unsigned char> BcInConst(IN, size_x, BOUNDARY_CONSTANT, '1');
Accessor<unsigned char> AccInConst(BcInConst);
LaplaceFilter LFConst(IsOut, AccInConst, M, size_x);
LFConst.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (CONSTANT): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// get results
host_out = OUT.getData();
#endif
#ifdef OpenCV
#ifdef CPU
fprintf(stderr, "\nCalculating OpenCV Laplacian filter on the CPU ...\n");
#else
fprintf(stderr, "\nCalculating OpenCV Laplacian filter on the GPU ...\n");
#endif
cv::Mat cv_data_in(height, width, CV_8UC1, host_in);
cv::Mat cv_data_out(height, width, CV_8UC1, host_out);
int ddepth = CV_8U;
double scale = 1.0f;
double delta = 0.0f;
for (int brd_type=0; brd_type<5; brd_type++) {
#ifdef CPU
if (brd_type==cv::BORDER_WRAP) {
// BORDER_WRAP is not supported on the CPU by OpenCV
timings.push_back(0.0f);
continue;
}
min_dt = DBL_MAX;
for (int nt=0; nt<10; nt++) {
time0 = time_ms();
cv::Laplacian(cv_data_in, cv_data_out, ddepth, size_x, scale, delta, brd_type);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
#else
#if SIZE_X==5
#error "OpenCV supports only 1x1 and 3x3 Laplace filters on the GPU!"
#endif
cv::gpu::GpuMat gpu_in, gpu_out;
gpu_in.upload(cv_data_in);
min_dt = DBL_MAX;
for (int nt=0; nt<10; nt++) {
time0 = time_ms();
cv::gpu::Laplacian(gpu_in, gpu_out, -1, size_x, scale, brd_type);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
gpu_out.download(cv_data_out);
#endif
fprintf(stderr, "OpenCV(");
switch (brd_type) {
case IPL_BORDER_CONSTANT:
fprintf(stderr, "CONSTANT");
break;
case IPL_BORDER_REPLICATE:
fprintf(stderr, "CLAMP");
break;
case IPL_BORDER_REFLECT:
fprintf(stderr, "MIRROR");
break;
case IPL_BORDER_WRAP:
fprintf(stderr, "REPEAT");
break;
case IPL_BORDER_REFLECT_101:
fprintf(stderr, "MIRROR_101");
break;
default:
break;
}
timings.push_back(min_dt);
fprintf(stderr, "): %.3f ms, %.3f Mpixel/s\n", min_dt, (width*height/min_dt)/1000);
}
#endif
// print statistics
for (unsigned int i=0; i<timings.size(); i++) {
fprintf(stderr, "\t%.3f", timings.data()[i]);
}
fprintf(stderr, "\n\n");
fprintf(stderr, "\nCalculating reference ...\n");
min_dt = DBL_MAX;
for (int nt=0; nt<3; nt++) {
time0 = time_ms();
// calculate reference
laplace_filter(reference_in, reference_out, (int *)mask, size_x, width, height);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
fprintf(stderr, "Reference: %.3f ms, %.3f Mpixel/s\n", min_dt, (width*height/min_dt)/1000);
fprintf(stderr, "\nComparing results ...\n");
#ifdef OpenCV
int upper_y = height-size_y+offset_y;
int upper_x = width-size_x+offset_x;
#else
int upper_y = height-offset_y;
int upper_x = width-offset_x;
#endif
// compare results
for (int y=offset_y; y<upper_y; y++) {
for (int x=offset_x; x<upper_x; x++) {
if (reference_out[y*width + x] != host_out[y*width + x]) {
fprintf(stderr, "Test FAILED, at (%d,%d): %d vs. %d\n", x,
y, reference_out[y*width + x], host_out[y*width + x]);
exit(EXIT_FAILURE);
}
}
}
fprintf(stderr, "Test PASSED\n");
// memory cleanup
free(host_in);
//free(host_out);
free(reference_in);
free(reference_out);
return EXIT_SUCCESS;
}
|
//
// Copyright (c) 2012, University of Erlangen-Nuremberg
// Copyright (c) 2012, Siemens AG
// 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <iostream>
#include <vector>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef OpenCV
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#endif
#include "hipacc.hpp"
// variables set by Makefile
//#define SIZE_X 3
//#define SIZE_Y 3
//#define WIDTH 4096
//#define HEIGHT 4096
//#define CPU
#define CONST_MASK
#define USE_LAMBDA
//#define RUN_UNDEF
using namespace hipacc;
using namespace hipacc::math;
// get time in milliseconds
double time_ms () {
struct timeval tv;
gettimeofday (&tv, NULL);
return ((double)(tv.tv_sec) * 1e+3 + (double)(tv.tv_usec) * 1e-3);
}
// Laplace filter reference
void laplace_filter(unsigned char *in, unsigned char *out, int *filter, int
size, int width, int height) {
const int size_x = size;
const int size_y = size;
int anchor_x = size_x >> 1;
int anchor_y = size_y >> 1;
#ifdef OpenCV
int upper_x = width-size_x+anchor_x;
int upper_y = height-size_y+anchor_y;
#else
int upper_x = width-anchor_x;
int upper_y = height-anchor_y;
#endif
for (int y=anchor_y; y<upper_y; ++y) {
for (int x=anchor_x; x<upper_x; ++x) {
int sum = 0;
for (int yf = -anchor_y; yf<=anchor_y; yf++) {
for (int xf = -anchor_x; xf<=anchor_x; xf++) {
sum += filter[(yf+anchor_y)*size_x + xf+anchor_x]*in[(y+yf)*width + x + xf];
}
}
sum = min(sum, 255);
sum = max(sum, 0);
out[y*width + x] = sum;
}
}
}
// Laplace filter in HIPAcc
class LaplaceFilter : public Kernel<unsigned char> {
private:
Accessor<unsigned char> &Input;
Domain &cDom;
Mask<int> &cMask;
const int size;
public:
LaplaceFilter(IterationSpace<unsigned char> &IS, Accessor<unsigned char>
&Input, Domain &cDom, Mask<int> &cMask, const int size) :
Kernel(IS),
Input(Input),
cDom(cDom),
cMask(cMask),
size(size)
{ addAccessor(&Input); }
#ifdef USE_LAMBDA
void kernel() {
int sum = reduce(cDom, HipaccSUM, [&] () -> int {
return cMask(cDom) * Input(cDom);
});
sum = min(sum, 255);
sum = max(sum, 0);
output() = (unsigned char) (sum);
}
#else
void kernel() {
const int anchor = size >> 1;
int sum = 0;
for (int yf = -anchor; yf<=anchor; yf++) {
for (int xf = -anchor; xf<=anchor; xf++) {
sum += cMask(xf, yf)*Input(xf, yf);
}
}
sum = min(sum, 255);
sum = max(sum, 0);
output() = (unsigned char) (sum);
}
#endif
};
/*************************************************************************
* Main function *
*************************************************************************/
int main(int argc, const char **argv) {
double time0, time1, dt, min_dt;
const int width = WIDTH;
const int height = HEIGHT;
const int size_x = SIZE_X;
const int size_y = SIZE_Y;
const int offset_x = size_x >> 1;
const int offset_y = size_y >> 1;
std::vector<float> timings;
float timing = 0.0f;
// only filter kernel sizes 3x3 and 5x5 supported
if (size_x != size_y || !(size_x == 3 || size_x == 5)) {
fprintf(stderr, "Wrong filter kernel size. Currently supported values: 3x3 and 5x5!\n");
exit(EXIT_FAILURE);
}
// convolution filter mask
#ifdef CONST_MASK
const
#endif
int mask[SIZE_Y][SIZE_X] = {
#if SIZE_X==1
{ 0, 1, 0 },
{ 1, -4, 1 },
{ 0, 1, 0 }
#endif
#if SIZE_X==3
{ 2, 0, 2 },
{ 0, -8, 0 },
{ 2, 0, 2 }
#endif
#if SIZE_X==5
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, -24, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 }
#endif
};
// host memory for image of of width x height pixels
unsigned char *host_in = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *host_out = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *reference_in = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
unsigned char *reference_out = (unsigned char *)malloc(sizeof(unsigned char)*width*height);
// initialize data
for (int y=0; y<height; ++y) {
for (int x=0; x<width; ++x) {
host_in[y*width + x] = (unsigned char)(y*width + x) % 256;
reference_in[y*width + x] = (unsigned char)(y*width + x) % 256;
host_out[y*width + x] = 0;
reference_out[y*width + x] = 0;
}
}
// input and output image of width x height pixels
Image<unsigned char> IN(width, height);
Image<unsigned char> OUT(width, height);
// filter mask
Mask<int> M(mask);
#ifdef CONST_MASK
Domain D(M);
#else
Domain D(size_x, size_y);
#endif
IterationSpace<unsigned char> IsOut(OUT);
IN = host_in;
OUT = host_out;
#ifndef OpenCV
fprintf(stderr, "Calculating Laplace filter ...\n");
// BOUNDARY_UNDEFINED
#ifdef RUN_UNDEF
BoundaryCondition<unsigned char> BcInUndef(IN, size_x, BOUNDARY_UNDEFINED);
Accessor<unsigned char> AccInUndef(BcInUndef);
LaplaceFilter LFU(IsOut, AccInUndef, D, M, size_x);
LFU.execute();
timing = hipaccGetLastKernelTiming();
#endif
timings.push_back(timing);
fprintf(stderr, "HIPACC (UNDEFINED): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_CLAMP
BoundaryCondition<unsigned char> BcInClamp(IN, size_x, BOUNDARY_CLAMP);
Accessor<unsigned char> AccInClamp(BcInClamp);
LaplaceFilter LFC(IsOut, AccInClamp, D, M, size_x);
LFC.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (CLAMP): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_REPEAT
BoundaryCondition<unsigned char> BcInRepeat(IN, size_x, BOUNDARY_REPEAT);
Accessor<unsigned char> AccInRepeat(BcInRepeat);
LaplaceFilter LFR(IsOut, AccInRepeat, D, M, size_x);
LFR.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (REPEAT): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_MIRROR
BoundaryCondition<unsigned char> BcInMirror(IN, size_x, BOUNDARY_MIRROR);
Accessor<unsigned char> AccInMirror(BcInMirror);
LaplaceFilter LFM(IsOut, AccInMirror, D, M, size_x);
LFM.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (MIRROR): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// BOUNDARY_CONSTANT
BoundaryCondition<unsigned char> BcInConst(IN, size_x, BOUNDARY_CONSTANT, '1');
Accessor<unsigned char> AccInConst(BcInConst);
LaplaceFilter LFConst(IsOut, AccInConst, D, M, size_x);
LFConst.execute();
timing = hipaccGetLastKernelTiming();
timings.push_back(timing);
fprintf(stderr, "HIPACC (CONSTANT): %.3f ms, %.3f Mpixel/s\n", timing, (width*height/timing)/1000);
// get results
host_out = OUT.getData();
#endif
#ifdef OpenCV
#ifdef CPU
fprintf(stderr, "\nCalculating OpenCV Laplacian filter on the CPU ...\n");
#else
fprintf(stderr, "\nCalculating OpenCV Laplacian filter on the GPU ...\n");
#endif
cv::Mat cv_data_in(height, width, CV_8UC1, host_in);
cv::Mat cv_data_out(height, width, CV_8UC1, host_out);
int ddepth = CV_8U;
double scale = 1.0f;
double delta = 0.0f;
for (int brd_type=0; brd_type<5; brd_type++) {
#ifdef CPU
if (brd_type==cv::BORDER_WRAP) {
// BORDER_WRAP is not supported on the CPU by OpenCV
timings.push_back(0.0f);
continue;
}
min_dt = DBL_MAX;
for (int nt=0; nt<10; nt++) {
time0 = time_ms();
cv::Laplacian(cv_data_in, cv_data_out, ddepth, size_x, scale, delta, brd_type);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
#else
#if SIZE_X==5
#error "OpenCV supports only 1x1 and 3x3 Laplace filters on the GPU!"
#endif
cv::gpu::GpuMat gpu_in, gpu_out;
gpu_in.upload(cv_data_in);
min_dt = DBL_MAX;
for (int nt=0; nt<10; nt++) {
time0 = time_ms();
cv::gpu::Laplacian(gpu_in, gpu_out, -1, size_x, scale, brd_type);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
gpu_out.download(cv_data_out);
#endif
fprintf(stderr, "OpenCV(");
switch (brd_type) {
case IPL_BORDER_CONSTANT:
fprintf(stderr, "CONSTANT");
break;
case IPL_BORDER_REPLICATE:
fprintf(stderr, "CLAMP");
break;
case IPL_BORDER_REFLECT:
fprintf(stderr, "MIRROR");
break;
case IPL_BORDER_WRAP:
fprintf(stderr, "REPEAT");
break;
case IPL_BORDER_REFLECT_101:
fprintf(stderr, "MIRROR_101");
break;
default:
break;
}
timings.push_back(min_dt);
fprintf(stderr, "): %.3f ms, %.3f Mpixel/s\n", min_dt, (width*height/min_dt)/1000);
}
#endif
// print statistics
for (unsigned int i=0; i<timings.size(); i++) {
fprintf(stderr, "\t%.3f", timings.data()[i]);
}
fprintf(stderr, "\n\n");
fprintf(stderr, "\nCalculating reference ...\n");
min_dt = DBL_MAX;
for (int nt=0; nt<3; nt++) {
time0 = time_ms();
// calculate reference
laplace_filter(reference_in, reference_out, (int *)mask, size_x, width, height);
time1 = time_ms();
dt = time1 - time0;
if (dt < min_dt) min_dt = dt;
}
fprintf(stderr, "Reference: %.3f ms, %.3f Mpixel/s\n", min_dt, (width*height/min_dt)/1000);
fprintf(stderr, "\nComparing results ...\n");
#ifdef OpenCV
int upper_y = height-size_y+offset_y;
int upper_x = width-size_x+offset_x;
#else
int upper_y = height-offset_y;
int upper_x = width-offset_x;
#endif
// compare results
for (int y=offset_y; y<upper_y; y++) {
for (int x=offset_x; x<upper_x; x++) {
if (reference_out[y*width + x] != host_out[y*width + x]) {
fprintf(stderr, "Test FAILED, at (%d,%d): %d vs. %d\n", x,
y, reference_out[y*width + x], host_out[y*width + x]);
exit(EXIT_FAILURE);
}
}
}
fprintf(stderr, "Test PASSED\n");
// memory cleanup
free(host_in);
//free(host_out);
free(reference_in);
free(reference_out);
return EXIT_SUCCESS;
}
|
Use Domain for Laplace and applied new syntax
|
Tests: Use Domain for Laplace and applied new syntax
|
C++
|
bsd-2-clause
|
hipacc/hipacc-vivado,hipacc/hipacc,hipacc/hipacc,hipacc/hipacc-vivado,hipacc/hipacc-vivado
|
199476d912dba7b480c2d94037841606455d6608
|
src/libraries/UtilsLib/Macros.hpp
|
src/libraries/UtilsLib/Macros.hpp
|
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#ifndef __RD_MACROS_HPP__
#define __RD_MACROS_HPP__
#include <stdio.h>
#include <string> // std::string
#include <string.h> // strrchr
//-- Thanks http://stackoverflow.com/questions/8487986/file-macro-shows-full-path
#ifdef WIN32
#define __REL_FILE__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#else
#define __REL_FILE__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
#ifdef WIN32
// Could be implemented for Win10: http://stackoverflow.com/a/38617204
#define RESET ""
#define BLACK "" /* Black */
#define RED "" /* Red */
#define GREEN "" /* Green */
#define YELLOW "" /* Yellow */
#define BLUE "" /* Blue */
#define MAGENTA "" /* Magenta */
#define CYAN "" /* Cyan */
#define WHITE "" /* White */
#define BOLDBLACK "" /* Bold Black */
#define BOLDRED "" /* Bold Red */
#define BOLDGREEN "" /* Bold Green */
#define BOLDYELLOW "" /* Bold Yellow */
#define BOLDBLUE "" /* Bold Blue */
#define BOLDMAGENTA "" /* Bold Magenta */
#define BOLDCYAN "" /* Bold Cyan */
#define BOLDWHITE "" /* Bold White */
#else
// http://stackoverflow.com/questions/1961209/making-some-text-in-printf-appear-in-green-and-red
#define RESET "\033[0m"
#define BLACK "\033[30m" /* Black */
#define RED "\033[31m" /* Red */
#define GREEN "\033[32m" /* Green */
#define YELLOW "\033[33m" /* Yellow */
#define BLUE "\033[34m" /* Blue */
#define MAGENTA "\033[35m" /* Magenta */
#define CYAN "\033[36m" /* Cyan */
#define WHITE "\033[37m" /* White */
#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */
#define BOLDRED "\033[1m\033[31m" /* Bold Red */
#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */
#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */
#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */
#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */
#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */
#define BOLDWHITE "\033[1m\033[37m" /* Bold White */
#endif
// http://en.wikipedia.org/wiki/Variadic_macro
// http://stackoverflow.com/questions/15549893/modify-printfs-via-macro-to-include-file-and-line-number-information
#define RD_ERROR(...) { fprintf(stderr,RED); do{fprintf(stderr, "[error] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
fprintf(stderr, __VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_WARNING(...) { fprintf(stderr,YELLOW); do{fprintf(stderr, "[warning] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
fprintf(stderr, __VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_SUCCESS(...) { fprintf(stderr,GREEN); do{printf("[success] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_INFO(...) { do{printf("[info] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); }
#define RD_DEBUG(...) { fprintf(stderr,BLUE); do{printf("[debug] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#endif // __RD_MACROS_HPP__
|
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#ifndef __RD_MACROS_HPP__
#define __RD_MACROS_HPP__
#include <stdio.h>
#include <string> // std::string
#include <string.h> // strrchr
//-- Fix for old Windows versions.
//-- Thanks: tomlogic @ http://stackoverflow.com/questions/2281970/cross-platform-defining-define-for-macros-function-and-func
#if defined(WIN32) && !defined(__func__)
#define __func__ __FUNCTION__
#endif
//-- Thanks http://stackoverflow.com/questions/8487986/file-macro-shows-full-path
#ifdef WIN32
#define __REL_FILE__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#else
#define __REL_FILE__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
#ifdef WIN32
// Could be implemented for Win10: http://stackoverflow.com/a/38617204
#define RESET ""
#define BLACK "" /* Black */
#define RED "" /* Red */
#define GREEN "" /* Green */
#define YELLOW "" /* Yellow */
#define BLUE "" /* Blue */
#define MAGENTA "" /* Magenta */
#define CYAN "" /* Cyan */
#define WHITE "" /* White */
#define BOLDBLACK "" /* Bold Black */
#define BOLDRED "" /* Bold Red */
#define BOLDGREEN "" /* Bold Green */
#define BOLDYELLOW "" /* Bold Yellow */
#define BOLDBLUE "" /* Bold Blue */
#define BOLDMAGENTA "" /* Bold Magenta */
#define BOLDCYAN "" /* Bold Cyan */
#define BOLDWHITE "" /* Bold White */
#else
// http://stackoverflow.com/questions/1961209/making-some-text-in-printf-appear-in-green-and-red
#define RESET "\033[0m"
#define BLACK "\033[30m" /* Black */
#define RED "\033[31m" /* Red */
#define GREEN "\033[32m" /* Green */
#define YELLOW "\033[33m" /* Yellow */
#define BLUE "\033[34m" /* Blue */
#define MAGENTA "\033[35m" /* Magenta */
#define CYAN "\033[36m" /* Cyan */
#define WHITE "\033[37m" /* White */
#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */
#define BOLDRED "\033[1m\033[31m" /* Bold Red */
#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */
#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */
#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */
#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */
#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */
#define BOLDWHITE "\033[1m\033[37m" /* Bold White */
#endif
// http://en.wikipedia.org/wiki/Variadic_macro
// http://stackoverflow.com/questions/15549893/modify-printfs-via-macro-to-include-file-and-line-number-information
#define RD_ERROR(...) { fprintf(stderr,RED); do{fprintf(stderr, "[error] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
fprintf(stderr, __VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_WARNING(...) { fprintf(stderr,YELLOW); do{fprintf(stderr, "[warning] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
fprintf(stderr, __VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_SUCCESS(...) { fprintf(stderr,GREEN); do{printf("[success] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#define RD_INFO(...) { do{printf("[info] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); }
#define RD_DEBUG(...) { fprintf(stderr,BLUE); do{printf("[debug] %s:%d %s(): ", __REL_FILE__, __LINE__, __func__); \
printf(__VA_ARGS__);} while(0); fprintf(stderr,RESET); }
#endif // __RD_MACROS_HPP__
|
Fix undefined __func__ macro on Windows
|
Fix undefined __func__ macro on Windows
Borrowed from color-debug.
|
C++
|
lgpl-2.1
|
asrob-uc3m/robotDevastation,asrob-uc3m/robotDevastation
|
36f40d96cd1d8f3f2a9095b1a190ddf9c6c223ce
|
streetname_fixer.cpp
|
streetname_fixer.cpp
|
/*
Copyright (c) 2014, Patrick Niklaus
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <unordered_map>
#include <fstream>
#include <osmium/io/pbf_input.hpp>
#include <osmium/tags/filter.hpp>
#include <osmium/index/multimap/vector.hpp>
struct ParsedWay
{
ParsedWay(osmium::object_id_type id,
unsigned long firstNodeId,
unsigned long lastNodeId,
unsigned nameId,
unsigned refID)
: id(id)
, firstNodeId(firstNodeId)
, lastNodeId(lastNodeId)
, nameId(nameId)
, refID(refID)
{
}
osmium::object_id_type id;
osmium::object_id_type firstNodeId;
osmium::object_id_type lastNodeId;
unsigned nameId;
unsigned refID;
};
using EndpointWayMapT = osmium::index::multimap::VectorBasedSparseMultimap<unsigned long, unsigned, std::vector>;
using StringTableT = std::vector<std::string>;
using ParsedWayVectorT = std::vector<ParsedWay>;
constexpr unsigned NO_NAME_ID = 0;
class BufferParser
{
public:
BufferParser()
: noncar_filer(true)
, endpoint_way_map(new EndpointWayMapT())
, parsed_ways(new ParsedWayVectorT())
, string_table(new StringTableT())
{
highway_filter.add(true, "highway");
noncar_filer.add(false, "highway", "footway");
noncar_filer.add(false, "highway", "cycleway");
noncar_filer.add(false, "highway", "steps");
noncar_filer.add(false, "highway", "path");
getStringID("");
}
void operator()(const osmium::memory::Buffer& buffer)
{
for (const auto& item : buffer)
{
if (item.type() == osmium::item_type::way)
{
parseWay(static_cast<const osmium::Way&>(item));
}
}
}
std::unique_ptr<EndpointWayMapT> getEndpointWayMap()
{
return std::move(endpoint_way_map);
}
std::unique_ptr<ParsedWayVectorT> getParsedWays()
{
return std::move(parsed_ways);
}
std::unique_ptr<StringTableT> getStringTable()
{
return std::move(string_table);
}
private:
inline void parseWay(const osmium::Way& way)
{
const auto& tags = way.tags();
auto it = std::find_if(tags.begin(), tags.end(), highway_filter);
if (it == tags.end())
{
return;
}
it = std::find_if(tags.begin(), tags.end(), noncar_filer);
if (it == tags.end())
{
return;
}
const char* name = tags.get_value_by_key("name", "");
const char* ref = tags.get_value_by_key("ref", "");
unsigned name_id = getStringID(name);
unsigned ref_id = getStringID(ref);
const osmium::NodeRef& first = way.nodes().front();
const osmium::NodeRef& last = way.nodes().back();
// we can't use osmium ids because MultiMap expects unsigned keys
unsigned long firstID = static_cast<unsigned long>(first.ref());
unsigned long lastID = static_cast<unsigned long>(last.ref());
const unsigned wayIdx = parsed_ways->size();
endpoint_way_map->unsorted_set(firstID, wayIdx);
endpoint_way_map->unsorted_set(lastID, wayIdx);
parsed_ways->emplace_back(way.id(), firstID, lastID, name_id, ref_id);
}
inline unsigned getStringID(const char* str)
{
auto it = string_id_map.find(str);
if (it == string_id_map.end())
{
string_id_map[str] = string_table->size();
string_table->push_back(str);
return string_table->size() - 1;
}
return it->second;
}
osmium::tags::KeyFilter highway_filter;
osmium::tags::KeyValueFilter noncar_filer;
std::unique_ptr<EndpointWayMapT> endpoint_way_map;
std::unique_ptr<ParsedWayVectorT> parsed_ways;
std::unique_ptr<StringTableT> string_table;
std::unordered_map<std::string, unsigned> string_id_map;
};
struct MissingNameError
{
MissingNameError(osmium::object_id_type startWay,
osmium::object_id_type enclosedWay,
osmium::object_id_type endWay,
unsigned name_id)
: startWay(startWay)
, enclosedWay(enclosedWay)
, endWay(endWay)
, name_id(name_id)
{
}
osmium::object_id_type startWay;
osmium::object_id_type enclosedWay;
osmium::object_id_type endWay;
unsigned name_id;
};
class MissingNameDetector
{
public:
MissingNameDetector(const EndpointWayMapT& endpoint_way_map,
const ParsedWayVectorT& parsed_ways)
: endpoint_way_map(endpoint_way_map)
, parsed_ways(parsed_ways)
{
}
std::vector<MissingNameError> operator()() const
{
std::vector<MissingNameError> errors;
unsigned no_names = 0;
for (const auto& way : parsed_ways)
{
// skip named streets
if (way.nameId != NO_NAME_ID)
{
continue;
}
no_names++;
const auto beforeWayRange = endpoint_way_map.get_all(way.firstNodeId);
const auto afterWayRange = endpoint_way_map.get_all(way.lastNodeId);
for (auto beforeIt = beforeWayRange.first; beforeIt != beforeWayRange.second; beforeIt++)
{
const auto& beforeWay = parsed_ways[beforeIt->second];
for (auto afterIt = afterWayRange.first; afterIt != afterWayRange.second; afterIt++)
{
const auto& afterWay = parsed_ways[afterIt->second];
// Found enclosing ways with same name
if (beforeWay.nameId != NO_NAME_ID && beforeWay.nameId == afterWay.nameId)
{
errors.emplace_back(beforeWay.id, way.id, afterWay.id, beforeWay.nameId);
}
}
}
}
std::sort(errors.begin(), errors.end(),
[](const MissingNameError& e1, const MissingNameError& e2)
{
return e1.enclosedWay < e2.enclosedWay;
}
);
std::vector<MissingNameError> unique_errors;
unique_errors.reserve(errors.size());
// Remove errors for the same enclosed way that suggest the same name
std::unique_copy(errors.begin(), errors.end(), std::back_inserter(unique_errors),
[](const MissingNameError& e1, const MissingNameError& e2)
{
return (e1.enclosedWay == e2.enclosedWay) && (e1.name_id == e2.name_id);
}
);
std::cout << "Number of ways without name: " << no_names << std::endl;
return unique_errors;
}
const EndpointWayMapT& endpoint_way_map;
const ParsedWayVectorT& parsed_ways;
};
void parseInput(const char* path,
std::unique_ptr<EndpointWayMapT>& endpoint_way_map,
std::unique_ptr<ParsedWayVectorT>& parsed_ways,
std::unique_ptr<StringTableT>& string_table )
{
osmium::io::File input(path);
osmium::io::Reader reader(input, osmium::osm_entity_bits::way);
std::cout << "Parsing... " << std::flush;
BufferParser parser;
while (osmium::memory::Buffer buffer = reader.read()) {
parser(buffer);
}
std::cout << " ok." << std::endl;
endpoint_way_map = std::move(parser.getEndpointWayMap());
// after the insersion finished we need to build the index
endpoint_way_map->consolidate();
parsed_ways = std::move(parser.getParsedWays());
string_table = std::move(parser.getStringTable());
std::cout << "Number of parsed ways: " << parsed_ways->size() << std::endl;
}
void writeOutput(const std::vector<MissingNameError>& errors, const StringTableT& string_table, const char* path)
{
std::ofstream output(path);
output << "prev_way_id,enclosed_way_id,next_way_id,name,name_id" << std::endl;
for (const auto& e : errors)
{
output << e.startWay << "," << e.enclosedWay << "," << e.endWay << "," << string_table[e.name_id] << "," << e.name_id << std::endl;
}
}
int main (int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "Error: Not enough arguments.\nUsage: ./streetname_fixer INPUT.pbf" << std::endl;
return 1;
}
char* input_file_path = argv[1];
std::unique_ptr<EndpointWayMapT> endpoint_way_map;
std::unique_ptr<ParsedWayVectorT> parsed_ways;
std::unique_ptr<StringTableT> string_table;
parseInput(input_file_path, endpoint_way_map, parsed_ways, string_table);
MissingNameDetector detector(*endpoint_way_map, *parsed_ways);
std::vector<MissingNameError> errors = detector();
writeOutput(errors, *string_table, "nonames.csv");
std::cout << "Number of errors: " << errors.size() << std::endl;
return 0;
}
|
/*
Copyright (c) 2014, Patrick Niklaus
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <unordered_map>
#include <fstream>
#include <osmium/io/pbf_input.hpp>
#include <osmium/tags/filter.hpp>
#include <osmium/index/multimap/vector.hpp>
struct ParsedWay
{
ParsedWay(osmium::object_id_type id,
unsigned long firstNodeId,
unsigned long lastNodeId,
unsigned nameId,
unsigned refID)
: id(id)
, firstNodeId(firstNodeId)
, lastNodeId(lastNodeId)
, nameId(nameId)
, refID(refID)
{
}
osmium::object_id_type id;
osmium::object_id_type firstNodeId;
osmium::object_id_type lastNodeId;
unsigned nameId;
unsigned refID;
};
using EndpointWayMapT = osmium::index::multimap::VectorBasedSparseMultimap<unsigned long, unsigned, std::vector>;
using StringTableT = std::vector<std::string>;
using ParsedWayVectorT = std::vector<ParsedWay>;
constexpr unsigned NO_NAME_ID = 0;
class BufferParser
{
public:
BufferParser()
: endpoint_way_map(new EndpointWayMapT())
, parsed_ways(new ParsedWayVectorT())
, string_table(new StringTableT())
{
highway_filter.add(true, "highway", "trunk");
highway_filter.add(true, "highway", "motorway");
highway_filter.add(true, "highway", "primary");
highway_filter.add(true, "highway", "secondary");
highway_filter.add(true, "highway", "tertiary");
highway_filter.add(true, "highway", "trunk_link");
highway_filter.add(true, "highway", "motorway_link");
highway_filter.add(true, "highway", "primary_link");
highway_filter.add(true, "highway", "secondary_link");
highway_filter.add(true, "highway", "tertiary_link");
highway_filter.add(true, "highway", "residential");
highway_filter.add(true, "highway", "service");
getStringID("");
}
void operator()(const osmium::memory::Buffer& buffer)
{
for (const auto& item : buffer)
{
if (item.type() == osmium::item_type::way)
{
parseWay(static_cast<const osmium::Way&>(item));
}
}
}
std::unique_ptr<EndpointWayMapT> getEndpointWayMap()
{
return std::move(endpoint_way_map);
}
std::unique_ptr<ParsedWayVectorT> getParsedWays()
{
return std::move(parsed_ways);
}
std::unique_ptr<StringTableT> getStringTable()
{
return std::move(string_table);
}
private:
inline void parseWay(const osmium::Way& way)
{
const auto& tags = way.tags();
auto it = std::find_if(tags.begin(), tags.end(), highway_filter);
if (it == tags.end())
{
return;
}
const char* name = tags.get_value_by_key("name", "");
const char* ref = tags.get_value_by_key("ref", "");
unsigned name_id = getStringID(name);
unsigned ref_id = getStringID(ref);
const osmium::NodeRef& first = way.nodes().front();
const osmium::NodeRef& last = way.nodes().back();
// we can't use osmium ids because MultiMap expects unsigned keys
unsigned long firstID = static_cast<unsigned long>(first.ref());
unsigned long lastID = static_cast<unsigned long>(last.ref());
const unsigned wayIdx = parsed_ways->size();
endpoint_way_map->unsorted_set(firstID, wayIdx);
endpoint_way_map->unsorted_set(lastID, wayIdx);
parsed_ways->emplace_back(way.id(), firstID, lastID, name_id, ref_id);
}
inline unsigned getStringID(const char* str)
{
auto it = string_id_map.find(str);
if (it == string_id_map.end())
{
string_id_map[str] = string_table->size();
string_table->push_back(str);
return string_table->size() - 1;
}
return it->second;
}
osmium::tags::KeyValueFilter highway_filter;
std::unique_ptr<EndpointWayMapT> endpoint_way_map;
std::unique_ptr<ParsedWayVectorT> parsed_ways;
std::unique_ptr<StringTableT> string_table;
std::unordered_map<std::string, unsigned> string_id_map;
};
struct MissingNameError
{
MissingNameError(osmium::object_id_type startWay,
osmium::object_id_type enclosedWay,
osmium::object_id_type endWay,
unsigned name_id)
: startWay(startWay)
, enclosedWay(enclosedWay)
, endWay(endWay)
, name_id(name_id)
{
}
osmium::object_id_type startWay;
osmium::object_id_type enclosedWay;
osmium::object_id_type endWay;
unsigned name_id;
};
class MissingNameDetector
{
public:
MissingNameDetector(const EndpointWayMapT& endpoint_way_map,
const ParsedWayVectorT& parsed_ways)
: endpoint_way_map(endpoint_way_map)
, parsed_ways(parsed_ways)
{
}
std::vector<MissingNameError> operator()() const
{
std::vector<MissingNameError> errors;
unsigned no_names = 0;
for (const auto& way : parsed_ways)
{
// skip named streets
if (way.nameId != NO_NAME_ID)
{
continue;
}
no_names++;
const auto beforeWayRange = endpoint_way_map.get_all(way.firstNodeId);
const auto afterWayRange = endpoint_way_map.get_all(way.lastNodeId);
for (auto beforeIt = beforeWayRange.first; beforeIt != beforeWayRange.second; beforeIt++)
{
const auto& beforeWay = parsed_ways[beforeIt->second];
for (auto afterIt = afterWayRange.first; afterIt != afterWayRange.second; afterIt++)
{
const auto& afterWay = parsed_ways[afterIt->second];
// Found enclosing ways with same name
if (beforeWay.nameId != NO_NAME_ID && beforeWay.nameId == afterWay.nameId)
{
errors.emplace_back(beforeWay.id, way.id, afterWay.id, beforeWay.nameId);
}
}
}
}
std::sort(errors.begin(), errors.end(),
[](const MissingNameError& e1, const MissingNameError& e2)
{
return e1.enclosedWay < e2.enclosedWay;
}
);
std::vector<MissingNameError> unique_errors;
unique_errors.reserve(errors.size());
// Remove errors for the same enclosed way that suggest the same name
std::unique_copy(errors.begin(), errors.end(), std::back_inserter(unique_errors),
[](const MissingNameError& e1, const MissingNameError& e2)
{
return (e1.enclosedWay == e2.enclosedWay) && (e1.name_id == e2.name_id);
}
);
std::cout << "Number of ways without name: " << no_names << std::endl;
return unique_errors;
}
const EndpointWayMapT& endpoint_way_map;
const ParsedWayVectorT& parsed_ways;
};
void parseInput(const char* path,
std::unique_ptr<EndpointWayMapT>& endpoint_way_map,
std::unique_ptr<ParsedWayVectorT>& parsed_ways,
std::unique_ptr<StringTableT>& string_table )
{
osmium::io::File input(path);
osmium::io::Reader reader(input, osmium::osm_entity_bits::way);
std::cout << "Parsing... " << std::flush;
BufferParser parser;
while (osmium::memory::Buffer buffer = reader.read()) {
parser(buffer);
}
std::cout << " ok." << std::endl;
endpoint_way_map = std::move(parser.getEndpointWayMap());
// after the insersion finished we need to build the index
endpoint_way_map->consolidate();
parsed_ways = std::move(parser.getParsedWays());
string_table = std::move(parser.getStringTable());
std::cout << "Number of parsed ways: " << parsed_ways->size() << std::endl;
}
void writeOutput(const std::vector<MissingNameError>& errors, const StringTableT& string_table, const char* path)
{
std::ofstream output(path);
output << "prev_way_id,enclosed_way_id,next_way_id,name,name_id" << std::endl;
for (const auto& e : errors)
{
output << e.startWay << "," << e.enclosedWay << "," << e.endWay << "," << string_table[e.name_id] << "," << e.name_id << std::endl;
}
}
int main (int argc, char *argv[])
{
if (argc < 2)
{
std::cout << "Error: Not enough arguments.\nUsage: ./streetname_fixer INPUT.pbf" << std::endl;
return 1;
}
char* input_file_path = argv[1];
std::unique_ptr<EndpointWayMapT> endpoint_way_map;
std::unique_ptr<ParsedWayVectorT> parsed_ways;
std::unique_ptr<StringTableT> string_table;
parseInput(input_file_path, endpoint_way_map, parsed_ways, string_table);
MissingNameDetector detector(*endpoint_way_map, *parsed_ways);
std::vector<MissingNameError> errors = detector();
writeOutput(errors, *string_table, "nonames.csv");
std::cout << "Number of errors: " << errors.size() << std::endl;
return 0;
}
|
Use whitelist for highways
|
Use whitelist for highways
|
C++
|
bsd-2-clause
|
TheMarex/streetname-fixer
|
5e49a3832a94577a161e95ccdcfe442bcbb916e8
|
VisualizationBase/src/declarative/AnchorLayoutConstraintSolver.cpp
|
VisualizationBase/src/declarative/AnchorLayoutConstraintSolver.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "AnchorLayoutConstraintSolver.h"
#include "FormElement.h"
#include <lpsolve/lp_lib.h>
namespace Visualization {
AnchorLayoutConstraintSolver::AnchorLayoutConstraintSolver()
{
// TODO Auto-generated constructor stub
}
AnchorLayoutConstraintSolver::~AnchorLayoutConstraintSolver()
{
cleanUpConstraintSolver();
}
void AnchorLayoutConstraintSolver::placeElements(const QVector<FormElement*>& elements, QList<AnchorLayoutAnchor*>& anchors,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// elements already have a minimum size
initializeConstraintSolver(elements.size() * 2);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
for (auto e : elements)
{
int elementIndex = elements.indexOf(e);
QVector<QPair<int, float>> constraintRow = {QPair<int, float>(endVariable(elementIndex), 1.0),
QPair<int, float>(startVariable(elementIndex), -1.0)};
float size;
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
size = (float) e->size(item).width();
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
size = (float) e->size(item).height();
if (e->sizeDependsOnParent(item))
addGreaterEqualConstraint(constraintRow, size);
else
addEqualConstraint(constraintRow, size);
}
// add constraints for each anchor
// placeElement.start + relativePlaceEdgePosition * placeElement.end
// == fixedElement.start + relativeFixedEdgePosition * fixedElement.end + offset
for (auto a : anchors)
{
int placeElementIndex = elements.indexOf(a->placeElement());
int fixedElementIndex = elements.indexOf(a->fixedElement());
QVector<QPair<int, float>> constraintRow =
{
QPair<int, float>(startVariable(placeElementIndex),1 - a->relativePlaceEdgePosition()),
QPair<int, float>(endVariable(placeElementIndex),a->relativePlaceEdgePosition()),
QPair<int, float>(startVariable(fixedElementIndex), -(1 - a->relativeFixedEdgePosition())),
QPair<int, float>(endVariable(fixedElementIndex),-a->relativeFixedEdgePosition())
};
addEqualConstraint(constraintRow, (float) a->offset());
}
// add objective function
// minimize the sum of the sizes of all the elements
QVector<float> objectiveRow;
for (int i=0; i<elements.size(); ++i)
{
objectiveRow.append(-1.0); // start variable of i-th element
objectiveRow.append(1.0); // end variable of i-th element
}
setMinimizeObjective(objectiveRow);
QVector<float> solution = solveConstraints();
cleanUpConstraintSolver();
// Apply the solution
for (int i=0; i<elements.size(); ++i)
{
FormElement* element = elements.at(i);
int size = std::ceil(solution[endVariable(i)] - solution[startVariable(i)]);
int position = std::ceil(solution[startVariable(i)]);
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
{
if (size > element->size(item).width())
element->computeSize(item, size, element->size(item).height());
element->setPos(item, QPoint(position, element->pos(item).y()));
}
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
{
if (size > element->size(item).height())
element->computeSize(item, element->size(item).width(), size);
element->setPos(item, QPoint(element->pos(item).x(), position));
}
}
}
void AnchorLayoutConstraintSolver::addGreaterEqualConstraint(QVector<QPair<int, float>> constraintRow, float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, GE, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::addEqualConstraint(QVector<QPair<int, float>> constraintRow, float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, EQ, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::setMinimizeObjective(QVector<float> objectiveRow)
{
set_add_rowmode(lp_, false);
for (int i=0; i<numVariables_; ++i)
{
columnIndices_[i] = i+1;
rowValues_[i] = (double) objectiveRow[i];
}
bool success = set_obj_fnex(lp_, numVariables_, rowValues_, columnIndices_);
Q_ASSERT(success);
set_minim(lp_);
}
QVector<float> AnchorLayoutConstraintSolver::solveConstraints()
{
set_verbose(lp_, CRITICAL);
solve(lp_);
get_variables(lp_, rowValues_);
QVector<float> result;
for (int i=0; i<numVariables_; ++i)
result.append((float) rowValues_[i]);
return result;
}
void AnchorLayoutConstraintSolver::initializeConstraintSolver(int numVariables)
{
lp_ = make_lp(0, numVariables);
Q_ASSERT(lp_ != nullptr);
rowValues_ = new double[numVariables];
columnIndices_ = new int[numVariables];
numVariables_ = numVariables;
set_add_rowmode(lp_, true);
}
void AnchorLayoutConstraintSolver::cleanUpConstraintSolver()
{
SAFE_DELETE(lp_);
if (rowValues_)
{
delete[] rowValues_;
rowValues_ = nullptr;
}
if (columnIndices_)
{
delete[] columnIndices_;
columnIndices_ = nullptr;
}
numVariables_ = 0;
}
} /* namespace Visualization */
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "AnchorLayoutConstraintSolver.h"
#include "FormElement.h"
#include "VisualizationException.h"
#include <lpsolve/lp_lib.h>
namespace Visualization {
AnchorLayoutConstraintSolver::AnchorLayoutConstraintSolver()
{
// TODO Auto-generated constructor stub
}
AnchorLayoutConstraintSolver::~AnchorLayoutConstraintSolver()
{
cleanUpConstraintSolver();
}
void AnchorLayoutConstraintSolver::placeElements(const QVector<FormElement*>& elements, QList<AnchorLayoutAnchor*>& anchors,
AnchorLayoutAnchor::Orientation orientation, Item* item)
{
// elements already have a minimum size
initializeConstraintSolver(elements.size() * 2);
// add size constraints for each element
// if element's size depends on parent's size
// element.end - element.start >= element.size
// else
// element.end - element.start = element.size
for (auto e : elements)
{
int elementIndex = elements.indexOf(e);
QVector<QPair<int, float>> constraintRow = {QPair<int, float>(endVariable(elementIndex), 1.0),
QPair<int, float>(startVariable(elementIndex), -1.0)};
float size;
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
size = (float) e->size(item).width();
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
size = (float) e->size(item).height();
if (e->sizeDependsOnParent(item))
addGreaterEqualConstraint(constraintRow, size);
else
addEqualConstraint(constraintRow, size);
}
// add constraints for each anchor
// placeElement.start + relativePlaceEdgePosition * placeElement.end
// == fixedElement.start + relativeFixedEdgePosition * fixedElement.end + offset
for (auto a : anchors)
{
int placeElementIndex = elements.indexOf(a->placeElement());
int fixedElementIndex = elements.indexOf(a->fixedElement());
QVector<QPair<int, float>> constraintRow =
{
QPair<int, float>(startVariable(placeElementIndex),1 - a->relativePlaceEdgePosition()),
QPair<int, float>(endVariable(placeElementIndex),a->relativePlaceEdgePosition()),
QPair<int, float>(startVariable(fixedElementIndex), -(1 - a->relativeFixedEdgePosition())),
QPair<int, float>(endVariable(fixedElementIndex),-a->relativeFixedEdgePosition())
};
addEqualConstraint(constraintRow, (float) a->offset());
}
// add objective function
// minimize the sum of the sizes of all the elements
QVector<float> objectiveRow;
for (int i=0; i<elements.size(); ++i)
{
objectiveRow.append(-1.0); // start variable of i-th element
objectiveRow.append(1.0); // end variable of i-th element
}
setMinimizeObjective(objectiveRow);
try
{
QVector<float> solution = solveConstraints();
cleanUpConstraintSolver();
// Apply the solution
for (int i=0; i<elements.size(); ++i)
{
FormElement* element = elements.at(i);
int size = std::ceil(solution[endVariable(i)] - solution[startVariable(i)]);
int position = std::ceil(solution[startVariable(i)]);
if (orientation == AnchorLayoutAnchor::Orientation::Horizontal)
{
if (size > element->size(item).width())
element->computeSize(item, size, element->size(item).height());
element->setPos(item, QPoint(position, element->pos(item).y()));
}
else // orientation == AnchorLayoutAnchor::Orientation::Vertical
{
if (size > element->size(item).height())
element->computeSize(item, element->size(item).width(), size);
element->setPos(item, QPoint(element->pos(item).x(), position));
}
}
}
catch (VisualizationException e)
{
cleanUpConstraintSolver();
throw e;
}
}
void AnchorLayoutConstraintSolver::addGreaterEqualConstraint(QVector<QPair<int, float>> constraintRow, float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, GE, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::addEqualConstraint(QVector<QPair<int, float>> constraintRow, float result)
{
for (int i=0; i<constraintRow.size(); ++i)
{
columnIndices_[i] = constraintRow[i].first + 1;
rowValues_[i] = (double) constraintRow[i].second;
}
bool success = add_constraintex(lp_, constraintRow.size(), rowValues_, columnIndices_, EQ, result);
Q_ASSERT(success);
}
void AnchorLayoutConstraintSolver::setMinimizeObjective(QVector<float> objectiveRow)
{
set_add_rowmode(lp_, false);
for (int i=0; i<numVariables_; ++i)
{
columnIndices_[i] = i+1;
rowValues_[i] = (double) objectiveRow[i];
}
bool success = set_obj_fnex(lp_, numVariables_, rowValues_, columnIndices_);
Q_ASSERT(success);
set_minim(lp_);
}
QVector<float> AnchorLayoutConstraintSolver::solveConstraints()
{
set_verbose(lp_, CRITICAL);
int success = solve(lp_);
if (success != OPTIMAL) throw VisualizationException("Failed to solve anchor constraints.");
get_variables(lp_, rowValues_);
QVector<float> result;
for (int i=0; i<numVariables_; ++i)
result.append((float) rowValues_[i]);
return result;
}
void AnchorLayoutConstraintSolver::initializeConstraintSolver(int numVariables)
{
lp_ = make_lp(0, numVariables);
Q_ASSERT(lp_ != nullptr);
rowValues_ = new double[numVariables];
columnIndices_ = new int[numVariables];
numVariables_ = numVariables;
set_add_rowmode(lp_, true);
}
void AnchorLayoutConstraintSolver::cleanUpConstraintSolver()
{
SAFE_DELETE(lp_);
if (rowValues_)
{
delete[] rowValues_;
rowValues_ = nullptr;
}
if (columnIndices_)
{
delete[] columnIndices_;
columnIndices_ = nullptr;
}
numVariables_ = 0;
}
} /* namespace Visualization */
|
Improve error handling of anchor layout.
|
Improve error handling of anchor layout.
- throw exception if placing fails, instead of just not working
|
C++
|
bsd-3-clause
|
dimitar-asenov/Envision,Vaishal-shah/Envision,patrick-luethi/Envision,lukedirtwalker/Envision,mgalbier/Envision,mgalbier/Envision,Vaishal-shah/Envision,mgalbier/Envision,mgalbier/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,patrick-luethi/Envision,patrick-luethi/Envision,BalzGuenat/Envision,mgalbier/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,BalzGuenat/Envision,patrick-luethi/Envision,dimitar-asenov/Envision,BalzGuenat/Envision,mgalbier/Envision,dimitar-asenov/Envision,BalzGuenat/Envision,BalzGuenat/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision
|
d67d7709a1ffe698768f46ee56c765736c583dfb
|
Code/Demos/RDKit/GettingStarted/sample.cpp
|
Code/Demos/RDKit/GettingStarted/sample.cpp
|
// $Id$
//
// Copyright (C) 2008-2010 Greg Landrum
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
// Can be built with:
// g++ -o sample.exe sample.cpp -I$RDBASE/Code -I$RDBASE/Extern \
// -L$RDBASE/lib -L$RDBASE/bin -lFileParsers -lSmilesParse -lDepictor \
// -lSubstructMatch -lGraphMol -lDataStructs -lRDGeometryLib -lRDGeneral
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// an example of doing some cleaning up of a molecule before
// calling the sanitizeMol function()
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
// remove the aromatic flag on the bond:
(*bondIt)->setIsAromatic(false);
// and cleanup its attached atoms as well (they were
// also marked aromatic when the bond was added)
(*bondIt)->getBeginAtom()->setIsAromatic(false);
(*bondIt)->getEndAtom()->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
CleanupMolecule();
}
|
// $Id$
//
// Copyright (C) 2008-2011 Greg Landrum
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
// Can be built with:
// g++ -o sample.exe sample.cpp -I$RDBASE/Code -I$RDBASE/Extern \
// -L$RDBASE/lib -lChemReactions -lFileParsers -lSmilesParse -lDepictor \
// -lSubstructMatch -lGraphMol -lDataStructs -lRDGeometryLib -lRDGeneral
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/ChemReactions/ReactionParser.h>
#include <GraphMol/ChemReactions/ReactionPickler.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// an example of doing some cleaning up of a molecule before
// calling the sanitizeMol function()
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
// remove the aromatic flag on the bond:
(*bondIt)->setIsAromatic(false);
// and cleanup its attached atoms as well (they were
// also marked aromatic when the bond was added)
(*bondIt)->getBeginAtom()->setIsAromatic(false);
(*bondIt)->getEndAtom()->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
void ReactionDemo(){
// reaction smarts for a crude amide-bond formation definition:
std::string sma="[C:1](=[O:2])[OH].[N:3]>>[O:2]=[C:1][N:3]";
// construct the reaction:
ChemicalReaction *rxn = RxnSmartsToChemicalReaction(sma);
// now initialize it and check for errors:
rxn->initReactantMatchers();
unsigned int nWarn,nError;
rxn->validate(nWarn,nError);
ROMol *mol;
MOL_SPTR_VECT reacts;
// build the list of reactants:
ROMOL_SPTR react1(SmilesToMol("CC(=O)O"));
ROMOL_SPTR react2(SmilesToMol("CCNCC1NC1"));
reacts.push_back(react1);
reacts.push_back(react2);
// run the reaction, it returns a vector of vectors of product molecules:
std::vector<MOL_SPTR_VECT> prods;
prods = rxn->runReactants(reacts);
// for each of the possible applications of the reaction to the reactants:
for(unsigned int i=0;i<prods.size();++i){
BOOST_LOG(rdInfoLog)<<" product set: " <<i<<std::endl;
// for each product of that application:
for(unsigned int j=0;j<prods[i].size();++j){
std::string psmiles=MolToSmiles(*prods[i][j],true);
BOOST_LOG(rdInfoLog)<<" product : " <<j<<" "<<psmiles<<std::endl;
}
}
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
CleanupMolecule();
ReactionDemo();
}
|
add a simple reaction example
|
add a simple reaction example
|
C++
|
bsd-3-clause
|
soerendip42/rdkit,strets123/rdkit,AlexanderSavelyev/rdkit,adalke/rdkit,AlexanderSavelyev/rdkit,strets123/rdkit,bp-kelley/rdkit,adalke/rdkit,strets123/rdkit,ptosco/rdkit,strets123/rdkit,rvianello/rdkit,adalke/rdkit,strets123/rdkit,greglandrum/rdkit,AlexanderSavelyev/rdkit,greglandrum/rdkit,adalke/rdkit,bp-kelley/rdkit,jandom/rdkit,strets123/rdkit,adalke/rdkit,rdkit/rdkit,bp-kelley/rdkit,ptosco/rdkit,soerendip42/rdkit,rdkit/rdkit,bp-kelley/rdkit,rvianello/rdkit,ptosco/rdkit,jandom/rdkit,adalke/rdkit,jandom/rdkit,strets123/rdkit,AlexanderSavelyev/rdkit,ptosco/rdkit,AlexanderSavelyev/rdkit,jandom/rdkit,adalke/rdkit,jandom/rdkit,ptosco/rdkit,rdkit/rdkit,rvianello/rdkit,rvianello/rdkit,greglandrum/rdkit,AlexanderSavelyev/rdkit,soerendip42/rdkit,rdkit/rdkit,rvianello/rdkit,rvianello/rdkit,strets123/rdkit,soerendip42/rdkit,ptosco/rdkit,greglandrum/rdkit,greglandrum/rdkit,bp-kelley/rdkit,greglandrum/rdkit,rdkit/rdkit,jandom/rdkit,greglandrum/rdkit,soerendip42/rdkit,bp-kelley/rdkit,jandom/rdkit,soerendip42/rdkit,rdkit/rdkit,rvianello/rdkit,bp-kelley/rdkit,greglandrum/rdkit,rdkit/rdkit,bp-kelley/rdkit,soerendip42/rdkit,ptosco/rdkit,rvianello/rdkit,jandom/rdkit,AlexanderSavelyev/rdkit,adalke/rdkit,soerendip42/rdkit,AlexanderSavelyev/rdkit,ptosco/rdkit,rdkit/rdkit,AlexanderSavelyev/rdkit
|
986589aa757c3efdd94017f8f2ffa7b8dfe08af9
|
test/correctness/load_library.cpp
|
test/correctness/load_library.cpp
|
#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// This test exercises the ability to override halide_load_library (etc)
// when using JIT code; to do so, it compiles & calls a simple pipeline
// using a Hexagon schedule, since that is known to load a helper library
// in a well-defined way and is unlikely to change a great deal in the
// near future; if this test breaks because of changes to the Hexagon
// runtime (and the way it uses these calls), we may need to revise
// this test to use a custom library of some sort.
namespace {
uint32_t libhalide_hexagon_host_magic_cookie = 0xdeadbeef;
int load_library_calls = 0;
int get_library_symbol_calls = 0;
int error_calls = 0;
void my_error_handler(void* u, const char *msg) {
error_calls++;
printf("Saw error: %s\n", msg);
}
void *my_get_symbol_impl(const char *name) {
fprintf(stderr, "Saw expected get_symbol: %s\n", name);
exit(-1);
}
void *my_load_library_impl(const char *name) {
load_library_calls++;
if (strcmp(name, "libhalide_hexagon_host.so") != 0) {
fprintf(stderr, "Saw unexpected call: load_library(%s)\n", name);
exit(-1);
}
// return a well-known non-null pointer.
return &libhalide_hexagon_host_magic_cookie;
}
void *my_get_library_symbol_impl(void *lib, const char *name) {
get_library_symbol_calls++;
if (lib != &libhalide_hexagon_host_magic_cookie) {
fprintf(stderr, "Saw unexpected call: get_library_symbol(%p, %s)\n", lib, name);
exit(-1);
}
return nullptr;
}
}
int main(int argc, char **argv) {
// These calls are only available for AOT-compiled code:
//
// halide_set_custom_get_symbol(my_get_symbol_impl);
// halide_set_custom_load_library(my_load_library_impl);
// halide_set_custom_get_library_symbol(my_get_library_symbol_impl);
//
// For JIT code, we must use JITSharedRuntime::set_default_handlers().
Internal::JITHandlers handlers;
handlers.custom_get_symbol = my_get_symbol_impl;
handlers.custom_load_library = my_load_library_impl;
handlers.custom_get_library_symbol = my_get_library_symbol_impl;
Internal::JITSharedRuntime::set_default_handlers(handlers);
Var x("x");
Func f("f");
f(x) = cast<int32_t>(x);
Target target = get_jit_target_from_environment().with_feature(Target::HVX_64);
f.hexagon().vectorize(x, 32);
f.set_error_handler(my_error_handler);
Buffer<int32_t> out = f.realize(64, target);
assert(load_library_calls == 1);
assert(get_library_symbol_calls == 1);
assert(error_calls == 1);
printf("Success!\n");
return 0;
}
|
#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// This test exercises the ability to override halide_get_library_symbol (etc)
// when using JIT code; to do so, it compiles & calls a simple pipeline
// using an OpenCL schedule, since that is known to use these calls
// in a (reasonably) well-defined way and is unlikely to change a great deal
// in the near future; additionally, it doesn't require a particular
// feature in LLVM (unlike, say, Hexagon).
namespace {
void my_error_handler(void* u, const char *msg) {
if (!strstr(msg, "OpenCL API not found")) {
fprintf(stderr, "Saw unexpected error: %s\n", msg);
exit(-1);
}
printf("Saw expected error: %s\n", msg);
printf("Success!\n");
exit(0);
}
void *my_get_symbol_impl(const char *name) {
fprintf(stderr, "Saw unexpected call: get_symbol(%s)\n", name);
exit(-1);
}
void *my_load_library_impl(const char *name) {
if (!strstr(name, "OpenCL") && !strstr(name, "opencl")) {
fprintf(stderr, "Saw unexpected call: load_library(%s)\n", name);
exit(-1);
}
printf("Saw load_library: %s\n", name);
return nullptr;
}
void *my_get_library_symbol_impl(void *lib, const char *name) {
if (lib != nullptr || strcmp(name, "clGetPlatformIDs") != 0) {
fprintf(stderr, "Saw unexpected call: get_library_symbol(%p, %s)\n", lib, name);
exit(-1);
}
printf("Saw get_library_symbol: %s\n", name);
return nullptr;
}
}
int main(int argc, char **argv) {
// These calls are only available for AOT-compiled code:
//
// halide_set_custom_get_symbol(my_get_symbol_impl);
// halide_set_custom_load_library(my_load_library_impl);
// halide_set_custom_get_library_symbol(my_get_library_symbol_impl);
//
// For JIT code, we must use JITSharedRuntime::set_default_handlers().
Internal::JITHandlers handlers;
handlers.custom_get_symbol = my_get_symbol_impl;
handlers.custom_load_library = my_load_library_impl;
handlers.custom_get_library_symbol = my_get_library_symbol_impl;
Internal::JITSharedRuntime::set_default_handlers(handlers);
Var x, y;
Func f;
f(x, y) = cast<int32_t>(x + y);
Target target = get_jit_target_from_environment().with_feature(Target::OpenCL);
f.gpu_tile(x, y, 8, 8, TailStrategy::Auto, DeviceAPI::OpenCL);
f.set_error_handler(my_error_handler);
Buffer<int32_t> out = f.realize(64, 64, target);
fprintf(stderr, "Should not get here.\n");
return -1;
}
|
rework load_library test to use OpenCL, not Hexagon
|
rework load_library test to use OpenCL, not Hexagon
Former-commit-id: 5b823a7ea816afff533c8a752ea83731fe8cc8d4
|
C++
|
mit
|
Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide
|
e2d0ebc91a6922350368a50cbc5721f8a5dac08a
|
Infovis/vtkDelimitedTextReader.cxx
|
Infovis/vtkDelimitedTextReader.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDelimitedTextReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkDelimitedTextReader.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkInformation.h"
#include "vtkStringArray.h"
#include "vtkStdString.h"
#include <vtkstd/algorithm>
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDelimitedTextReader, "1.5");
vtkStandardNewMacro(vtkDelimitedTextReader);
struct vtkDelimitedTextReaderInternals
{
ifstream *File;
};
// Forward function reference (definition at bottom :)
static int splitString(const vtkStdString& input,
char fieldDelimiter,
char stringDelimiter,
bool useStringDelimiter,
vtkstd::vector<vtkStdString>& results,
bool includeEmpties=true);
// I need a safe way to read a line of arbitrary length. It exists on
// some platforms but not others so I'm afraid I have to write it
// myself.
static int my_getline(istream& stream, vtkStdString &output, char delim='\n');
// ----------------------------------------------------------------------
vtkDelimitedTextReader::vtkDelimitedTextReader()
{
this->Internals = new vtkDelimitedTextReaderInternals();
this->Internals->File = 0;
this->FileName = 0;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->ReadBuffer = new char[2048];
this->FieldDelimiter = ',';
this->StringDelimiter = '"';
this->UseStringDelimiter = true;
}
// ----------------------------------------------------------------------
vtkDelimitedTextReader::~vtkDelimitedTextReader()
{
this->SetFileName(0);
delete this->ReadBuffer;
delete this->Internals;
}
// ----------------------------------------------------------------------
void vtkDelimitedTextReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "FileName: "
<< (this->FileName ? this->FileName : "(none)") << endl;
os << indent << "Field delimiter: '" << this->FieldDelimiter
<< "'" << endl;
os << indent << "String delimiter: '" << this->StringDelimiter
<< "'" << endl;
os << indent << "UseStringDelimiter: "
<< (this->UseStringDelimiter ? "true" : "false") << endl;
os << indent << "HaveHeaders: "
<< (this->HaveHeaders ? "true" : "false") << endl;
}
// ----------------------------------------------------------------------
void vtkDelimitedTextReader::OpenFile()
{
// If the file was open close it.
if (this->Internals->File)
{
this->Internals->File->close();
delete this->Internals->File;
this->Internals->File = NULL;
}
// Open the new file.
vtkDebugMacro(<< "vtkDelimitedTextReader is opening file: " << this->FileName);
this->Internals->File = new ifstream(this->FileName, ios::in);
// Check to see if open was successful
if (! this->Internals->File || this->Internals->File->fail())
{
vtkErrorMacro(<< "vtkDelimitedTextReader could not open file "
<< this->FileName);
return;
}
}
// ----------------------------------------------------------------------
int vtkDelimitedTextReader::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Check that the filename has been specified
if (!this->FileName)
{
vtkErrorMacro("vtkDelimitedTextReader: You must specify a filename!");
return 0;
}
// Open the file
this->OpenFile();
// Go to the top of the file
this->Internals->File->seekg(0,ios::beg);
// Store the text data into a vtkTable
vtkTable* table = vtkTable::GetData(outputVector);
// The first line of the file might contain the headers, so we want
// to be a little bit careful about it. If we don't have headers
// we'll have to make something up.
vtkstd::vector<vtkStdString> headers;
// Not all platforms support vtkstd::getline(istream&, vtkstd::string) so
// I have to do this the clunky way.
vtkstd::vector<vtkStdString> firstLineFields;
vtkStdString firstLine;
my_getline(*(this->Internals->File), firstLine);
vtkDebugMacro(<<"First line of file: " << firstLine.c_str());
if (this->HaveHeaders)
{
splitString(firstLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
headers);
}
else
{
splitString(firstLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
firstLineFields);
for (unsigned int i = 0; i < firstLineFields.size(); ++i)
{
// I know it's not a great idea to use sprintf. It's safe right
// here because an unsigned int will never take up enough
// characters to fill up this buffer.
char fieldName[64];
sprintf(fieldName, "Field %d", i);
headers.push_back(fieldName);
}
}
// Now we can create the arrays that will hold the data for each
// field.
vtkstd::vector<vtkStdString>::const_iterator fieldIter;
for(fieldIter = headers.begin(); fieldIter != headers.end(); ++fieldIter)
{
vtkStringArray* array = vtkStringArray::New();
array->SetName((*fieldIter).c_str());
table->AddColumn(array);
array->Delete();
}
// If the first line did not contain headers then we need to add it
// to the table.
if (!this->HaveHeaders)
{
vtkVariantArray* dataArray = vtkVariantArray::New();
vtkstd::vector<vtkStdString>::const_iterator I;
for(I = firstLineFields.begin(); I != firstLineFields.end(); ++I)
{
dataArray->InsertNextValue(vtkVariant(*I));
}
// Insert the data into the table
table->InsertNextRow(dataArray);
dataArray->Delete();
}
// Okay read the file and add the data to the table
vtkStdString nextLine;
while (my_getline(*(this->Internals->File), nextLine))
{
vtkDebugMacro(<<"Next line: " << nextLine.c_str());
vtkstd::vector<vtkStdString> dataVector;
// Split string on the delimiters
splitString(nextLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
dataVector);
vtkDebugMacro(<<"Split into " << dataVector.size() << " fields");
// Add data to the output arrays
// Convert from vector to variant array
vtkVariantArray* dataArray = vtkVariantArray::New();
vtkstd::vector<vtkStdString>::const_iterator I;
for(I = dataVector.begin(); I != dataVector.end(); ++I)
{
dataArray->InsertNextValue(vtkVariant(*I));
}
// Pad out any missing columns
while (dataArray->GetNumberOfTuples() < table->GetNumberOfColumns())
{
dataArray->InsertNextValue(vtkVariant());
}
// Insert the data into the table
table->InsertNextRow(dataArray);
dataArray->Delete();
}
return 1;
}
// ----------------------------------------------------------------------
static int
splitString(const vtkStdString& input,
char fieldDelimiter,
char stringDelimiter,
bool useStringDelimiter,
vtkstd::vector<vtkStdString>& results,
bool includeEmpties)
{
if (input.size() == 0)
{
return 0;
}
bool inString = false;
char thisCharacter = 0;
char lastCharacter = 0;
vtkstd::string currentField;
for (unsigned int i = 0; i < input.size(); ++i)
{
thisCharacter = input[i];
// Zeroth: are we in an escape sequence? If so, interpret this
// character accordingly.
if (lastCharacter == '\\')
{
char characterToAppend;
switch (thisCharacter)
{
case '0': characterToAppend = '\0'; break;
case 'a': characterToAppend = '\a'; break;
case 'b': characterToAppend = '\b'; break;
case 't': characterToAppend = '\t'; break;
case 'n': characterToAppend = '\n'; break;
case 'v': characterToAppend = '\v'; break;
case 'f': characterToAppend = '\f'; break;
case 'r': characterToAppend = '\r'; break;
case '\\': characterToAppend = '\\'; break;
default: characterToAppend = thisCharacter; break;
}
currentField += characterToAppend;
lastCharacter = thisCharacter;
if (lastCharacter == '\\') lastCharacter = 0;
}
else
{
// We're not in an escape sequence.
// First, are we /starting/ an escape sequence?
if (thisCharacter == '\\')
{
lastCharacter = thisCharacter;
continue;
}
else if (useStringDelimiter && thisCharacter == stringDelimiter)
{
// this should just toggle inString
inString = (inString == false);
}
else if (thisCharacter == fieldDelimiter && !inString)
{
// A delimiter starts a new field unless we're in a string, in
// which case it's normal text and we won't even get here.
if (includeEmpties || currentField.size() > 0)
{
results.push_back(currentField);
}
currentField = vtkStdString();
}
else
{
// The character is just plain text. Accumulate it and move on.
currentField += thisCharacter;
}
lastCharacter = thisCharacter;
}
}
results.push_back(currentField);
return results.size();
}
// ----------------------------------------------------------------------
static int
my_getline(istream& in, vtkStdString &out, char delimiter)
{
out = vtkStdString();
int numCharactersRead = 0;
int nextValue = 0;
while ((nextValue = in.get()) != EOF &&
numCharactersRead < out.max_size())
{
++numCharactersRead;
char downcast = static_cast<char>(nextValue);
if (downcast != delimiter)
{
out += downcast;
}
else
{
return numCharactersRead;
}
}
return numCharactersRead;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkDelimitedTextReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkDelimitedTextReader.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkInformation.h"
#include "vtkStringArray.h"
#include "vtkStdString.h"
#include <vtkstd/algorithm>
#include <vtkstd/vector>
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkDelimitedTextReader, "1.6");
vtkStandardNewMacro(vtkDelimitedTextReader);
struct vtkDelimitedTextReaderInternals
{
ifstream *File;
};
// Forward function reference (definition at bottom :)
static int splitString(const vtkStdString& input,
char fieldDelimiter,
char stringDelimiter,
bool useStringDelimiter,
vtkstd::vector<vtkStdString>& results,
bool includeEmpties=true);
// I need a safe way to read a line of arbitrary length. It exists on
// some platforms but not others so I'm afraid I have to write it
// myself.
static int my_getline(istream& stream, vtkStdString &output, char delim='\n');
// ----------------------------------------------------------------------
vtkDelimitedTextReader::vtkDelimitedTextReader()
{
this->Internals = new vtkDelimitedTextReaderInternals();
this->Internals->File = 0;
this->FileName = 0;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->ReadBuffer = new char[2048];
this->FieldDelimiter = ',';
this->StringDelimiter = '"';
this->UseStringDelimiter = true;
}
// ----------------------------------------------------------------------
vtkDelimitedTextReader::~vtkDelimitedTextReader()
{
this->SetFileName(0);
delete this->ReadBuffer;
delete this->Internals;
}
// ----------------------------------------------------------------------
void vtkDelimitedTextReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "FileName: "
<< (this->FileName ? this->FileName : "(none)") << endl;
os << indent << "Field delimiter: '" << this->FieldDelimiter
<< "'" << endl;
os << indent << "String delimiter: '" << this->StringDelimiter
<< "'" << endl;
os << indent << "UseStringDelimiter: "
<< (this->UseStringDelimiter ? "true" : "false") << endl;
os << indent << "HaveHeaders: "
<< (this->HaveHeaders ? "true" : "false") << endl;
}
// ----------------------------------------------------------------------
void vtkDelimitedTextReader::OpenFile()
{
// If the file was open close it.
if (this->Internals->File)
{
this->Internals->File->close();
delete this->Internals->File;
this->Internals->File = NULL;
}
// Open the new file.
vtkDebugMacro(<< "vtkDelimitedTextReader is opening file: " << this->FileName);
this->Internals->File = new ifstream(this->FileName, ios::in);
// Check to see if open was successful
if (! this->Internals->File || this->Internals->File->fail())
{
vtkErrorMacro(<< "vtkDelimitedTextReader could not open file "
<< this->FileName);
return;
}
}
// ----------------------------------------------------------------------
int vtkDelimitedTextReader::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Check that the filename has been specified
if (!this->FileName)
{
vtkErrorMacro("vtkDelimitedTextReader: You must specify a filename!");
return 0;
}
// Open the file
this->OpenFile();
// Go to the top of the file
this->Internals->File->seekg(0,ios::beg);
// Store the text data into a vtkTable
vtkTable* table = vtkTable::GetData(outputVector);
// The first line of the file might contain the headers, so we want
// to be a little bit careful about it. If we don't have headers
// we'll have to make something up.
vtkstd::vector<vtkStdString> headers;
// Not all platforms support vtkstd::getline(istream&, vtkstd::string) so
// I have to do this the clunky way.
vtkstd::vector<vtkStdString> firstLineFields;
vtkStdString firstLine;
my_getline(*(this->Internals->File), firstLine);
vtkDebugMacro(<<"First line of file: " << firstLine.c_str());
if (this->HaveHeaders)
{
splitString(firstLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
headers);
}
else
{
splitString(firstLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
firstLineFields);
for (unsigned int i = 0; i < firstLineFields.size(); ++i)
{
// I know it's not a great idea to use sprintf. It's safe right
// here because an unsigned int will never take up enough
// characters to fill up this buffer.
char fieldName[64];
sprintf(fieldName, "Field %d", i);
headers.push_back(fieldName);
}
}
// Now we can create the arrays that will hold the data for each
// field.
vtkstd::vector<vtkStdString>::const_iterator fieldIter;
for(fieldIter = headers.begin(); fieldIter != headers.end(); ++fieldIter)
{
vtkStringArray* array = vtkStringArray::New();
array->SetName((*fieldIter).c_str());
table->AddColumn(array);
array->Delete();
}
// If the first line did not contain headers then we need to add it
// to the table.
if (!this->HaveHeaders)
{
vtkVariantArray* dataArray = vtkVariantArray::New();
vtkstd::vector<vtkStdString>::const_iterator I;
for(I = firstLineFields.begin(); I != firstLineFields.end(); ++I)
{
dataArray->InsertNextValue(vtkVariant(*I));
}
// Insert the data into the table
table->InsertNextRow(dataArray);
dataArray->Delete();
}
// Okay read the file and add the data to the table
vtkStdString nextLine;
while (my_getline(*(this->Internals->File), nextLine))
{
vtkDebugMacro(<<"Next line: " << nextLine.c_str());
vtkstd::vector<vtkStdString> dataVector;
// Split string on the delimiters
splitString(nextLine,
this->FieldDelimiter,
this->StringDelimiter,
this->UseStringDelimiter,
dataVector);
vtkDebugMacro(<<"Split into " << dataVector.size() << " fields");
// Add data to the output arrays
// Convert from vector to variant array
vtkVariantArray* dataArray = vtkVariantArray::New();
vtkstd::vector<vtkStdString>::const_iterator I;
for(I = dataVector.begin(); I != dataVector.end(); ++I)
{
dataArray->InsertNextValue(vtkVariant(*I));
}
// Pad out any missing columns
while (dataArray->GetNumberOfTuples() < table->GetNumberOfColumns())
{
dataArray->InsertNextValue(vtkVariant());
}
// Insert the data into the table
table->InsertNextRow(dataArray);
dataArray->Delete();
}
return 1;
}
// ----------------------------------------------------------------------
static int
splitString(const vtkStdString& input,
char fieldDelimiter,
char stringDelimiter,
bool useStringDelimiter,
vtkstd::vector<vtkStdString>& results,
bool includeEmpties)
{
if (input.size() == 0)
{
return 0;
}
bool inString = false;
char thisCharacter = 0;
char lastCharacter = 0;
vtkstd::string currentField;
for (unsigned int i = 0; i < input.size(); ++i)
{
thisCharacter = input[i];
// Zeroth: are we in an escape sequence? If so, interpret this
// character accordingly.
if (lastCharacter == '\\')
{
char characterToAppend;
switch (thisCharacter)
{
case '0': characterToAppend = '\0'; break;
case 'a': characterToAppend = '\a'; break;
case 'b': characterToAppend = '\b'; break;
case 't': characterToAppend = '\t'; break;
case 'n': characterToAppend = '\n'; break;
case 'v': characterToAppend = '\v'; break;
case 'f': characterToAppend = '\f'; break;
case 'r': characterToAppend = '\r'; break;
case '\\': characterToAppend = '\\'; break;
default: characterToAppend = thisCharacter; break;
}
currentField += characterToAppend;
lastCharacter = thisCharacter;
if (lastCharacter == '\\') lastCharacter = 0;
}
else
{
// We're not in an escape sequence.
// First, are we /starting/ an escape sequence?
if (thisCharacter == '\\')
{
lastCharacter = thisCharacter;
continue;
}
else if (useStringDelimiter && thisCharacter == stringDelimiter)
{
// this should just toggle inString
inString = (inString == false);
}
else if (thisCharacter == fieldDelimiter && !inString)
{
// A delimiter starts a new field unless we're in a string, in
// which case it's normal text and we won't even get here.
if (includeEmpties || currentField.size() > 0)
{
results.push_back(currentField);
}
currentField = vtkStdString();
}
else
{
// The character is just plain text. Accumulate it and move on.
currentField += thisCharacter;
}
lastCharacter = thisCharacter;
}
}
results.push_back(currentField);
return results.size();
}
// ----------------------------------------------------------------------
static int
my_getline(istream& in, vtkStdString &out, char delimiter)
{
out = vtkStdString();
unsigned int numCharactersRead = 0;
int nextValue = 0;
while ((nextValue = in.get()) != EOF &&
numCharactersRead < out.max_size())
{
++numCharactersRead;
char downcast = static_cast<char>(nextValue);
if (downcast != delimiter)
{
out += downcast;
}
else
{
return numCharactersRead;
}
}
return numCharactersRead;
}
|
Fix a signed/unsigned comparison warning
|
COMP: Fix a signed/unsigned comparison warning
|
C++
|
bsd-3-clause
|
demarle/VTK,collects/VTK,arnaudgelas/VTK,candy7393/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,sankhesh/VTK,gram526/VTK,keithroe/vtkoptix,candy7393/VTK,daviddoria/PointGraphsPhase1,spthaolt/VTK,Wuteyan/VTK,demarle/VTK,msmolens/VTK,arnaudgelas/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,collects/VTK,collects/VTK,SimVascular/VTK,jmerkow/VTK,johnkit/vtk-dev,demarle/VTK,demarle/VTK,arnaudgelas/VTK,spthaolt/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,sankhesh/VTK,johnkit/vtk-dev,msmolens/VTK,biddisco/VTK,cjh1/VTK,ashray/VTK-EVM,SimVascular/VTK,aashish24/VTK-old,daviddoria/PointGraphsPhase1,collects/VTK,naucoin/VTKSlicerWidgets,hendradarwin/VTK,mspark93/VTK,biddisco/VTK,aashish24/VTK-old,keithroe/vtkoptix,keithroe/vtkoptix,mspark93/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,jmerkow/VTK,johnkit/vtk-dev,sumedhasingla/VTK,johnkit/vtk-dev,mspark93/VTK,SimVascular/VTK,spthaolt/VTK,msmolens/VTK,demarle/VTK,SimVascular/VTK,jmerkow/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,jeffbaumes/jeffbaumes-vtk,gram526/VTK,keithroe/vtkoptix,cjh1/VTK,demarle/VTK,hendradarwin/VTK,mspark93/VTK,SimVascular/VTK,hendradarwin/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,ashray/VTK-EVM,collects/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,gram526/VTK,sankhesh/VTK,mspark93/VTK,arnaudgelas/VTK,arnaudgelas/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,ashray/VTK-EVM,gram526/VTK,biddisco/VTK,Wuteyan/VTK,keithroe/vtkoptix,naucoin/VTKSlicerWidgets,aashish24/VTK-old,daviddoria/PointGraphsPhase1,naucoin/VTKSlicerWidgets,candy7393/VTK,sumedhasingla/VTK,sumedhasingla/VTK,Wuteyan/VTK,sankhesh/VTK,arnaudgelas/VTK,ashray/VTK-EVM,ashray/VTK-EVM,spthaolt/VTK,msmolens/VTK,SimVascular/VTK,hendradarwin/VTK,aashish24/VTK-old,mspark93/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,gram526/VTK,hendradarwin/VTK,cjh1/VTK,demarle/VTK,johnkit/vtk-dev,johnkit/vtk-dev,sumedhasingla/VTK,jmerkow/VTK,mspark93/VTK,ashray/VTK-EVM,keithroe/vtkoptix,aashish24/VTK-old,daviddoria/PointGraphsPhase1,cjh1/VTK,candy7393/VTK,sankhesh/VTK,sankhesh/VTK,candy7393/VTK,spthaolt/VTK,sankhesh/VTK,sumedhasingla/VTK,keithroe/vtkoptix,candy7393/VTK,msmolens/VTK,msmolens/VTK,candy7393/VTK,Wuteyan/VTK,spthaolt/VTK,msmolens/VTK,biddisco/VTK,candy7393/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,hendradarwin/VTK,Wuteyan/VTK,gram526/VTK,sumedhasingla/VTK,collects/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,sumedhasingla/VTK,SimVascular/VTK,gram526/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,Wuteyan/VTK,cjh1/VTK,naucoin/VTKSlicerWidgets,gram526/VTK,keithroe/vtkoptix,hendradarwin/VTK,biddisco/VTK,cjh1/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,sankhesh/VTK,spthaolt/VTK,berendkleinhaneveld/VTK
|
24204204b4db57754c3fcb6b054f955df77ba685
|
InterThresholdCalibration/main.cpp
|
InterThresholdCalibration/main.cpp
|
/**
* @copyright Copyright 2017 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 main.cpp
*/
#include <JPetManager/JPetManager.h>
#include "../LargeBarrelAnalysis/TimeWindowCreator.h"
#include "../LargeBarrelAnalysis/SignalFinder.h"
#include "../LargeBarrelAnalysis/SignalTransformer.h"
#include "../LargeBarrelAnalysis/HitFinder.h"
#include "InterThresholdCalibration.h"
using namespace std;
int main(int argc, const char* argv[])
{
try {
JPetManager& manager = JPetManager::getManager();
manager.registerTask<TimeWindowCreator>("TimeWindowCreator");
manager.registerTask<SignalFinder>("SignalFinder");
manager.registerTask<SignalTransformer>("SignalTransformer");
manager.registerTask<HitFinder>("HitFinder");
manager.registerTask<InterThresholdCalibration>("InterThresholdCalibration");
manager.useTask("TimeWindowCreator", "hld", "tslot.calib");
manager.useTask("SignalFinder", "tslot.calib", "raw.sig");
manager.useTask("SignalTransformer", "raw.sig", "phys.sig");
manager.useTask("HitFinder", "phys.sig", "hits");
manager.useTask("InterThresholdCalibration", "hits", "calib");
manager.run(argc, argv);
} catch (const std::exception& except) {
std::cerr << "Unrecoverable error occured:" << except.what() << "Exiting the program!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
/**
* @copyright Copyright 2017 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 main.cpp
*/
#include <JPetManager/JPetManager.h>
#include "../LargeBarrelAnalysis/TimeWindowCreator.h"
#include "../LargeBarrelAnalysis/SignalFinder.h"
#include "../LargeBarrelAnalysis/SignalTransformer.h"
#include "../LargeBarrelAnalysis/HitFinder.h"
#include "InterThresholdCalibration.h"
using namespace std;
int main(int argc, const char* argv[])
{
try {
JPetManager& manager = JPetManager::getManager();
manager.registerTask<TimeWindowCreator>("TimeWindowCreator");
manager.registerTask<SignalFinder>("SignalFinder");
manager.registerTask<SignalTransformer>("SignalTransformer");
manager.registerTask<HitFinder>("HitFinder");
manager.registerTask<InterThresholdCalibration>("InterThresholdCalibration");
manager.useTask("TimeWindowCreator", "hld", "tslot.calib");
manager.useTask("SignalFinder", "tslot.calib", "raw.sig");
manager.useTask("SignalTransformer", "raw.sig", "phys.sig");
manager.useTask("HitFinder", "phys.sig", "hits");
manager.useTask("InterThresholdCalibration", "hits", "hits.calib");
manager.run(argc, argv);
} catch (const std::exception& except) {
std::cerr << "Unrecoverable error occured:" << except.what() << "Exiting the program!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Change output file extension to be more informative
|
Change output file extension to be more informative
|
C++
|
apache-2.0
|
JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples,JPETTomography/j-pet-framework-examples
|
c3f256c5e7520eb0e0193496c7c2f51ff8a97f49
|
tests/test_constructor_binding.cpp
|
tests/test_constructor_binding.cpp
|
#include "catch.hpp"
#include <reflection_binding.hpp>
struct test_construct1
{
test_construct1(int in, float fn) : i(2 * in), f(fn)
{
}
int i;
float f;
};
struct test_construct2
{
char c;
double d;
};
TEST_CASE("test constructor binding", "[generic_constructor_bind_point]")
{
auto int_construct_from_int =
&shadow::constructor_detail::generic_constructor_bind_point<int, int>;
auto int_construct_from_float =
&shadow::constructor_detail::generic_constructor_bind_point<int, float>;
auto test_construct1_constructor =
&shadow::constructor_detail::
generic_constructor_bind_point<test_construct1, int, float>;
auto test_construct2_constructor =
&shadow::constructor_detail::
generic_constructor_bind_point<test_construct2, char, double>;
SECTION("construct int with int")
{
shadow::any intarg = 11;
auto result = int_construct_from_int(&intarg);
REQUIRE(result.get<int>() == 11);
}
SECTION("construct int with float")
{
shadow::any floatarg = 23.5f;
auto result = int_construct_from_float(&floatarg);
REQUIRE(result.get<int>() == 23);
}
SECTION("when constructing a test_construct1 with int, float args, the "
"constructor should be chosen")
{
shadow::any args[] = {10, 23.4f};
auto result = test_construct1_constructor(args);
REQUIRE(result.get<test_construct1>().i == 20);
REQUIRE(result.get<test_construct1>().f == 23.4f);
}
SECTION("when constructing a test_construct2, braced-init-list "
"construction should be chosen")
{
shadow::any args[] = {'a', 25.3};
auto result = test_construct2_constructor(args);
REQUIRE(result.get<test_construct2>().c == 'a');
REQUIRE(result.get<test_construct2>().d == 25.3);
}
}
|
#include "catch.hpp"
#include <reflection_binding.hpp>
struct test_construct1
{
test_construct1(int in, float fn) : i(2 * in), f(fn)
{
}
int i;
float f;
};
struct test_construct2
{
char c;
double d;
};
TEST_CASE("test constructor binding", "[generic_constructor_bind_point]")
{
auto int_construct_from_int =
&shadow::constructor_detail::generic_constructor_bind_point<int, int>;
auto int_construct_from_float =
&shadow::constructor_detail::generic_constructor_bind_point<int, float>;
auto test_construct1_constructor =
&shadow::constructor_detail::
generic_constructor_bind_point<test_construct1, int, float>;
auto test_construct2_constructor =
&shadow::constructor_detail::
generic_constructor_bind_point<test_construct2, char, double>;
auto int_default_constructor =
&shadow::constructor_detail::generic_constructor_bind_point<int>;
SECTION("construct int with int")
{
shadow::any intarg = 11;
auto result = int_construct_from_int(&intarg);
REQUIRE(result.get<int>() == 11);
}
SECTION("construct int with float")
{
shadow::any floatarg = 23.5f;
auto result = int_construct_from_float(&floatarg);
REQUIRE(result.get<int>() == 23);
}
SECTION("when constructing a test_construct1 with int, float args, the "
"constructor should be chosen")
{
shadow::any args[] = {10, 23.4f};
auto result = test_construct1_constructor(args);
REQUIRE(result.get<test_construct1>().i == 20);
REQUIRE(result.get<test_construct1>().f == 23.4f);
}
SECTION("when constructing a test_construct2, braced-init-list "
"construction should be chosen")
{
shadow::any args[] = {'a', 25.3};
auto result = test_construct2_constructor(args);
REQUIRE(result.get<test_construct2>().c == 'a');
REQUIRE(result.get<test_construct2>().d == 25.3);
}
SECTION(
"when using default constructor of int, the int in the any should be 0")
{
auto result = int_default_constructor(nullptr);
REQUIRE(result.get<int>() == 0);
}
}
|
Add unit test for default constructor of int. modified: tests/test_constructor_binding.cpp
|
Add unit test for default constructor of int.
modified: tests/test_constructor_binding.cpp
|
C++
|
mit
|
bergesenha/shadow
|
00c6e7f7c09009af9152d29e3d3031f453f18e23
|
Evaluator/Source/BallDetectorEvaluator.cpp
|
Evaluator/Source/BallDetectorEvaluator.cpp
|
#include "BallDetectorEvaluator.h"
#include <glib.h>
#include <glib/gstdio.h>
#include <strstream>
#include <fstream>
#include <sstream>
#include <Representations/Perception/BallCandidates.h>
#include <Extern/libb64/encode.h>
#include <Tools/naoth_opencv.h>
#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) // version >= 4.6
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wconversion"
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) // version >= 4.9
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#endif
#include <opencv2/imgcodecs/imgcodecs.hpp>
#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) // version >= 4.6
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic error "-Wconversion"
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) // version >= 4.9
#pragma GCC diagnostic error "-Wfloat-conversion"
#endif
#endif
BallDetectorEvaluator::BallDetectorEvaluator(const std::string &fileArg)
: fileArg(fileArg), minNeighbours(0),
truePositives(0), falsePositives(0), falseNegatives(0)
{
}
BallDetectorEvaluator::~BallDetectorEvaluator()
{
}
void BallDetectorEvaluator::execute()
{
std::string outFileName = "HaarBallDetector_Evaluation.html";
std::ofstream html;
html.open(outFileName);
html << "<html>" << std::endl;
html << "<head>" << std::endl;
html << "<style>" << std::endl;
// CSS
html << "img.patch {width: 36px; height: 36px}" << std::endl;
html << "</style>" << std::endl;
html << "</head>" << std::endl;
html << "<body>" << std::endl;
// do experiment for different parameters
for(minNeighbours=0; minNeighbours < 6; minNeighbours++)
{
truePositives = falseNegatives = falsePositives = 0;
falsePositivePatches.clear();
falseNegativePatches.clear();
unsigned int totalSize = 0;
if(g_file_test(fileArg.c_str(), G_FILE_TEST_IS_DIR))
{
std::string dirlocation = fileArg;
if (!g_str_has_suffix(dirlocation.c_str(), "/"))
{
dirlocation = dirlocation + "/";
}
GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);
if (dir != NULL)
{
const gchar* name;
while ((name = g_dir_read_name(dir)) != NULL)
{
if (g_str_has_suffix(name, ".log"))
{
std::string completeFileName = dirlocation + name;
if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)
&& g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))
{
totalSize += executeSingleFile(completeFileName);
}
}
}
g_dir_close(dir);
}
}
else
{
// only one file
totalSize = executeSingleFile(fileArg);
}
double precision = 1.0;
if(truePositives + falsePositives > 0)
{
precision = (double) truePositives / ((double) (truePositives + falsePositives));
}
double recall = 1.0;
if(truePositives + falsePositives > 0)
{
recall = (double) truePositives / ((double) (truePositives + falseNegatives));
}
std::cout << "=============" << std::endl;
std::cout << "minNeighbours=" << minNeighbours << std::endl;
std::cout << "precision: " << precision << std::endl;
std::cout << "recall: " << recall << std::endl;
std::cout << "=============" << std::endl;
std::cout << "Written detailed report to " << outFileName << std::endl;
base64::Encoder base64Encoder(64);
html << "<h1>minNeighbours=" << minNeighbours << "</h1>" << std::endl;
html << "<h2>Summary</h2>" << std::endl;
html << "<p><strong>precision: " << precision << "<br />recall: " << recall << "</strong></p>" << std::endl;
unsigned int numOfBalls = truePositives + falseNegatives;
html << "<p>total number of samples: " << totalSize << " (" << numOfBalls << " balls, " << (totalSize - numOfBalls) << " non-balls)</p>" << std::endl;
html << "<h2>False Positives</h2>" << std::endl;
html << "<p>number: " << falsePositives << "</p>" << std::endl;
html << "<div>" << std::endl;
for(std::list<ErrorEntry>::const_iterator it=falsePositivePatches.begin(); it != falsePositivePatches.end(); it++)
{
// use a data URI to embed the image in PNG format
std::string imgPNG = createPNG(it->patch);
html << "<img class=\"patch\" title=\"" << it->idx << "@" << it->fileName
<< "\" src=\"data:image/png;base64," << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size()) << "\" />" << std::endl;
}
html << "</div>" << std::endl;
html << "<h1>False Negatives</h1>" << std::endl;
html << "<p>number: " << falseNegatives << "</p>" << std::endl;
html << "<div>" << std::endl;
for(std::list<ErrorEntry>::const_iterator it=falseNegativePatches.begin(); it != falseNegativePatches.end(); it++)
{
// use a data URI to embed the image in PNG format
std::string imgPNG = createPNG(it->patch);
html << "<img class=\"patch\" title=\"" << it->idx << "@" << it->fileName
<< "\" src=\"data:image/png;base64," << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size()) << "\" />" << std::endl;
}
html << "</div>" << std::endl;
}
html << "</body>" << std::endl;
html.close();
}
unsigned int BallDetectorEvaluator::executeSingleFile(std::string file)
{
LogFileScanner logFileScanner(file);
std::set<unsigned int> expectedBallIdx;
unsigned int maxValidIdx = loadGroundTruth(file, expectedBallIdx);
unsigned int patchIdx = 0;
// read in each frame
LogFileScanner::FrameIterator secondLastFrame = logFileScanner.end();
secondLastFrame--;
for(LogFileScanner::FrameIterator it = logFileScanner.begin(); it != secondLastFrame; it++)
{
// reset all existing candidates
getBallCandidates().reset();
getBallCandidatesTop().reset();
LogFileScanner::Frame frame;
logFileScanner.readFrame(*it, frame);
// deserialize all ball candidates (bottom and top camera)
LogFileScanner::Frame::const_iterator frameBallCandidate = frame.find("BallCandidates");
LogFileScanner::Frame::const_iterator frameBallCandidateTop = frame.find("BallCandidatesTop");
if(frameBallCandidate!= frame.end())
{
std::istrstream stream(frameBallCandidate->second.data.data(), frameBallCandidate->second.data.size());
naoth::Serializer<BallCandidates>::deserialize(stream, getBallCandidates());
}
if(frameBallCandidateTop != frame.end())
{
std::istrstream stream(frameBallCandidateTop->second.data.data(), frameBallCandidateTop->second.data.size());
naoth::Serializer<BallCandidatesTop>::deserialize(stream, getBallCandidatesTop());
}
// The python script will always read the bottom patches first, thus in order to have the correct index
// the loops have to bee in the same order.
for(const BallCandidates::Patch& p : getBallCandidates().patches)
{
evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file);
}
for(const BallCandidates::Patch& p : getBallCandidatesTop().patches)
{
evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file);
}
if(patchIdx >= maxValidIdx)
{
break;
}
}
return patchIdx;
}
void BallDetectorEvaluator::evaluatePatch(const BallCandidates::Patch &p, unsigned int patchIdx,
CameraInfo::CameraID camID,
const std::set<unsigned int>& expectedBallIdx,
std::string fileName)
{
bool expected = expectedBallIdx.find(patchIdx) != expectedBallIdx.end();
bool actual = classifier.classify(p, minNeighbours) > 0;
if(expected == actual)
{
if(expected)
{
truePositives++;
}
}
else
{
ErrorEntry error;
error.patch= p;
error.idx = patchIdx;
error.fileName = fileName;
if(actual)
{
falsePositivePatches.push_back(error);
falsePositives++;
}
else
{
falseNegativePatches.push_back(error);
falseNegatives++;
}
}
}
int BallDetectorEvaluator::loadGroundTruth(std::string file, std::set<unsigned int>& expectedBallIdx)
{
typedef std::vector<picojson::value> array;
typedef std::map<std::string, picojson::value> object;
int maxValidIdx = 0;
size_t dotPos = file.find_last_of('.');
std::string jsonFile = dotPos == std::string::npos ? file : file.substr(0, dotPos) + ".json";
std::cout << "loading ground truth from '" << jsonFile << "'" << std::endl;
std::ifstream groundTruthStream(jsonFile);
picojson::value parsedJson;
picojson::parse(parsedJson, groundTruthStream);
groundTruthStream.close();
array ballIdx;
array noBallIdx;
if(parsedJson.is<object>())
{
if(parsedJson.get("ball").is<array>())
{
ballIdx = parsedJson.get("ball").get<array>();
}
if(parsedJson.get("noball").is<array>())
{
noBallIdx = parsedJson.get("noball").get<array>();
}
for(picojson::value idx : ballIdx)
{
if(idx.is<double>())
{
int idxVal = static_cast<int>(idx.get<double>());
expectedBallIdx.insert(idxVal);
maxValidIdx = std::max(maxValidIdx, idxVal);
}
}
for(picojson::value idx : noBallIdx)
{
if(idx.is<double>())
{
int idxVal = static_cast<int>(idx.get<double>());
maxValidIdx = std::max(maxValidIdx, idxVal);
}
}
}
return maxValidIdx;
}
std::string BallDetectorEvaluator::createPGM(const BallCandidates::Patch &p)
{
std::stringstream str;
// header (we are gray scale, thus P2)
str << "P2\n";
// the width and the height of the image
str << BallCandidates::Patch::SIZE << "\n" << BallCandidates::Patch::SIZE << "\n";
// the maximum value we use
str << "255\n";
// output each pixel
for(unsigned int y=0; y < BallCandidates::Patch::SIZE; y++)
{
for(unsigned int x=0; x < BallCandidates::Patch::SIZE; x++)
{
str << (int) p.data[x*BallCandidates::Patch::SIZE + y];
if(x < BallCandidates::Patch::SIZE - 1)
{
str << " ";
}
}
str << "\n";
}
return str.str();
}
std::string BallDetectorEvaluator::createPNG(const BallCandidates::Patch &p)
{
cv::Mat wrappedImg(12, 12, CV_8UC1, (void*) p.data.data());
std::vector<uchar> buffer;
cv::imencode(".png", wrappedImg, buffer);
return std::string(buffer.begin(), buffer.end());
}
|
#include "BallDetectorEvaluator.h"
#include <glib.h>
#include <glib/gstdio.h>
#include <strstream>
#include <fstream>
#include <sstream>
#include <Representations/Perception/BallCandidates.h>
#include <Extern/libb64/encode.h>
#include <Tools/naoth_opencv.h>
#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) // version >= 4.6
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Wconversion"
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) // version >= 4.9
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#endif
#include <opencv2/imgcodecs/imgcodecs.hpp>
#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) // version >= 4.6
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic error "-Wconversion"
#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) // version >= 4.9
#pragma GCC diagnostic error "-Wfloat-conversion"
#endif
#endif
BallDetectorEvaluator::BallDetectorEvaluator(const std::string &fileArg)
: fileArg(fileArg), minNeighbours(0),
truePositives(0), falsePositives(0), falseNegatives(0)
{
}
BallDetectorEvaluator::~BallDetectorEvaluator()
{
}
void BallDetectorEvaluator::execute()
{
std::string outFileName = "HaarBallDetector_Evaluation.html";
std::ofstream html;
html.open(outFileName);
html << "<html>" << std::endl;
html << "<head>" << std::endl;
html << "<style>" << std::endl;
// CSS
html << "img.patch {width: 36px; height: 36px}" << std::endl;
html << "</style>" << std::endl;
html << "</head>" << std::endl;
html << "<body>" << std::endl;
html << "<h1><a id=\"overview\">Overview</a></h1>" << std::endl;
// do experiment for different parameters
for(minNeighbours=0; minNeighbours < 6; minNeighbours++)
{
truePositives = falseNegatives = falsePositives = 0;
falsePositivePatches.clear();
falseNegativePatches.clear();
unsigned int totalSize = 0;
if(g_file_test(fileArg.c_str(), G_FILE_TEST_IS_DIR))
{
std::string dirlocation = fileArg;
if (!g_str_has_suffix(dirlocation.c_str(), "/"))
{
dirlocation = dirlocation + "/";
}
GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);
if (dir != NULL)
{
const gchar* name;
while ((name = g_dir_read_name(dir)) != NULL)
{
if (g_str_has_suffix(name, ".log"))
{
std::string completeFileName = dirlocation + name;
if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)
&& g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))
{
totalSize += executeSingleFile(completeFileName);
}
}
}
g_dir_close(dir);
}
}
else
{
// only one file
totalSize = executeSingleFile(fileArg);
}
double precision = 1.0;
if(truePositives + falsePositives > 0)
{
precision = (double) truePositives / ((double) (truePositives + falsePositives));
}
double recall = 1.0;
if(truePositives + falsePositives > 0)
{
recall = (double) truePositives / ((double) (truePositives + falseNegatives));
}
std::cout << "=============" << std::endl;
std::cout << "minNeighbours=" << minNeighbours << std::endl;
std::cout << "precision: " << precision << std::endl;
std::cout << "recall: " << recall << std::endl;
std::cout << "=============" << std::endl;
std::cout << "Written detailed report to " << outFileName << std::endl;
base64::Encoder base64Encoder(64);
html << "<h1>minNeighbours=" << minNeighbours << "</h1>" << std::endl;
html << "<h2>Summary</h2>" << std::endl;
html << "<p><strong>precision: " << precision << "<br />recall: " << recall << "</strong></p>" << std::endl;
unsigned int numOfBalls = truePositives + falseNegatives;
html << "<p>total number of samples: " << totalSize << " (" << numOfBalls << " balls, " << (totalSize - numOfBalls) << " non-balls)</p>" << std::endl;
html << "<p><a href=\"#overview\">back to top</a></p>" << std::endl;
html << "<h2>False Positives</h2>" << std::endl;
html << "<p>number: " << falsePositives << "</p>" << std::endl;
html << "<div>" << std::endl;
for(std::list<ErrorEntry>::const_iterator it=falsePositivePatches.begin(); it != falsePositivePatches.end(); it++)
{
// use a data URI to embed the image in PNG format
std::string imgPNG = createPNG(it->patch);
html << "<img class=\"patch\" title=\"" << it->idx << "@" << it->fileName
<< "\" src=\"data:image/png;base64," << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size()) << "\" />" << std::endl;
}
html << "</div>" << std::endl;
html << "<h1>False Negatives</h1>" << std::endl;
html << "<p>number: " << falseNegatives << "</p>" << std::endl;
html << "<div>" << std::endl;
for(std::list<ErrorEntry>::const_iterator it=falseNegativePatches.begin(); it != falseNegativePatches.end(); it++)
{
// use a data URI to embed the image in PNG format
std::string imgPNG = createPNG(it->patch);
html << "<img class=\"patch\" title=\"" << it->idx << "@" << it->fileName
<< "\" src=\"data:image/png;base64," << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size()) << "\" />" << std::endl;
}
html << "</div>" << std::endl;
}
html << "</body>" << std::endl;
html.close();
}
unsigned int BallDetectorEvaluator::executeSingleFile(std::string file)
{
LogFileScanner logFileScanner(file);
std::set<unsigned int> expectedBallIdx;
unsigned int maxValidIdx = loadGroundTruth(file, expectedBallIdx);
unsigned int patchIdx = 0;
// read in each frame
LogFileScanner::FrameIterator secondLastFrame = logFileScanner.end();
secondLastFrame--;
for(LogFileScanner::FrameIterator it = logFileScanner.begin(); it != secondLastFrame; it++)
{
// reset all existing candidates
getBallCandidates().reset();
getBallCandidatesTop().reset();
LogFileScanner::Frame frame;
logFileScanner.readFrame(*it, frame);
// deserialize all ball candidates (bottom and top camera)
LogFileScanner::Frame::const_iterator frameBallCandidate = frame.find("BallCandidates");
LogFileScanner::Frame::const_iterator frameBallCandidateTop = frame.find("BallCandidatesTop");
if(frameBallCandidate!= frame.end())
{
std::istrstream stream(frameBallCandidate->second.data.data(), frameBallCandidate->second.data.size());
naoth::Serializer<BallCandidates>::deserialize(stream, getBallCandidates());
}
if(frameBallCandidateTop != frame.end())
{
std::istrstream stream(frameBallCandidateTop->second.data.data(), frameBallCandidateTop->second.data.size());
naoth::Serializer<BallCandidatesTop>::deserialize(stream, getBallCandidatesTop());
}
// The python script will always read the bottom patches first, thus in order to have the correct index
// the loops have to bee in the same order.
for(const BallCandidates::Patch& p : getBallCandidates().patches)
{
evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file);
}
for(const BallCandidates::Patch& p : getBallCandidatesTop().patches)
{
evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file);
}
if(patchIdx >= maxValidIdx)
{
break;
}
}
return patchIdx;
}
void BallDetectorEvaluator::evaluatePatch(const BallCandidates::Patch &p, unsigned int patchIdx,
CameraInfo::CameraID camID,
const std::set<unsigned int>& expectedBallIdx,
std::string fileName)
{
bool expected = expectedBallIdx.find(patchIdx) != expectedBallIdx.end();
bool actual = classifier.classify(p, minNeighbours) > 0;
if(expected == actual)
{
if(expected)
{
truePositives++;
}
}
else
{
ErrorEntry error;
error.patch= p;
error.idx = patchIdx;
error.fileName = fileName;
if(actual)
{
falsePositivePatches.push_back(error);
falsePositives++;
}
else
{
falseNegativePatches.push_back(error);
falseNegatives++;
}
}
}
int BallDetectorEvaluator::loadGroundTruth(std::string file, std::set<unsigned int>& expectedBallIdx)
{
typedef std::vector<picojson::value> array;
typedef std::map<std::string, picojson::value> object;
int maxValidIdx = 0;
size_t dotPos = file.find_last_of('.');
std::string jsonFile = dotPos == std::string::npos ? file : file.substr(0, dotPos) + ".json";
std::cout << "loading ground truth from '" << jsonFile << "'" << std::endl;
std::ifstream groundTruthStream(jsonFile);
picojson::value parsedJson;
picojson::parse(parsedJson, groundTruthStream);
groundTruthStream.close();
array ballIdx;
array noBallIdx;
if(parsedJson.is<object>())
{
if(parsedJson.get("ball").is<array>())
{
ballIdx = parsedJson.get("ball").get<array>();
}
if(parsedJson.get("noball").is<array>())
{
noBallIdx = parsedJson.get("noball").get<array>();
}
for(picojson::value idx : ballIdx)
{
if(idx.is<double>())
{
int idxVal = static_cast<int>(idx.get<double>());
expectedBallIdx.insert(idxVal);
maxValidIdx = std::max(maxValidIdx, idxVal);
}
}
for(picojson::value idx : noBallIdx)
{
if(idx.is<double>())
{
int idxVal = static_cast<int>(idx.get<double>());
maxValidIdx = std::max(maxValidIdx, idxVal);
}
}
}
return maxValidIdx;
}
std::string BallDetectorEvaluator::createPGM(const BallCandidates::Patch &p)
{
std::stringstream str;
// header (we are gray scale, thus P2)
str << "P2\n";
// the width and the height of the image
str << BallCandidates::Patch::SIZE << "\n" << BallCandidates::Patch::SIZE << "\n";
// the maximum value we use
str << "255\n";
// output each pixel
for(unsigned int y=0; y < BallCandidates::Patch::SIZE; y++)
{
for(unsigned int x=0; x < BallCandidates::Patch::SIZE; x++)
{
str << (int) p.data[x*BallCandidates::Patch::SIZE + y];
if(x < BallCandidates::Patch::SIZE - 1)
{
str << " ";
}
}
str << "\n";
}
return str.str();
}
std::string BallDetectorEvaluator::createPNG(const BallCandidates::Patch &p)
{
cv::Mat wrappedImg(12, 12, CV_8UC1, (void*) p.data.data());
std::vector<uchar> buffer;
cv::imencode(".png", wrappedImg, buffer);
return std::string(buffer.begin(), buffer.end());
}
|
Allow navigation to top.
|
Allow navigation to top.
|
C++
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
3d616e65378ff3f430a7e5907480d8ccea05120e
|
unittests/clangd/HeadersTests.cpp
|
unittests/clangd/HeadersTests.cpp
|
//===-- HeadersTests.cpp - Include headers unit tests -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Headers.h"
#include "Compiler.h"
#include "TestFS.h"
#include "TestTU.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace clang {
namespace clangd {
namespace {
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::UnorderedElementsAre;
class HeadersTest : public ::testing::Test {
public:
HeadersTest() {
CDB.ExtraClangFlags = {SearchDirArg.c_str()};
FS.Files[MainFile] = "";
// Make sure directory sub/ exists.
FS.Files[testPath("sub/EMPTY")] = "";
}
private:
std::unique_ptr<CompilerInstance> setupClang() {
auto Cmd = CDB.getCompileCommand(MainFile);
assert(static_cast<bool>(Cmd));
auto VFS = FS.getFileSystem();
VFS->setCurrentWorkingDirectory(Cmd->Directory);
std::vector<const char *> Argv;
for (const auto &S : Cmd->CommandLine)
Argv.push_back(S.c_str());
auto CI = clang::createInvocationFromCommandLine(
Argv,
CompilerInstance::createDiagnostics(new DiagnosticOptions(),
&IgnoreDiags, false),
VFS);
EXPECT_TRUE(static_cast<bool>(CI));
CI->getFrontendOpts().DisableFree = false;
// The diagnostic options must be set before creating a CompilerInstance.
CI->getDiagnosticOpts().IgnoreWarnings = true;
auto Clang = prepareCompilerInstance(
std::move(CI), /*Preamble=*/nullptr,
MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
std::make_shared<PCHContainerOperations>(), VFS, IgnoreDiags);
EXPECT_FALSE(Clang->getFrontendOpts().Inputs.empty());
return Clang;
}
protected:
IncludeStructure collectIncludes() {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
IncludeStructure Includes;
Clang->getPreprocessor().addPPCallbacks(
collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
EXPECT_TRUE(Action.Execute());
Action.EndSourceFile();
return Includes;
}
// Calculates the include path, or returns "" on error or header should not be
// inserted.
std::string calculate(PathRef Original, PathRef Preferred = "",
const std::vector<Inclusion> &Inclusions = {}) {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
if (Preferred.empty())
Preferred = Original;
auto ToHeaderFile = [](StringRef Header) {
return HeaderFile{Header,
/*Verbatim=*/!sys::path::is_absolute(Header)};
};
IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
CDB.getCompileCommand(MainFile)->Directory,
Clang->getPreprocessor().getHeaderSearchInfo());
for (const auto &Inc : Inclusions)
Inserter.addExisting(Inc);
auto Declaring = ToHeaderFile(Original);
auto Inserted = ToHeaderFile(Preferred);
if (!Inserter.shouldInsertInclude(Declaring, Inserted))
return "";
std::string Path = Inserter.calculateIncludePath(Declaring, Inserted);
Action.EndSourceFile();
return Path;
}
Optional<TextEdit> insert(StringRef VerbatimHeader) {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
CDB.getCompileCommand(MainFile)->Directory,
Clang->getPreprocessor().getHeaderSearchInfo());
auto Edit = Inserter.insert(VerbatimHeader);
Action.EndSourceFile();
return Edit;
}
MockFSProvider FS;
MockCompilationDatabase CDB;
std::string MainFile = testPath("main.cpp");
std::string Subdir = testPath("sub");
std::string SearchDirArg = (Twine("-I") + Subdir).str();
IgnoringDiagConsumer IgnoreDiags;
};
MATCHER_P(Written, Name, "") { return arg.Written == Name; }
MATCHER_P(Resolved, Name, "") { return arg.Resolved == Name; }
MATCHER_P(IncludeLine, N, "") { return arg.R.start.line == N; }
MATCHER_P2(Distance, File, D, "") {
if (arg.getKey() != File)
*result_listener << "file =" << arg.getKey().str();
if (arg.getValue() != D)
*result_listener << "distance =" << arg.getValue();
return arg.getKey() == File && arg.getValue() == D;
}
TEST_F(HeadersTest, CollectRewrittenAndResolved) {
FS.Files[MainFile] = R"cpp(
#include "sub/bar.h" // not shortest
)cpp";
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = "";
EXPECT_THAT(collectIncludes().MainFileIncludes,
UnorderedElementsAre(
AllOf(Written("\"sub/bar.h\""), Resolved(BarHeader))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u),
Distance(testPath("sub/bar.h"), 1u)));
}
TEST_F(HeadersTest, OnlyCollectInclusionsInMain) {
std::string BazHeader = testPath("sub/baz.h");
FS.Files[BazHeader] = "";
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = R"cpp(
#include "baz.h"
)cpp";
FS.Files[MainFile] = R"cpp(
#include "bar.h"
)cpp";
EXPECT_THAT(
collectIncludes().MainFileIncludes,
UnorderedElementsAre(AllOf(Written("\"bar.h\""), Resolved(BarHeader))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u),
Distance(testPath("sub/bar.h"), 1u),
Distance(testPath("sub/baz.h"), 2u)));
// includeDepth() also works for non-main files.
EXPECT_THAT(collectIncludes().includeDepth(testPath("sub/bar.h")),
UnorderedElementsAre(Distance(testPath("sub/bar.h"), 0u),
Distance(testPath("sub/baz.h"), 1u)));
}
TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
// We use TestTU here, to ensure we use the preamble replay logic.
// We're testing that the logic doesn't crash, and doesn't result in duplicate
// includes. (We'd test more directly, but it's pretty well encapsulated!)
auto TU = TestTU::withCode(R"cpp(
#include "a.h"
#include "a.h"
void foo();
#include "a.h"
)cpp");
TU.HeaderFilename = "a.h"; // suppress "not found".
EXPECT_THAT(TU.build().getIncludeStructure().MainFileIncludes,
ElementsAre(IncludeLine(1), IncludeLine(2), IncludeLine(4)));
}
TEST_F(HeadersTest, UnResolvedInclusion) {
FS.Files[MainFile] = R"cpp(
#include "foo.h"
)cpp";
EXPECT_THAT(collectIncludes().MainFileIncludes,
UnorderedElementsAre(AllOf(Written("\"foo.h\""), Resolved(""))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u)));
}
TEST_F(HeadersTest, InsertInclude) {
std::string Path = testPath("sub/bar.h");
FS.Files[Path] = "";
EXPECT_EQ(calculate(Path), "\"bar.h\"");
}
TEST_F(HeadersTest, DoNotInsertIfInSameFile) {
MainFile = testPath("main.h");
EXPECT_EQ(calculate(MainFile), "");
}
TEST_F(HeadersTest, ShortenedInclude) {
std::string BarHeader = testPath("sub/bar.h");
EXPECT_EQ(calculate(BarHeader), "\"bar.h\"");
}
TEST_F(HeadersTest, NotShortenedInclude) {
std::string BarHeader = testPath("sub-2/bar.h");
EXPECT_EQ(calculate(BarHeader, ""), "\"" + BarHeader + "\"");
}
TEST_F(HeadersTest, PreferredHeader) {
std::string BarHeader = testPath("sub/bar.h");
EXPECT_EQ(calculate(BarHeader, "<bar>"), "<bar>");
std::string BazHeader = testPath("sub/baz.h");
EXPECT_EQ(calculate(BarHeader, BazHeader), "\"baz.h\"");
}
TEST_F(HeadersTest, DontInsertDuplicatePreferred) {
Inclusion Inc;
Inc.Written = "\"bar.h\"";
Inc.Resolved = "";
EXPECT_EQ(calculate(testPath("sub/bar.h"), "\"bar.h\"", {Inc}), "");
EXPECT_EQ(calculate("\"x.h\"", "\"bar.h\"", {Inc}), "");
}
TEST_F(HeadersTest, DontInsertDuplicateResolved) {
Inclusion Inc;
Inc.Written = "fake-bar.h";
Inc.Resolved = testPath("sub/bar.h");
EXPECT_EQ(calculate(Inc.Resolved, "", {Inc}), "");
// Do not insert preferred.
EXPECT_EQ(calculate(Inc.Resolved, "\"BAR.h\"", {Inc}), "");
}
TEST_F(HeadersTest, PreferInserted) {
auto Edit = insert("<y>");
EXPECT_TRUE(Edit.hasValue());
EXPECT_TRUE(StringRef(Edit->newText).contains("<y>"));
}
} // namespace
} // namespace clangd
} // namespace clang
|
//===-- HeadersTests.cpp - Include headers unit tests -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Headers.h"
#include "Compiler.h"
#include "TestFS.h"
#include "TestTU.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace clang {
namespace clangd {
namespace {
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::UnorderedElementsAre;
class HeadersTest : public ::testing::Test {
public:
HeadersTest() {
CDB.ExtraClangFlags = {SearchDirArg.c_str()};
FS.Files[MainFile] = "";
// Make sure directory sub/ exists.
FS.Files[testPath("sub/EMPTY")] = "";
}
private:
std::unique_ptr<CompilerInstance> setupClang() {
auto Cmd = CDB.getCompileCommand(MainFile);
assert(static_cast<bool>(Cmd));
auto VFS = FS.getFileSystem();
VFS->setCurrentWorkingDirectory(Cmd->Directory);
ParseInputs PI;
PI.CompileCommand = *Cmd;
PI.FS = VFS;
auto CI = buildCompilerInvocation(PI);
EXPECT_TRUE(static_cast<bool>(CI));
// The diagnostic options must be set before creating a CompilerInstance.
CI->getDiagnosticOpts().IgnoreWarnings = true;
auto Clang = prepareCompilerInstance(
std::move(CI), /*Preamble=*/nullptr,
MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
std::make_shared<PCHContainerOperations>(), VFS, IgnoreDiags);
EXPECT_FALSE(Clang->getFrontendOpts().Inputs.empty());
return Clang;
}
protected:
IncludeStructure collectIncludes() {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
IncludeStructure Includes;
Clang->getPreprocessor().addPPCallbacks(
collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
EXPECT_TRUE(Action.Execute());
Action.EndSourceFile();
return Includes;
}
// Calculates the include path, or returns "" on error or header should not be
// inserted.
std::string calculate(PathRef Original, PathRef Preferred = "",
const std::vector<Inclusion> &Inclusions = {}) {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
if (Preferred.empty())
Preferred = Original;
auto ToHeaderFile = [](StringRef Header) {
return HeaderFile{Header,
/*Verbatim=*/!sys::path::is_absolute(Header)};
};
IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
CDB.getCompileCommand(MainFile)->Directory,
Clang->getPreprocessor().getHeaderSearchInfo());
for (const auto &Inc : Inclusions)
Inserter.addExisting(Inc);
auto Declaring = ToHeaderFile(Original);
auto Inserted = ToHeaderFile(Preferred);
if (!Inserter.shouldInsertInclude(Declaring, Inserted))
return "";
std::string Path = Inserter.calculateIncludePath(Declaring, Inserted);
Action.EndSourceFile();
return Path;
}
Optional<TextEdit> insert(StringRef VerbatimHeader) {
auto Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]));
IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
CDB.getCompileCommand(MainFile)->Directory,
Clang->getPreprocessor().getHeaderSearchInfo());
auto Edit = Inserter.insert(VerbatimHeader);
Action.EndSourceFile();
return Edit;
}
MockFSProvider FS;
MockCompilationDatabase CDB;
std::string MainFile = testPath("main.cpp");
std::string Subdir = testPath("sub");
std::string SearchDirArg = (Twine("-I") + Subdir).str();
IgnoringDiagConsumer IgnoreDiags;
};
MATCHER_P(Written, Name, "") { return arg.Written == Name; }
MATCHER_P(Resolved, Name, "") { return arg.Resolved == Name; }
MATCHER_P(IncludeLine, N, "") { return arg.R.start.line == N; }
MATCHER_P2(Distance, File, D, "") {
if (arg.getKey() != File)
*result_listener << "file =" << arg.getKey().str();
if (arg.getValue() != D)
*result_listener << "distance =" << arg.getValue();
return arg.getKey() == File && arg.getValue() == D;
}
TEST_F(HeadersTest, CollectRewrittenAndResolved) {
FS.Files[MainFile] = R"cpp(
#include "sub/bar.h" // not shortest
)cpp";
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = "";
EXPECT_THAT(collectIncludes().MainFileIncludes,
UnorderedElementsAre(
AllOf(Written("\"sub/bar.h\""), Resolved(BarHeader))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u),
Distance(testPath("sub/bar.h"), 1u)));
}
TEST_F(HeadersTest, OnlyCollectInclusionsInMain) {
std::string BazHeader = testPath("sub/baz.h");
FS.Files[BazHeader] = "";
std::string BarHeader = testPath("sub/bar.h");
FS.Files[BarHeader] = R"cpp(
#include "baz.h"
)cpp";
FS.Files[MainFile] = R"cpp(
#include "bar.h"
)cpp";
EXPECT_THAT(
collectIncludes().MainFileIncludes,
UnorderedElementsAre(AllOf(Written("\"bar.h\""), Resolved(BarHeader))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u),
Distance(testPath("sub/bar.h"), 1u),
Distance(testPath("sub/baz.h"), 2u)));
// includeDepth() also works for non-main files.
EXPECT_THAT(collectIncludes().includeDepth(testPath("sub/bar.h")),
UnorderedElementsAre(Distance(testPath("sub/bar.h"), 0u),
Distance(testPath("sub/baz.h"), 1u)));
}
TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
// We use TestTU here, to ensure we use the preamble replay logic.
// We're testing that the logic doesn't crash, and doesn't result in duplicate
// includes. (We'd test more directly, but it's pretty well encapsulated!)
auto TU = TestTU::withCode(R"cpp(
#include "a.h"
#include "a.h"
void foo();
#include "a.h"
)cpp");
TU.HeaderFilename = "a.h"; // suppress "not found".
EXPECT_THAT(TU.build().getIncludeStructure().MainFileIncludes,
ElementsAre(IncludeLine(1), IncludeLine(2), IncludeLine(4)));
}
TEST_F(HeadersTest, UnResolvedInclusion) {
FS.Files[MainFile] = R"cpp(
#include "foo.h"
)cpp";
EXPECT_THAT(collectIncludes().MainFileIncludes,
UnorderedElementsAre(AllOf(Written("\"foo.h\""), Resolved(""))));
EXPECT_THAT(collectIncludes().includeDepth(MainFile),
UnorderedElementsAre(Distance(MainFile, 0u)));
}
TEST_F(HeadersTest, InsertInclude) {
std::string Path = testPath("sub/bar.h");
FS.Files[Path] = "";
EXPECT_EQ(calculate(Path), "\"bar.h\"");
}
TEST_F(HeadersTest, DoNotInsertIfInSameFile) {
MainFile = testPath("main.h");
EXPECT_EQ(calculate(MainFile), "");
}
TEST_F(HeadersTest, ShortenedInclude) {
std::string BarHeader = testPath("sub/bar.h");
EXPECT_EQ(calculate(BarHeader), "\"bar.h\"");
}
TEST_F(HeadersTest, NotShortenedInclude) {
std::string BarHeader = testPath("sub-2/bar.h");
EXPECT_EQ(calculate(BarHeader, ""), "\"" + BarHeader + "\"");
}
TEST_F(HeadersTest, PreferredHeader) {
std::string BarHeader = testPath("sub/bar.h");
EXPECT_EQ(calculate(BarHeader, "<bar>"), "<bar>");
std::string BazHeader = testPath("sub/baz.h");
EXPECT_EQ(calculate(BarHeader, BazHeader), "\"baz.h\"");
}
TEST_F(HeadersTest, DontInsertDuplicatePreferred) {
Inclusion Inc;
Inc.Written = "\"bar.h\"";
Inc.Resolved = "";
EXPECT_EQ(calculate(testPath("sub/bar.h"), "\"bar.h\"", {Inc}), "");
EXPECT_EQ(calculate("\"x.h\"", "\"bar.h\"", {Inc}), "");
}
TEST_F(HeadersTest, DontInsertDuplicateResolved) {
Inclusion Inc;
Inc.Written = "fake-bar.h";
Inc.Resolved = testPath("sub/bar.h");
EXPECT_EQ(calculate(Inc.Resolved, "", {Inc}), "");
// Do not insert preferred.
EXPECT_EQ(calculate(Inc.Resolved, "\"BAR.h\"", {Inc}), "");
}
TEST_F(HeadersTest, PreferInserted) {
auto Edit = insert("<y>");
EXPECT_TRUE(Edit.hasValue());
EXPECT_TRUE(StringRef(Edit->newText).contains("<y>"));
}
} // namespace
} // namespace clangd
} // namespace clang
|
Use buildCompilerInvocation to simplify the HeadersTests, NFC.
|
[clangd] Use buildCompilerInvocation to simplify the HeadersTests, NFC.
git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@349148 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
|
3c1c20e91dbb0a37a4c0ac912e3d9cd444652ef9
|
test/python/resources/classes.hpp
|
test/python/resources/classes.hpp
|
#ifndef __CLASSES__
#define __CLASSES__
namespace unused{
}
typedef char * str;
typedef const char* const const_str;
namespace outside{
class ExternalDependency{
};
}
namespace trial{
class Main{
public:
Main();
Main(const Main &);
virtual ~Main();
Main &operator=(const Main & );
int varargs_method(double d, ...);
int const_varargs_method(double d, ...) const;
struct Internal{
};
class Inner{
public:
Inner();
void method(outside::ExternalDependency d){
}
class Tertiary{
public:
float timestamp(){return 8349876.123f; }
};
};
const double method(const struct Internal &) const{
return 0.1;
}
//std::string string_method();
};
namespace incomplete{
class Incomplete;
class Empty{
};
}
}
#endif
|
#ifndef __CLASSES__
#define __CLASSES__
namespace unused{
}
typedef char * str;
typedef const char* const const_str;
namespace outside{
class ExternalDependency{
};
}
namespace trial{
class A{
public:
void aMethod();
};
class B{
public:
void bMethod();
};
class Inherited: public A{
};
class MultipleInherited: public A, public B{
};
class Main{
public:
Main();
Main(const Main &);
virtual ~Main();
Main &operator=(const Main & );
int varargs_method(double d, ...);
int const_varargs_method(double d, ...) const;
struct Internal{
};
class Inner{
public:
Inner();
void method(outside::ExternalDependency d){
}
class Tertiary{
public:
float timestamp(){return 8349876.123f; }
};
};
const double method(const struct Internal &) const{
return 0.1;
}
//std::string string_method();
};
namespace incomplete{
class Incomplete;
class Empty{
};
}
}
#endif
|
Add inheritance to generation tests
|
Add inheritance to generation tests
|
C++
|
apache-2.0
|
nak/pyllars,nak/pyllars,nak/pyllars
|
dc93efe30e8fe819c7bd3abecf4b6ea50030e394
|
utils/TableGen/CodeEmitterGen.cpp
|
utils/TableGen/CodeEmitterGen.cpp
|
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
void CodeEmitterGen::emitInstrOpBits(std::ostream &o,
const std::vector<RecordVal> &Vals,
std::map<std::string, unsigned> &OpOrder,
std::map<std::string, bool> &OpContinuous)
{
for (unsigned f = 0, e = Vals.size(); f != e; ++f) {
if (Vals[f].getPrefix()) {
BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();
// Scan through the field looking for bit initializers of the current
// variable...
for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) {
Init *I = FieldInitializer->getBit(i);
if (BitInit *BI = dynamic_cast<BitInit*>(I)) {
DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n");
} else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(I)) {
DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n");
} else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(I)) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
// If the bits of the field are laid out consecutively in the
// instruction, then instead of separately ORing in bits, just
// mask and shift the entire field for efficiency.
if (OpContinuous[VI->getName()]) {
// already taken care of in the loop above, thus there is no
// need to individually OR in the bits
// for debugging, output the regular version anyway, commented
DEBUG(o << " // Value |= getValueBit(op"
<< OpOrder[VI->getName()] << ", " << VBI->getBitNum()
<< ")" << " << " << i << ";\n");
} else {
o << " Value |= getValueBit(op" << OpOrder[VI->getName()]
<< ", " << VBI->getBitNum()
<< ")" << " << " << i << ";\n";
}
} else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {
// FIXME: implement this!
std::cerr << "Error: FieldInit not implemented!\n";
abort();
} else {
std::cerr << "Error: unimplemented case in "
<< "CodeEmitterGen::emitInstrOpBits()\n";
abort();
}
}
}
}
}
}
void CodeEmitterGen::run(std::ostream &o) {
CodeGenTarget Target;
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
EmitSourceFileHeader("Machine Code Emitter", o);
o << "namespace llvm {\n\n";
std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
// Emit function declaration
o << "unsigned " << Target.getName() << "CodeEmitter::"
<< "getBinaryCodeForInstr(MachineInstr &MI) {\n"
<< " unsigned Value = 0;\n"
<< " DEBUG(std::cerr << MI);\n"
<< " switch (MI.getOpcode()) {\n";
// Emit a case statement for each opcode
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
o << " case " << Namespace << R->getName() << ": {\n"
<< " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n";
BitsInit *BI = R->getValueAsBitsInit("Inst");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) {
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
BI = NewBI;
}
unsigned Value = 0;
const std::vector<RecordVal> &Vals = R->getValues();
DEBUG(o << " // prefilling: ");
// Start by filling in fixed values...
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
Value |= B->getValue() << (e-i-1);
DEBUG(o << B->getValue());
} else {
DEBUG(o << "0");
}
}
DEBUG(o << "\n");
DEBUG(o << " // " << *R->getValue("Inst") << "\n");
o << " Value = " << Value << "U;\n\n";
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
unsigned op = 0;
std::map<std::string, unsigned> OpOrder;
std::map<std::string, bool> OpContinuous;
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
// Is the operand continuous? If so, we can just mask and OR it in
// instead of doing it bit-by-bit, saving a lot in runtime cost.
BitsInit *InstInit = BI;
int beginBitInVar = -1, endBitInVar = -1;
int beginBitInInst = -1, endBitInInst = -1;
bool continuous = true;
for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) {
if (VarBitInit *VBI =
dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
// only process the current variable
if (VI->getName() != Vals[i].getName())
continue;
if (beginBitInVar == -1)
beginBitInVar = VBI->getBitNum();
if (endBitInVar == -1)
endBitInVar = VBI->getBitNum();
else {
if (endBitInVar == (int)VBI->getBitNum() + 1)
endBitInVar = VBI->getBitNum();
else {
continuous = false;
break;
}
}
if (beginBitInInst == -1)
beginBitInInst = bit;
if (endBitInInst == -1)
endBitInInst = bit;
else {
if (endBitInInst == bit + 1)
endBitInInst = bit;
else {
continuous = false;
break;
}
}
// maintain same distance between bits in field and bits in
// instruction. if the relative distances stay the same
// throughout,
if (beginBitInVar - (int)VBI->getBitNum() !=
beginBitInInst - bit) {
continuous = false;
break;
}
}
}
}
// If we have found no bit in "Inst" which comes from this field, then
// this is not an operand!!
if (beginBitInInst != -1) {
o << " // op" << op << ": " << Vals[i].getName() << "\n"
<< " int op" << op
<<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n";
//<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n";
OpOrder[Vals[i].getName()] = op++;
DEBUG(o << " // Var: begin = " << beginBitInVar
<< ", end = " << endBitInVar
<< "; Inst: begin = " << beginBitInInst
<< ", end = " << endBitInInst << "\n");
if (continuous) {
DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()]
<< "\n");
// Mask off the right bits
// Low mask (ie. shift, if necessary)
assert(endBitInVar >= 0 && "Negative shift amount in masking!");
if (endBitInVar != 0) {
o << " op" << OpOrder[Vals[i].getName()]
<< " >>= " << endBitInVar << ";\n";
beginBitInVar -= endBitInVar;
endBitInVar = 0;
}
// High mask
o << " op" << OpOrder[Vals[i].getName()]
<< " &= (1<<" << beginBitInVar+1 << ") - 1;\n";
// Shift the value to the correct place (according to place in inst)
assert(endBitInInst >= 0 && "Negative shift amount!");
if (endBitInInst != 0)
o << " op" << OpOrder[Vals[i].getName()]
<< " <<= " << endBitInInst << ";\n";
// Just OR in the result
o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n";
}
// otherwise, will be taken care of in the loop below using this
// value:
OpContinuous[Vals[i].getName()] = continuous;
}
}
}
emitInstrOpBits(o, Vals, OpOrder, OpContinuous);
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n"
<< " abort();\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
o << "} // End llvm namespace \n";
}
|
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
void CodeEmitterGen::emitInstrOpBits(std::ostream &o,
const std::vector<RecordVal> &Vals,
std::map<std::string, unsigned> &OpOrder,
std::map<std::string, bool> &OpContinuous)
{
for (unsigned f = 0, e = Vals.size(); f != e; ++f) {
if (Vals[f].getPrefix()) {
BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();
// Scan through the field looking for bit initializers of the current
// variable...
for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) {
Init *I = FieldInitializer->getBit(i);
if (BitInit *BI = dynamic_cast<BitInit*>(I)) {
DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n");
} else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(I)) {
DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n");
} else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(I)) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
// If the bits of the field are laid out consecutively in the
// instruction, then instead of separately ORing in bits, just
// mask and shift the entire field for efficiency.
if (OpContinuous[VI->getName()]) {
// already taken care of in the loop above, thus there is no
// need to individually OR in the bits
// for debugging, output the regular version anyway, commented
DEBUG(o << " // Value |= getValueBit(op"
<< OpOrder[VI->getName()] << ", " << VBI->getBitNum()
<< ")" << " << " << i << ";\n");
} else {
o << " Value |= getValueBit(op" << OpOrder[VI->getName()]
<< ", " << VBI->getBitNum()
<< ")" << " << " << i << ";\n";
}
} else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {
// FIXME: implement this!
std::cerr << "Error: FieldInit not implemented!\n";
abort();
} else {
std::cerr << "Error: unimplemented case in "
<< "CodeEmitterGen::emitInstrOpBits()\n";
abort();
}
}
}
}
}
}
void CodeEmitterGen::run(std::ostream &o) {
CodeGenTarget Target;
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
EmitSourceFileHeader("Machine Code Emitter", o);
std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
// Emit function declaration
o << "unsigned " << Target.getName() << "CodeEmitter::"
<< "getBinaryCodeForInstr(MachineInstr &MI) {\n"
<< " unsigned Value = 0;\n"
<< " DEBUG(std::cerr << MI);\n"
<< " switch (MI.getOpcode()) {\n";
// Emit a case statement for each opcode
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
o << " case " << Namespace << R->getName() << ": {\n"
<< " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n";
BitsInit *BI = R->getValueAsBitsInit("Inst");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) {
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
BI = NewBI;
}
unsigned Value = 0;
const std::vector<RecordVal> &Vals = R->getValues();
DEBUG(o << " // prefilling: ");
// Start by filling in fixed values...
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
Value |= B->getValue() << (e-i-1);
DEBUG(o << B->getValue());
} else {
DEBUG(o << "0");
}
}
DEBUG(o << "\n");
DEBUG(o << " // " << *R->getValue("Inst") << "\n");
o << " Value = " << Value << "U;\n\n";
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
unsigned op = 0;
std::map<std::string, unsigned> OpOrder;
std::map<std::string, bool> OpContinuous;
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
// Is the operand continuous? If so, we can just mask and OR it in
// instead of doing it bit-by-bit, saving a lot in runtime cost.
BitsInit *InstInit = BI;
int beginBitInVar = -1, endBitInVar = -1;
int beginBitInInst = -1, endBitInInst = -1;
bool continuous = true;
for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) {
if (VarBitInit *VBI =
dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
// only process the current variable
if (VI->getName() != Vals[i].getName())
continue;
if (beginBitInVar == -1)
beginBitInVar = VBI->getBitNum();
if (endBitInVar == -1)
endBitInVar = VBI->getBitNum();
else {
if (endBitInVar == (int)VBI->getBitNum() + 1)
endBitInVar = VBI->getBitNum();
else {
continuous = false;
break;
}
}
if (beginBitInInst == -1)
beginBitInInst = bit;
if (endBitInInst == -1)
endBitInInst = bit;
else {
if (endBitInInst == bit + 1)
endBitInInst = bit;
else {
continuous = false;
break;
}
}
// maintain same distance between bits in field and bits in
// instruction. if the relative distances stay the same
// throughout,
if (beginBitInVar - (int)VBI->getBitNum() !=
beginBitInInst - bit) {
continuous = false;
break;
}
}
}
}
// If we have found no bit in "Inst" which comes from this field, then
// this is not an operand!!
if (beginBitInInst != -1) {
o << " // op" << op << ": " << Vals[i].getName() << "\n"
<< " int op" << op
<<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n";
//<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n";
OpOrder[Vals[i].getName()] = op++;
DEBUG(o << " // Var: begin = " << beginBitInVar
<< ", end = " << endBitInVar
<< "; Inst: begin = " << beginBitInInst
<< ", end = " << endBitInInst << "\n");
if (continuous) {
DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()]
<< "\n");
// Mask off the right bits
// Low mask (ie. shift, if necessary)
assert(endBitInVar >= 0 && "Negative shift amount in masking!");
if (endBitInVar != 0) {
o << " op" << OpOrder[Vals[i].getName()]
<< " >>= " << endBitInVar << ";\n";
beginBitInVar -= endBitInVar;
endBitInVar = 0;
}
// High mask
o << " op" << OpOrder[Vals[i].getName()]
<< " &= (1<<" << beginBitInVar+1 << ") - 1;\n";
// Shift the value to the correct place (according to place in inst)
assert(endBitInInst >= 0 && "Negative shift amount!");
if (endBitInInst != 0)
o << " op" << OpOrder[Vals[i].getName()]
<< " <<= " << endBitInInst << ";\n";
// Just OR in the result
o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n";
}
// otherwise, will be taken care of in the loop below using this
// value:
OpContinuous[Vals[i].getName()] = continuous;
}
}
}
emitInstrOpBits(o, Vals, OpOrder, OpContinuous);
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n"
<< " abort();\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
|
Fix an incompatibility with GCC 4.1, thanks to Vladimir Merzliakov for pointing this out!
|
Fix an incompatibility with GCC 4.1, thanks to Vladimir Merzliakov
for pointing this out!
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@23963 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
|
64ed07b552c2f044f59b269a383d7adc9405f650
|
tools/flags/SkCommandLineFlags.cpp
|
tools/flags/SkCommandLineFlags.cpp
|
/*
* 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 "SkCommandLineFlags.h"
#include "SkTDArray.h"
bool SkFlagInfo::CreateStringFlag(const char* name, const char* shortName,
SkCommandLineFlags::StringArray* pStrings,
const char* defaultValue, const char* helpString) {
SkFlagInfo* info = SkNEW_ARGS(SkFlagInfo, (name, shortName, kString_FlagType, helpString));
info->fDefaultString.set(defaultValue);
info->fStrings = pStrings;
SetDefaultStrings(pStrings, defaultValue);
return true;
}
void SkFlagInfo::SetDefaultStrings(SkCommandLineFlags::StringArray* pStrings,
const char* defaultValue) {
pStrings->reset();
// If default is "", leave the array empty.
size_t defaultLength = strlen(defaultValue);
if (defaultLength > 0) {
const char* const defaultEnd = defaultValue + defaultLength;
const char* begin = defaultValue;
while (true) {
while (begin < defaultEnd && ' ' == *begin) {
begin++;
}
if (begin < defaultEnd) {
const char* end = begin + 1;
while (end < defaultEnd && ' ' != *end) {
end++;
}
size_t length = end - begin;
pStrings->append(begin, length);
begin = end + 1;
} else {
break;
}
}
}
}
static bool string_is_in(const char* target, const char* set[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (0 == strcmp(target, set[i])) {
return true;
}
}
return false;
}
/**
* Check to see whether string represents a boolean value.
* @param string C style string to parse.
* @param result Pointer to a boolean which will be set to the value in the string, if the
* string represents a boolean.
* @param boolean True if the string represents a boolean, false otherwise.
*/
static bool parse_bool_arg(const char* string, bool* result) {
static const char* trueValues[] = { "1", "TRUE", "true" };
if (string_is_in(string, trueValues, SK_ARRAY_COUNT(trueValues))) {
*result = true;
return true;
}
static const char* falseValues[] = { "0", "FALSE", "false" };
if (string_is_in(string, falseValues, SK_ARRAY_COUNT(falseValues))) {
*result = false;
return true;
}
SkDebugf("Parameter \"%s\" not supported.\n", string);
return false;
}
bool SkFlagInfo::match(const char* string) {
if (SkStrStartsWith(string, '-') && strlen(string) > 1) {
string++;
const SkString* compareName;
if (SkStrStartsWith(string, '-') && strlen(string) > 1) {
string++;
// There were two dashes. Compare against full name.
compareName = &fName;
} else {
// One dash. Compare against the short name.
compareName = &fShortName;
}
if (kBool_FlagType == fFlagType) {
// In this case, go ahead and set the value.
if (compareName->equals(string)) {
*fBoolValue = true;
return true;
}
if (SkStrStartsWith(string, "no") && strlen(string) > 2) {
string += 2;
// Only allow "no" to be prepended to the full name.
if (fName.equals(string)) {
*fBoolValue = false;
return true;
}
return false;
}
int equalIndex = SkStrFind(string, "=");
if (equalIndex > 0) {
// The string has an equal sign. Check to see if the string matches.
SkString flag(string, equalIndex);
if (flag.equals(*compareName)) {
// Check to see if the remainder beyond the equal sign is true or false:
string += equalIndex + 1;
parse_bool_arg(string, fBoolValue);
return true;
} else {
return false;
}
}
}
return compareName->equals(string);
} else {
// Has no dash
return false;
}
return false;
}
SkFlagInfo* SkCommandLineFlags::gHead;
SkString SkCommandLineFlags::gUsage;
void SkCommandLineFlags::SetUsage(const char* usage) {
gUsage.set(usage);
}
// Maximum line length for the help message.
#define LINE_LENGTH 80
static void print_help_for_flag(const SkFlagInfo* flag) {
SkDebugf("\t--%s", flag->name().c_str());
const SkString& shortName = flag->shortName();
if (shortName.size() > 0) {
SkDebugf(" or -%s", shortName.c_str());
}
SkDebugf(":\ttype: %s", flag->typeAsString().c_str());
if (flag->defaultValue().size() > 0) {
SkDebugf("\tdefault: %s", flag->defaultValue().c_str());
}
SkDebugf("\n");
const SkString& help = flag->help();
size_t length = help.size();
const char* currLine = help.c_str();
const char* stop = currLine + length;
while (currLine < stop) {
if (strlen(currLine) < LINE_LENGTH) {
// Only one line length's worth of text left.
SkDebugf("\t\t%s\n", currLine);
break;
}
int lineBreak = SkStrFind(currLine, "\n");
if (lineBreak < 0 || lineBreak > LINE_LENGTH) {
// No line break within line length. Will need to insert one.
// Find a space before the line break.
int spaceIndex = LINE_LENGTH - 1;
while (spaceIndex > 0 && currLine[spaceIndex] != ' ') {
spaceIndex--;
}
int gap;
if (0 == spaceIndex) {
// No spaces on the entire line. Go ahead and break mid word.
spaceIndex = LINE_LENGTH;
gap = 0;
} else {
// Skip the space on the next line
gap = 1;
}
SkDebugf("\t\t%.*s\n", spaceIndex, currLine);
currLine += spaceIndex + gap;
} else {
// the line break is within the limit. Break there.
lineBreak++;
SkDebugf("\t\t%.*s", lineBreak, currLine);
currLine += lineBreak;
}
}
SkDebugf("\n");
}
void SkCommandLineFlags::Parse(int argc, char** argv) {
// Only allow calling this function once.
static bool gOnce;
if (gOnce) {
SkDebugf("Parse should only be called once at the beginning of main!\n");
SkASSERT(false);
return;
}
gOnce = true;
bool helpPrinted = false;
// Loop over argv, starting with 1, since the first is just the name of the program.
for (int i = 1; i < argc; i++) {
if (0 == strcmp("-h", argv[i]) || 0 == strcmp("--help", argv[i])) {
// Print help message.
SkTDArray<const char*> helpFlags;
for (int j = i + 1; j < argc; j++) {
if (SkStrStartsWith(argv[j], '-')) {
break;
}
helpFlags.append(1, &argv[j]);
}
if (0 == helpFlags.count()) {
// Only print general help message if help for specific flags is not requested.
SkDebugf("%s\n%s\n", argv[0], gUsage.c_str());
}
SkDebugf("Flags:\n");
SkFlagInfo* flag = SkCommandLineFlags::gHead;
while (flag != NULL) {
// If no flags followed --help, print them all
bool printFlag = 0 == helpFlags.count();
if (!printFlag) {
for (int k = 0; k < helpFlags.count(); k++) {
if (flag->name().equals(helpFlags[k]) ||
flag->shortName().equals(helpFlags[k])) {
printFlag = true;
helpFlags.remove(k);
break;
}
}
}
if (printFlag) {
print_help_for_flag(flag);
}
flag = flag->next();
}
if (helpFlags.count() > 0) {
SkDebugf("Requested help for unrecognized flags:\n");
for (int k = 0; k < helpFlags.count(); k++) {
SkDebugf("\t--%s\n", helpFlags[k]);
}
}
helpPrinted = true;
}
if (!helpPrinted) {
bool flagMatched = false;
SkFlagInfo* flag = gHead;
while (flag != NULL) {
if (flag->match(argv[i])) {
flagMatched = true;
switch (flag->getFlagType()) {
case SkFlagInfo::kBool_FlagType:
// Can be handled by match, above, but can also be set by the next
// string.
if (i+1 < argc && !SkStrStartsWith(argv[i+1], '-')) {
i++;
bool value;
if (parse_bool_arg(argv[i], &value)) {
flag->setBool(value);
}
}
break;
case SkFlagInfo::kString_FlagType:
flag->resetStrings();
// Add all arguments until another flag is reached.
while (i+1 < argc && !SkStrStartsWith(argv[i+1], '-')) {
i++;
flag->append(argv[i]);
}
break;
case SkFlagInfo::kInt_FlagType:
i++;
flag->setInt(atoi(argv[i]));
break;
case SkFlagInfo::kDouble_FlagType:
i++;
flag->setDouble(atof(argv[i]));
break;
default:
SkASSERT(!"Invalid flag type");
}
break;
}
flag = flag->next();
}
if (!flagMatched) {
SkDebugf("Got unknown flag \"%s\". Exiting.\n", argv[i]);
exit(-1);
}
}
}
// Since all of the flags have been set, release the memory used by each
// flag. FLAGS_x can still be used after this.
SkFlagInfo* flag = gHead;
gHead = NULL;
while (flag != NULL) {
SkFlagInfo* next = flag->next();
SkDELETE(flag);
flag = next;
}
if (helpPrinted) {
exit(0);
}
}
|
/*
* 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 "SkCommandLineFlags.h"
#include "SkTDArray.h"
bool SkFlagInfo::CreateStringFlag(const char* name, const char* shortName,
SkCommandLineFlags::StringArray* pStrings,
const char* defaultValue, const char* helpString) {
SkFlagInfo* info = SkNEW_ARGS(SkFlagInfo, (name, shortName, kString_FlagType, helpString));
info->fDefaultString.set(defaultValue);
info->fStrings = pStrings;
SetDefaultStrings(pStrings, defaultValue);
return true;
}
void SkFlagInfo::SetDefaultStrings(SkCommandLineFlags::StringArray* pStrings,
const char* defaultValue) {
pStrings->reset();
if (NULL == defaultValue) {
return;
}
// If default is "", leave the array empty.
size_t defaultLength = strlen(defaultValue);
if (defaultLength > 0) {
const char* const defaultEnd = defaultValue + defaultLength;
const char* begin = defaultValue;
while (true) {
while (begin < defaultEnd && ' ' == *begin) {
begin++;
}
if (begin < defaultEnd) {
const char* end = begin + 1;
while (end < defaultEnd && ' ' != *end) {
end++;
}
size_t length = end - begin;
pStrings->append(begin, length);
begin = end + 1;
} else {
break;
}
}
}
}
static bool string_is_in(const char* target, const char* set[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (0 == strcmp(target, set[i])) {
return true;
}
}
return false;
}
/**
* Check to see whether string represents a boolean value.
* @param string C style string to parse.
* @param result Pointer to a boolean which will be set to the value in the string, if the
* string represents a boolean.
* @param boolean True if the string represents a boolean, false otherwise.
*/
static bool parse_bool_arg(const char* string, bool* result) {
static const char* trueValues[] = { "1", "TRUE", "true" };
if (string_is_in(string, trueValues, SK_ARRAY_COUNT(trueValues))) {
*result = true;
return true;
}
static const char* falseValues[] = { "0", "FALSE", "false" };
if (string_is_in(string, falseValues, SK_ARRAY_COUNT(falseValues))) {
*result = false;
return true;
}
SkDebugf("Parameter \"%s\" not supported.\n", string);
return false;
}
bool SkFlagInfo::match(const char* string) {
if (SkStrStartsWith(string, '-') && strlen(string) > 1) {
string++;
const SkString* compareName;
if (SkStrStartsWith(string, '-') && strlen(string) > 1) {
string++;
// There were two dashes. Compare against full name.
compareName = &fName;
} else {
// One dash. Compare against the short name.
compareName = &fShortName;
}
if (kBool_FlagType == fFlagType) {
// In this case, go ahead and set the value.
if (compareName->equals(string)) {
*fBoolValue = true;
return true;
}
if (SkStrStartsWith(string, "no") && strlen(string) > 2) {
string += 2;
// Only allow "no" to be prepended to the full name.
if (fName.equals(string)) {
*fBoolValue = false;
return true;
}
return false;
}
int equalIndex = SkStrFind(string, "=");
if (equalIndex > 0) {
// The string has an equal sign. Check to see if the string matches.
SkString flag(string, equalIndex);
if (flag.equals(*compareName)) {
// Check to see if the remainder beyond the equal sign is true or false:
string += equalIndex + 1;
parse_bool_arg(string, fBoolValue);
return true;
} else {
return false;
}
}
}
return compareName->equals(string);
} else {
// Has no dash
return false;
}
return false;
}
SkFlagInfo* SkCommandLineFlags::gHead;
SkString SkCommandLineFlags::gUsage;
void SkCommandLineFlags::SetUsage(const char* usage) {
gUsage.set(usage);
}
// Maximum line length for the help message.
#define LINE_LENGTH 80
static void print_help_for_flag(const SkFlagInfo* flag) {
SkDebugf("\t--%s", flag->name().c_str());
const SkString& shortName = flag->shortName();
if (shortName.size() > 0) {
SkDebugf(" or -%s", shortName.c_str());
}
SkDebugf(":\ttype: %s", flag->typeAsString().c_str());
if (flag->defaultValue().size() > 0) {
SkDebugf("\tdefault: %s", flag->defaultValue().c_str());
}
SkDebugf("\n");
const SkString& help = flag->help();
size_t length = help.size();
const char* currLine = help.c_str();
const char* stop = currLine + length;
while (currLine < stop) {
if (strlen(currLine) < LINE_LENGTH) {
// Only one line length's worth of text left.
SkDebugf("\t\t%s\n", currLine);
break;
}
int lineBreak = SkStrFind(currLine, "\n");
if (lineBreak < 0 || lineBreak > LINE_LENGTH) {
// No line break within line length. Will need to insert one.
// Find a space before the line break.
int spaceIndex = LINE_LENGTH - 1;
while (spaceIndex > 0 && currLine[spaceIndex] != ' ') {
spaceIndex--;
}
int gap;
if (0 == spaceIndex) {
// No spaces on the entire line. Go ahead and break mid word.
spaceIndex = LINE_LENGTH;
gap = 0;
} else {
// Skip the space on the next line
gap = 1;
}
SkDebugf("\t\t%.*s\n", spaceIndex, currLine);
currLine += spaceIndex + gap;
} else {
// the line break is within the limit. Break there.
lineBreak++;
SkDebugf("\t\t%.*s", lineBreak, currLine);
currLine += lineBreak;
}
}
SkDebugf("\n");
}
void SkCommandLineFlags::Parse(int argc, char** argv) {
// Only allow calling this function once.
static bool gOnce;
if (gOnce) {
SkDebugf("Parse should only be called once at the beginning of main!\n");
SkASSERT(false);
return;
}
gOnce = true;
bool helpPrinted = false;
// Loop over argv, starting with 1, since the first is just the name of the program.
for (int i = 1; i < argc; i++) {
if (0 == strcmp("-h", argv[i]) || 0 == strcmp("--help", argv[i])) {
// Print help message.
SkTDArray<const char*> helpFlags;
for (int j = i + 1; j < argc; j++) {
if (SkStrStartsWith(argv[j], '-')) {
break;
}
helpFlags.append(1, &argv[j]);
}
if (0 == helpFlags.count()) {
// Only print general help message if help for specific flags is not requested.
SkDebugf("%s\n%s\n", argv[0], gUsage.c_str());
}
SkDebugf("Flags:\n");
SkFlagInfo* flag = SkCommandLineFlags::gHead;
while (flag != NULL) {
// If no flags followed --help, print them all
bool printFlag = 0 == helpFlags.count();
if (!printFlag) {
for (int k = 0; k < helpFlags.count(); k++) {
if (flag->name().equals(helpFlags[k]) ||
flag->shortName().equals(helpFlags[k])) {
printFlag = true;
helpFlags.remove(k);
break;
}
}
}
if (printFlag) {
print_help_for_flag(flag);
}
flag = flag->next();
}
if (helpFlags.count() > 0) {
SkDebugf("Requested help for unrecognized flags:\n");
for (int k = 0; k < helpFlags.count(); k++) {
SkDebugf("\t--%s\n", helpFlags[k]);
}
}
helpPrinted = true;
}
if (!helpPrinted) {
bool flagMatched = false;
SkFlagInfo* flag = gHead;
while (flag != NULL) {
if (flag->match(argv[i])) {
flagMatched = true;
switch (flag->getFlagType()) {
case SkFlagInfo::kBool_FlagType:
// Can be handled by match, above, but can also be set by the next
// string.
if (i+1 < argc && !SkStrStartsWith(argv[i+1], '-')) {
i++;
bool value;
if (parse_bool_arg(argv[i], &value)) {
flag->setBool(value);
}
}
break;
case SkFlagInfo::kString_FlagType:
flag->resetStrings();
// Add all arguments until another flag is reached.
while (i+1 < argc && !SkStrStartsWith(argv[i+1], '-')) {
i++;
flag->append(argv[i]);
}
break;
case SkFlagInfo::kInt_FlagType:
i++;
flag->setInt(atoi(argv[i]));
break;
case SkFlagInfo::kDouble_FlagType:
i++;
flag->setDouble(atof(argv[i]));
break;
default:
SkASSERT(!"Invalid flag type");
}
break;
}
flag = flag->next();
}
if (!flagMatched) {
SkDebugf("Got unknown flag \"%s\". Exiting.\n", argv[i]);
exit(-1);
}
}
}
// Since all of the flags have been set, release the memory used by each
// flag. FLAGS_x can still be used after this.
SkFlagInfo* flag = gHead;
gHead = NULL;
while (flag != NULL) {
SkFlagInfo* next = flag->next();
SkDELETE(flag);
flag = next;
}
if (helpPrinted) {
exit(0);
}
}
|
Fix the build.
|
Fix the build.
Allow NULL for defaultValue in SkCommandLineFlags.
unreviewed.
Review URL: https://codereview.chromium.org/14472017
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@8847 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,MatChung/color-emoji.skia,Hankuo/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,Frankie-666/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia,hbwhlklive/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,Frankie-666/color-emoji.skia,hbwhlklive/color-emoji.skia
|
6c4bcf63d864d7a040a984dfebe8079311ae2020
|
src/mlpack/methods/ann/layer/dropout_layer.hpp
|
src/mlpack/methods/ann/layer/dropout_layer.hpp
|
/**
* @file dropout_layer.hpp
* @author Marcus Edel
*
* Definition of the DropoutLayer class, which implements a regularizer that
* randomly sets units to zero. Preventing units from co-adapting.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The dropout layer is a regularizer that randomly with probability ratio
* sets input values to zero and scales the remaining elements by factor 1 /
* (1 - ratio). If rescale is true the input is scaled with 1 / (1-p) when
* deterministic is false. In the deterministic mode (during testing), the layer
* just scales the output.
*
* Note: During training you should set deterministic to false and during
* testing you should set deterministic to true.
*
* For more information, see the following.
*
* @code
* @article{Hinton2012,
* author = {Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky,
* Ilya Sutskever, Ruslan Salakhutdinov},
* title = {Improving neural networks by preventing co-adaptation of feature
* detectors},
* journal = {CoRR},
* volume = {abs/1207.0580},
* year = {2012},
* }
* @endcode
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class DropoutLayer
{
public:
/**
* Create the BaseLayer object using the specified number of units.
*
* @param outSize The number of output units.
*/
DropoutLayer(const double ratio = 0.5,
const bool rescale = true) :
ratio(ratio),
rescale(rescale)
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Mat<eT> >(input.n_rows, input.n_cols);
arma::mat::iterator a = mask.begin();
arma::mat::iterator b = mask.end();
for(arma::mat::iterator i = a; i != b; ++i)
{
(*i) = (*i) > ratio;
}
output = input % mask * scale;
}
}
/**
* Ordinary feed backward pass of the dropout layer.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& /* unused */,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g)
{
g = gy % mask * scale;
}
//! Get the input parameter.
InputDataType& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the detla.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! The value of the deterministic parameter.
bool Deterministic() const {return deterministic; }
//! Modify the value of the deterministic parameter.
bool& Deterministic() {return deterministic; }
//! The probability of setting a value to zero.
double Ratio() const {return ratio; }
//! Modify the probability of setting a value to zero.
double& Ratio() {return ratio; }
//! The value of the rescale parameter.
bool Rescale() const {return rescale; }
//! Modify the value of the rescale parameter.
bool& Rescale() {return rescale; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored mast object.
OutputDataType mask;
//! The probability of setting a value to zero.
double ratio;
//! The scale fraction.
double scale;
//! If true dropout and scaling is disabled, see notes above.
bool deterministic;
//! If true the input is rescaled when deterministic is False.
bool rescale;
}; // class DropoutLayer
//! Layer traits for the bias layer.
template<
typename InputDataType,
typename OutputDataType
>
class LayerTraits<DropoutLayer<InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
}; // namespace ann
}; // namespace mlpack
#endif
|
/**
* @file dropout_layer.hpp
* @author Marcus Edel
*
* Definition of the DropoutLayer class, which implements a regularizer that
* randomly sets units to zero. Preventing units from co-adapting.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The dropout layer is a regularizer that randomly with probability ratio
* sets input values to zero and scales the remaining elements by factor 1 /
* (1 - ratio). If rescale is true the input is scaled with 1 / (1-p) when
* deterministic is false. In the deterministic mode (during testing), the layer
* just scales the output.
*
* Note: During training you should set deterministic to false and during
* testing you should set deterministic to true.
*
* For more information, see the following.
*
* @code
* @article{Hinton2012,
* author = {Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky,
* Ilya Sutskever, Ruslan Salakhutdinov},
* title = {Improving neural networks by preventing co-adaptation of feature
* detectors},
* journal = {CoRR},
* volume = {abs/1207.0580},
* year = {2012},
* }
* @endcode
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class DropoutLayer
{
public:
/**
* Create the BaseLayer object using the specified number of units.
*
* @param outSize The number of output units.
*/
DropoutLayer(const double ratio = 0.5,
const bool rescale = true) :
ratio(ratio),
rescale(rescale)
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Mat<eT> >(input.n_rows, input.n_cols);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Cube<eT> >(input.n_rows, input.n_cols,
input.n_slices);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed backward pass of the dropout layer.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename DataType>
void Backward(const DataType& /* unused */,
const DataType& gy,
DataType& g)
{
g = gy % mask * scale;
}
//! Get the input parameter.
InputDataType& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the detla.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! The value of the deterministic parameter.
bool Deterministic() const {return deterministic; }
//! Modify the value of the deterministic parameter.
bool& Deterministic() {return deterministic; }
//! The probability of setting a value to zero.
double Ratio() const {return ratio; }
//! Modify the probability of setting a value to zero.
double& Ratio() {return ratio; }
//! The value of the rescale parameter.
bool Rescale() const {return rescale; }
//! Modify the value of the rescale parameter.
bool& Rescale() {return rescale; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored mast object.
OutputDataType mask;
//! The probability of setting a value to zero.
double ratio;
//! The scale fraction.
double scale;
//! If true dropout and scaling is disabled, see notes above.
bool deterministic;
//! If true the input is rescaled when deterministic is False.
bool rescale;
}; // class DropoutLayer
//! Layer traits for the bias layer.
template <
typename InputDataType,
typename OutputDataType
>
class LayerTraits<DropoutLayer<InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
/**
* Standard Dropout-Layer2D.
*/
template <
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
using DropoutLayer2D = DropoutLayer<InputDataType, OutputDataType>;
}; // namespace ann
}; // namespace mlpack
#endif
|
Add 3rd-order tensor support (Dropout layer).
|
Add 3rd-order tensor support (Dropout layer).
|
C++
|
bsd-3-clause
|
ranjan1990/mlpack,ranjan1990/mlpack,erubboli/mlpack,palashahuja/mlpack,ersanliqiao/mlpack,ajjl/mlpack,stereomatchingkiss/mlpack,darcyliu/mlpack,theranger/mlpack,ajjl/mlpack,ajjl/mlpack,palashahuja/mlpack,ranjan1990/mlpack,lezorich/mlpack,theranger/mlpack,stereomatchingkiss/mlpack,ersanliqiao/mlpack,ersanliqiao/mlpack,stereomatchingkiss/mlpack,lezorich/mlpack,darcyliu/mlpack,theranger/mlpack,BookChan/mlpack,darcyliu/mlpack,erubboli/mlpack,BookChan/mlpack,BookChan/mlpack,palashahuja/mlpack,lezorich/mlpack,erubboli/mlpack
|
3424ad9f8a42e2302c800c55fc7f98eb9e3498e5
|
lib/node_modules/@stdlib/strided/common/examples/addon-nan-polymorphic/addon.cpp
|
lib/node_modules/@stdlib/strided/common/examples/addon-nan-polymorphic/addon.cpp
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
/**
* Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*/
#include <stdint.h>
#include <nan.h>
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/strided_binary.h"
/**
* Add-on namespace.
*/
namespace addon_strided_add {
using Nan::FunctionCallbackInfo;
using Nan::TypedArrayContents;
using Nan::ThrowTypeError;
using Nan::ThrowError;
using v8::Local;
using v8::Value;
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param x typed array
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( Local<Value> x ) {
if ( x->IsFloat64Array() ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( x->IsFloat32Array() ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( x->IsInt32Array() ) {
return STDLIB_NDARRAY_INT32;
}
if ( x->IsUint32Array() ) {
return STDLIB_NDARRAY_UINT32;
}
if ( x->IsInt16Array() ) {
return STDLIB_NDARRAY_INT16;
}
if ( x->IsUint16Array() ) {
return STDLIB_NDARRAY_UINT16;
}
if ( x->IsInt8Array() ) {
return STDLIB_NDARRAY_INT8;
}
if ( x->IsUint8Array() ) {
return STDLIB_NDARRAY_UINT8;
}
return STDLIB_NDARRAY_UINT8; // Uint8ClampedArray
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* When called from JavaScript, the function expects the following arguments:
*
* * __n__: number of elements.
* * __X__: input typed array.
* * __sx__: `X` stride length.
* * __Y__: input typed array.
* * __sy__: `Y` typed array stride length.
* * __Z__: destination typed array.
* * __sz__: destination typed array stride length.
*
* @param info arguments
*/
void node_add( const FunctionCallbackInfo<Value>& info ) {
enum STDLIB_NDARRAY_DTYPE types[ 3 ];
uint8_t *arrays[ 3 ];
int64_t strides[ 3 ];
int64_t shape[ 1 ];
uint8_t scalarX;
uint8_t scalarY;
int64_t nargs;
int64_t nout;
int64_t nin;
int64_t i;
int64_t j;
int64_t n;
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Compute the index of the first output strided array argument:
n = ( nin*2 ) + 1;
if ( info.Length() != nargs ) {
ThrowError( "invalid invocation. Incorrect number of arguments." );
return;
}
// The first argument is always the number of elements over which to iterate...
if ( !info[ 0 ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. First argument must be a number." );
return;
} else {
shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() );
}
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
if ( !info[ i ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. Stride argument must be a number." );
return;
}
j = ( i-2 ) / 2;
strides[ j ] = static_cast<int64_t>( info[ i ]->IntegerValue() );
}
#if defined(V8_MAJOR_VERSION) && ( V8_MAJOR_VERSION > 4 || ( V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3 ) )
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < n; i += 2 ) {
if ( info[ i ]->IsArrayBufferView() ) {
j = ( i-1 ) / 2;
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else if ( info[ i ]->IsNumber() ) {
scalarX = 1; // TODO
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = n; i < nargs; i++ ) {
if ( !info[ i ]->IsArrayBufferView() ) {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return;
} else {
j = ( i-1 ) / 2;
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
}
}
#else
// TODO: add support for older Node versions (type verification and strides; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc and https://github.com/nodejs/nan/blob/master/nan_typedarray_contents.h)
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < n; i += 2 ) {
if ( info[ i ]->IsNumber() ) {
scalarX = 1; // TODO
} else if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
j = ( i-1 ) / 2;
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from the typed array instance)
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = n; i < nargs; i++ ) {
if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
j = ( i-1 ) / 2;
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from typed array instance)
} else {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return;
}
}
#endif
// Broadcasting...
if ( scalarX == 1 ) {
if ( scalarY == 1 ) {
ThrowError( "invalid input arguments. At least one of the second and fourth arguments must be a typed array." );
return;
}
// Create an array having the closest "compatible" type...
arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
if ( scalarY == 1 ) {
// Create an array having the closest "compatible" type...
arrays[ 1 ] = broadcast( static_cast<double>( info[ 3 ]->NumberValue() ), types[ 1 ] );
}
// Perform addition:
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
}
NAN_MODULE_INIT( Init ) {
Nan::Export( target, "add", node_add );
}
NODE_MODULE( addon, Init )
} // end namespace addon_strided_add
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
/**
* Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*/
#include <stdint.h>
#include <nan.h>
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/strided_binary.h"
/**
* Add-on namespace.
*/
namespace addon_strided_add {
using Nan::FunctionCallbackInfo;
using Nan::TypedArrayContents;
using Nan::ThrowTypeError;
using Nan::ThrowError;
using v8::Local;
using v8::Value;
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param x typed array
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( Local<Value> x ) {
if ( x->IsFloat64Array() ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( x->IsFloat32Array() ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( x->IsInt32Array() ) {
return STDLIB_NDARRAY_INT32;
}
if ( x->IsUint32Array() ) {
return STDLIB_NDARRAY_UINT32;
}
if ( x->IsInt16Array() ) {
return STDLIB_NDARRAY_INT16;
}
if ( x->IsUint16Array() ) {
return STDLIB_NDARRAY_UINT16;
}
if ( x->IsInt8Array() ) {
return STDLIB_NDARRAY_INT8;
}
if ( x->IsUint8Array() ) {
return STDLIB_NDARRAY_UINT8;
}
return STDLIB_NDARRAY_UINT8; // Uint8ClampedArray
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* When called from JavaScript, the function expects the following arguments:
*
* * __n__: number of elements.
* * __X__: input typed array.
* * __sx__: `X` stride length.
* * __Y__: input typed array.
* * __sy__: `Y` typed array stride length.
* * __Z__: destination typed array.
* * __sz__: destination typed array stride length.
*
* @param info arguments
*/
void node_add( const FunctionCallbackInfo<Value>& info ) {
enum STDLIB_NDARRAY_DTYPE types[3];
uint8_t *arrays[3];
int64_t strides[3];
int64_t shape[1];
int64_t sargs; // WARNING: we assume no more than 64 input strided array arguments, which seems a reasonable assumption
int64_t nargs;
int64_t nout;
int64_t nin;
int64_t i;
int64_t j;
int64_t n;
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Compute the index of the first output strided array argument:
n = ( nin*2 ) + 1;
if ( info.Length() != nargs ) {
ThrowError( "invalid invocation. Incorrect number of arguments." );
return;
}
// The first argument is always the number of elements over which to iterate...
if ( !info[ 0 ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. First argument must be a number." );
return;
} else {
shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() );
}
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
if ( !info[ i ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. Stride argument must be a number." );
return;
}
j = ( i-2 ) / 2;
strides[ j ] = static_cast<int64_t>( info[ i ]->IntegerValue() );
}
#if defined(V8_MAJOR_VERSION) && ( V8_MAJOR_VERSION > 4 || ( V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3 ) )
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < n; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsArrayBufferView() ) {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = n; i < nargs; i++ ) {
j = ( i-1 ) / 2;
if ( !info[ i ]->IsArrayBufferView() ) {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return;
} else {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
}
}
#else
// TODO: add support for older Node versions (type verification and strides; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc and https://github.com/nodejs/nan/blob/master/nan_typedarray_contents.h)
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < n; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
} else if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from the typed array instance)
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = n; i < nargs; i++ ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from typed array instance)
} else {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return;
}
}
#endif
// Broadcasting...
if ( scalarX == 1 ) {
if ( scalarY == 1 ) {
ThrowError( "invalid input arguments. At least one of the second and fourth arguments must be a typed array." );
return;
}
// Create an array having the closest "compatible" type...
arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
if ( scalarY == 1 ) {
// Create an array having the closest "compatible" type...
arrays[ 1 ] = broadcast( static_cast<double>( info[ 3 ]->NumberValue() ), types[ 1 ] );
}
// Perform addition:
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
}
NAN_MODULE_INIT( Init ) {
Nan::Export( target, "add", node_add );
}
NODE_MODULE( addon, Init )
} // end namespace addon_strided_add
|
Use a bitmask to track scalar input arguments
|
Use a bitmask to track scalar input arguments
|
C++
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
255cc1087235c62244706169c8c2f11fd4fbedb1
|
KTp/Declarative/messages-model.cpp
|
KTp/Declarative/messages-model.cpp
|
/*
Copyright (C) 2011 Lasath Fernando <[email protected]>
Copyright (C) 2013 Lasath Fernando <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "messages-model.h"
#include <KDebug>
#include <KLocalizedString>
#include <TelepathyQt/ReceivedMessage>
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/Account>
#include <KTp/message-processor.h>
#include <KTp/message-context.h>
#include <KTp/Logger/scrollback-manager.h>
class MessagePrivate
{
public:
MessagePrivate(const KTp::Message &message);
KTp::Message message;
MessagesModel::DeliveryStatus deliveryStatus;
QDateTime deliveryReportReceiveTime;
};
MessagePrivate::MessagePrivate(const KTp::Message &message) :
message(message),
deliveryStatus(MessagesModel::DeliveryStatusUnknown)
{
}
class MessagesModel::MessagesModelPrivate
{
public:
Tp::TextChannelPtr textChannel;
Tp::AccountPtr account;
ScrollbackManager *logManager;
QList<MessagePrivate> messages;
// For fast lookup of original messages upon receipt of a message delivery report.
QHash<QString /*messageToken*/, QPersistentModelIndex> messagesByMessageToken;
bool visible;
};
MessagesModel::MessagesModel(const Tp::AccountPtr &account, QObject *parent) :
QAbstractListModel(parent),
d(new MessagesModelPrivate)
{
kDebug();
QHash<int, QByteArray> roles;
roles[TextRole] = "text";
roles[TimeRole] = "time";
roles[TypeRole] = "type";
roles[SenderIdRole] = "senderId";
roles[SenderAliasRole] = "senderAlias";
roles[SenderAvatarRole] = "senderAvatar";
roles[DeliveryStatusRole] = "deliveryStatus";
roles[DeliveryReportReceiveTimeRole] = "deliveryReportReceiveTime";
setRoleNames(roles);
d->account = account;
d->visible = false;
d->logManager = new ScrollbackManager(this);
connect(d->logManager, SIGNAL(fetched(QList<KTp::Message>)), SLOT(onHistoryFetched(QList<KTp::Message>)));
d->logManager->setScrollbackLength(10);
}
Tp::TextChannelPtr MessagesModel::textChannel() const
{
return d->textChannel;
}
bool MessagesModel::verifyPendingOperation(Tp::PendingOperation *op)
{
bool operationSucceeded = true;
if (op->isError()) {
kWarning() << op->errorName() << "+" << op->errorMessage();
operationSucceeded = false;
}
return operationSucceeded;
}
void MessagesModel::setupChannelSignals(const Tp::TextChannelPtr &channel)
{
connect(channel.data(),
SIGNAL(messageReceived(Tp::ReceivedMessage)),
SLOT(onMessageReceived(Tp::ReceivedMessage)));
connect(channel.data(),
SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)),
SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString)));
connect(channel.data(),
SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)),
SLOT(onPendingMessageRemoved()));
}
void MessagesModel::setTextChannel(const Tp::TextChannelPtr &channel)
{
Q_ASSERT(channel != d->textChannel);
kDebug();
setupChannelSignals(channel);
if (d->textChannel) {
removeChannelSignals(d->textChannel);
}
d->textChannel = channel;
d->logManager->setTextChannel(d->account, d->textChannel);
d->logManager->fetchScrollback();
QList<Tp::ReceivedMessage> messageQueue = channel->messageQueue();
Q_FOREACH(const Tp::ReceivedMessage &message, messageQueue) {
bool messageAlreadyInModel = false;
Q_FOREACH(const MessagePrivate ¤t, d->messages) {
//FIXME: docs say messageToken can return an empty string. What to do if that happens?
//Tp::Message has an == operator. maybe I can use that?
if (current.message.token() == message.messageToken()) {
messageAlreadyInModel = true;
break;
}
}
if (!messageAlreadyInModel) {
onMessageReceived(message);
}
}
}
void MessagesModel::onHistoryFetched(const QList<KTp::Message> &messages)
{
kDebug() << "found" << messages.count() << "messages in history";
if (!messages.isEmpty()) {
//Add all messages before the ones already present in the channel
for(int i=messages.size()-1;i>=0;i--) {
beginInsertRows(QModelIndex(), 0, 0);
d->messages.prepend(messages[i]);
endInsertRows();
}
}
}
void MessagesModel::onMessageReceived(const Tp::ReceivedMessage &message)
{
int unreadCount = d->textChannel->messageQueue().size();
kDebug() << "unreadMessagesCount =" << unreadCount;
kDebug() << "text =" << message.text();
kDebug() << "messageType = " << message.messageType();
kDebug() << "messageToken =" << message.messageToken();
if (message.isDeliveryReport()) {
d->textChannel->acknowledge(QList<Tp::ReceivedMessage>() << message);
Tp::ReceivedMessage::DeliveryDetails deliveryDetails = message.deliveryDetails();
if(!deliveryDetails.hasOriginalToken()) {
kDebug() << "Delivery report without original message token received.";
// Matching the delivery report to the original message is impossible without the token.
return;
}
kDebug() << "originalMessageToken =" << deliveryDetails.originalToken();
QPersistentModelIndex originalMessageIndex = d->messagesByMessageToken.value(
deliveryDetails.originalToken());
if (!originalMessageIndex.isValid() || originalMessageIndex.row() >= d->messages.count()) {
// The original message for this delivery report was not found.
return;
}
MessagePrivate &originalMessage = d->messages[originalMessageIndex.row()];
kDebug() << "Got delivery status" << deliveryDetails.status()
<< "for message with text" << originalMessage.message.mainMessagePart();
originalMessage.deliveryReportReceiveTime = message.received();
switch(deliveryDetails.status()) {
case Tp::DeliveryStatusPermanentlyFailed:
case Tp::DeliveryStatusTemporarilyFailed:
originalMessage.deliveryStatus = DeliveryStatusFailed;
if (deliveryDetails.hasDebugMessage()) {
kDebug() << "Delivery failure debug message:" << deliveryDetails.debugMessage();
}
break;
case Tp::DeliveryStatusDelivered:
originalMessage.deliveryStatus = DeliveryStatusDelivered;
break;
case Tp::DeliveryStatusRead:
originalMessage.deliveryStatus = DeliveryStatusRead;
break;
default:
originalMessage.deliveryStatus = DeliveryStatusUnknown;
break;
}
Q_EMIT dataChanged(originalMessageIndex, originalMessageIndex);
} else {
int length = rowCount();
beginInsertRows(QModelIndex(), length, length);
d->messages.append(KTp::MessageProcessor::instance()->processIncomingMessage(
message, d->account, d->textChannel));
endInsertRows();
if (d->visible) {
acknowledgeAllMessages();
} else {
Q_EMIT unreadCountChanged(unreadCount);
}
}
}
void MessagesModel::onMessageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &messageToken)
{
Q_UNUSED(flags);
int length = rowCount();
beginInsertRows(QModelIndex(), length, length);
kDebug() << "text =" << message.text();
const KTp::Message &newMessage = KTp::MessageProcessor::instance()->processIncomingMessage(
message, d->account, d->textChannel);
d->messages.append(newMessage);
if (!messageToken.isEmpty()) {
// Insert the message into the lookup table for delivery reports.
const QPersistentModelIndex &modelIndex(createIndex(length, 0));
d->messagesByMessageToken.insert(messageToken, modelIndex);
}
endInsertRows();
}
void MessagesModel::onPendingMessageRemoved()
{
Q_EMIT unreadCountChanged(unreadCount());
}
QVariant MessagesModel::data(const QModelIndex &index, int role) const
{
QVariant result;
if (index.isValid()) {
const MessagePrivate m = d->messages[index.row()];
switch (role) {
case TextRole:
result = m.message.finalizedMessage();
break;
case TypeRole:
if (m.message.type() == Tp::ChannelTextMessageTypeAction) {
result = MessageTypeAction;
} else {
if (m.message.direction() == KTp::Message::LocalToRemote) {
result = MessageTypeOutgoing;
} else {
result = MessageTypeIncoming;
}
}
break;
case TimeRole:
result = m.message.time();
break;
case SenderIdRole:
result = m.message.senderId();
break;
case SenderAliasRole:
result = m.message.senderAlias();
break;
case SenderAvatarRole:
if (m.message.sender()) {
result = QVariant::fromValue(m.message.sender()->avatarPixmap());
}
break;
case DeliveryStatusRole:
result = m.deliveryStatus;
break;
case DeliveryReportReceiveTimeRole:
result = m.deliveryReportReceiveTime;
break;
};
} else {
kError() << "Attempting to access data at invalid index (" << index << ")";
}
return result;
}
int MessagesModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return d->messages.size();
}
void MessagesModel::sendNewMessage(const QString &message)
{
if (message.isEmpty()) {
kWarning() << "Attempting to send empty string";
} else {
Tp::PendingOperation *op;
QString modifiedMessage = message;
if (d->textChannel->supportsMessageType(Tp::ChannelTextMessageTypeAction)
&& modifiedMessage.startsWith(QLatin1String("/me "))) {
//remove "/me " from the start of the message
modifiedMessage.remove(0,4);
op = d->textChannel->send(modifiedMessage, Tp::ChannelTextMessageTypeAction);
} else {
op = d->textChannel->send(modifiedMessage);
}
connect(op,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(verifyPendingOperation(Tp::PendingOperation*)));
}
}
void MessagesModel::removeChannelSignals(const Tp::TextChannelPtr &channel)
{
QObject::disconnect(channel.data(),
SIGNAL(messageReceived(Tp::ReceivedMessage)),
this,
SLOT(onMessageReceived(Tp::ReceivedMessage))
);
QObject::disconnect(channel.data(),
SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)),
this,
SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString))
);
}
int MessagesModel::unreadCount() const
{
return d->textChannel->messageQueue().size();
}
void MessagesModel::acknowledgeAllMessages()
{
QList<Tp::ReceivedMessage> queue = d->textChannel->messageQueue();
kDebug() << "Conversation Visible, Acknowledging " << queue.size() << " messages.";
d->textChannel->acknowledge(queue);
Q_EMIT unreadCountChanged(queue.size());
}
void MessagesModel::setVisibleToUser(bool visible)
{
kDebug() << visible;
if (d->visible != visible) {
d->visible = visible;
Q_EMIT visibleToUserChanged(d->visible);
}
if (visible) {
acknowledgeAllMessages();
}
}
bool MessagesModel::isVisibleToUser() const
{
return d->visible;
}
MessagesModel::~MessagesModel()
{
kDebug();
delete d;
}
bool MessagesModel::shouldStartOpened() const
{
return d->textChannel->isRequested();
}
|
/*
Copyright (C) 2011 Lasath Fernando <[email protected]>
Copyright (C) 2013 Lasath Fernando <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "messages-model.h"
#include <KDebug>
#include <KLocalizedString>
#include <TelepathyQt/ReceivedMessage>
#include <TelepathyQt/TextChannel>
#include <TelepathyQt/Account>
#include <KTp/message-processor.h>
#include <KTp/message-context.h>
#include <KTp/Logger/scrollback-manager.h>
class MessagePrivate
{
public:
MessagePrivate(const KTp::Message &message);
KTp::Message message;
MessagesModel::DeliveryStatus deliveryStatus;
QDateTime deliveryReportReceiveTime;
};
MessagePrivate::MessagePrivate(const KTp::Message &message) :
message(message),
deliveryStatus(MessagesModel::DeliveryStatusUnknown)
{
}
class MessagesModel::MessagesModelPrivate
{
public:
Tp::TextChannelPtr textChannel;
Tp::AccountPtr account;
ScrollbackManager *logManager;
QList<MessagePrivate> messages;
// For fast lookup of original messages upon receipt of a message delivery report.
QHash<QString /*messageToken*/, QPersistentModelIndex> messagesByMessageToken;
bool visible;
};
MessagesModel::MessagesModel(const Tp::AccountPtr &account, QObject *parent) :
QAbstractListModel(parent),
d(new MessagesModelPrivate)
{
kDebug();
QHash<int, QByteArray> roles;
roles[TextRole] = "text";
roles[TimeRole] = "time";
roles[TypeRole] = "type";
roles[SenderIdRole] = "senderId";
roles[SenderAliasRole] = "senderAlias";
roles[SenderAvatarRole] = "senderAvatar";
roles[DeliveryStatusRole] = "deliveryStatus";
roles[DeliveryReportReceiveTimeRole] = "deliveryReportReceiveTime";
setRoleNames(roles);
d->account = account;
d->visible = false;
d->logManager = new ScrollbackManager(this);
connect(d->logManager, SIGNAL(fetched(QList<KTp::Message>)), SLOT(onHistoryFetched(QList<KTp::Message>)));
//Load configuration for number of message to show
KConfig config(QLatin1String("ktelepathyrc"));
KConfigGroup tabConfig = config.group("Behavior");
d->logManager->setScrollbackLength(tabConfig.readEntry<int>("scrollbackLength", 10));
}
Tp::TextChannelPtr MessagesModel::textChannel() const
{
return d->textChannel;
}
bool MessagesModel::verifyPendingOperation(Tp::PendingOperation *op)
{
bool operationSucceeded = true;
if (op->isError()) {
kWarning() << op->errorName() << "+" << op->errorMessage();
operationSucceeded = false;
}
return operationSucceeded;
}
void MessagesModel::setupChannelSignals(const Tp::TextChannelPtr &channel)
{
connect(channel.data(),
SIGNAL(messageReceived(Tp::ReceivedMessage)),
SLOT(onMessageReceived(Tp::ReceivedMessage)));
connect(channel.data(),
SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)),
SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString)));
connect(channel.data(),
SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)),
SLOT(onPendingMessageRemoved()));
}
void MessagesModel::setTextChannel(const Tp::TextChannelPtr &channel)
{
Q_ASSERT(channel != d->textChannel);
kDebug();
setupChannelSignals(channel);
if (d->textChannel) {
removeChannelSignals(d->textChannel);
}
d->textChannel = channel;
d->logManager->setTextChannel(d->account, d->textChannel);
d->logManager->fetchScrollback();
QList<Tp::ReceivedMessage> messageQueue = channel->messageQueue();
Q_FOREACH(const Tp::ReceivedMessage &message, messageQueue) {
bool messageAlreadyInModel = false;
Q_FOREACH(const MessagePrivate ¤t, d->messages) {
//FIXME: docs say messageToken can return an empty string. What to do if that happens?
//Tp::Message has an == operator. maybe I can use that?
if (current.message.token() == message.messageToken()) {
messageAlreadyInModel = true;
break;
}
}
if (!messageAlreadyInModel) {
onMessageReceived(message);
}
}
}
void MessagesModel::onHistoryFetched(const QList<KTp::Message> &messages)
{
kDebug() << "found" << messages.count() << "messages in history";
if (!messages.isEmpty()) {
//Add all messages before the ones already present in the channel
for(int i=messages.size()-1;i>=0;i--) {
beginInsertRows(QModelIndex(), 0, 0);
d->messages.prepend(messages[i]);
endInsertRows();
}
}
}
void MessagesModel::onMessageReceived(const Tp::ReceivedMessage &message)
{
int unreadCount = d->textChannel->messageQueue().size();
kDebug() << "unreadMessagesCount =" << unreadCount;
kDebug() << "text =" << message.text();
kDebug() << "messageType = " << message.messageType();
kDebug() << "messageToken =" << message.messageToken();
if (message.isDeliveryReport()) {
d->textChannel->acknowledge(QList<Tp::ReceivedMessage>() << message);
Tp::ReceivedMessage::DeliveryDetails deliveryDetails = message.deliveryDetails();
if(!deliveryDetails.hasOriginalToken()) {
kDebug() << "Delivery report without original message token received.";
// Matching the delivery report to the original message is impossible without the token.
return;
}
kDebug() << "originalMessageToken =" << deliveryDetails.originalToken();
QPersistentModelIndex originalMessageIndex = d->messagesByMessageToken.value(
deliveryDetails.originalToken());
if (!originalMessageIndex.isValid() || originalMessageIndex.row() >= d->messages.count()) {
// The original message for this delivery report was not found.
return;
}
MessagePrivate &originalMessage = d->messages[originalMessageIndex.row()];
kDebug() << "Got delivery status" << deliveryDetails.status()
<< "for message with text" << originalMessage.message.mainMessagePart();
originalMessage.deliveryReportReceiveTime = message.received();
switch(deliveryDetails.status()) {
case Tp::DeliveryStatusPermanentlyFailed:
case Tp::DeliveryStatusTemporarilyFailed:
originalMessage.deliveryStatus = DeliveryStatusFailed;
if (deliveryDetails.hasDebugMessage()) {
kDebug() << "Delivery failure debug message:" << deliveryDetails.debugMessage();
}
break;
case Tp::DeliveryStatusDelivered:
originalMessage.deliveryStatus = DeliveryStatusDelivered;
break;
case Tp::DeliveryStatusRead:
originalMessage.deliveryStatus = DeliveryStatusRead;
break;
default:
originalMessage.deliveryStatus = DeliveryStatusUnknown;
break;
}
Q_EMIT dataChanged(originalMessageIndex, originalMessageIndex);
} else {
int length = rowCount();
beginInsertRows(QModelIndex(), length, length);
d->messages.append(KTp::MessageProcessor::instance()->processIncomingMessage(
message, d->account, d->textChannel));
endInsertRows();
if (d->visible) {
acknowledgeAllMessages();
} else {
Q_EMIT unreadCountChanged(unreadCount);
}
}
}
void MessagesModel::onMessageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &messageToken)
{
Q_UNUSED(flags);
int length = rowCount();
beginInsertRows(QModelIndex(), length, length);
kDebug() << "text =" << message.text();
const KTp::Message &newMessage = KTp::MessageProcessor::instance()->processIncomingMessage(
message, d->account, d->textChannel);
d->messages.append(newMessage);
if (!messageToken.isEmpty()) {
// Insert the message into the lookup table for delivery reports.
const QPersistentModelIndex &modelIndex(createIndex(length, 0));
d->messagesByMessageToken.insert(messageToken, modelIndex);
}
endInsertRows();
}
void MessagesModel::onPendingMessageRemoved()
{
Q_EMIT unreadCountChanged(unreadCount());
}
QVariant MessagesModel::data(const QModelIndex &index, int role) const
{
QVariant result;
if (index.isValid()) {
const MessagePrivate m = d->messages[index.row()];
switch (role) {
case TextRole:
result = m.message.finalizedMessage();
break;
case TypeRole:
if (m.message.type() == Tp::ChannelTextMessageTypeAction) {
result = MessageTypeAction;
} else {
if (m.message.direction() == KTp::Message::LocalToRemote) {
result = MessageTypeOutgoing;
} else {
result = MessageTypeIncoming;
}
}
break;
case TimeRole:
result = m.message.time();
break;
case SenderIdRole:
result = m.message.senderId();
break;
case SenderAliasRole:
result = m.message.senderAlias();
break;
case SenderAvatarRole:
if (m.message.sender()) {
result = QVariant::fromValue(m.message.sender()->avatarPixmap());
}
break;
case DeliveryStatusRole:
result = m.deliveryStatus;
break;
case DeliveryReportReceiveTimeRole:
result = m.deliveryReportReceiveTime;
break;
};
} else {
kError() << "Attempting to access data at invalid index (" << index << ")";
}
return result;
}
int MessagesModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return d->messages.size();
}
void MessagesModel::sendNewMessage(const QString &message)
{
if (message.isEmpty()) {
kWarning() << "Attempting to send empty string";
} else {
Tp::PendingOperation *op;
QString modifiedMessage = message;
if (d->textChannel->supportsMessageType(Tp::ChannelTextMessageTypeAction)
&& modifiedMessage.startsWith(QLatin1String("/me "))) {
//remove "/me " from the start of the message
modifiedMessage.remove(0,4);
op = d->textChannel->send(modifiedMessage, Tp::ChannelTextMessageTypeAction);
} else {
op = d->textChannel->send(modifiedMessage);
}
connect(op,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(verifyPendingOperation(Tp::PendingOperation*)));
}
}
void MessagesModel::removeChannelSignals(const Tp::TextChannelPtr &channel)
{
QObject::disconnect(channel.data(),
SIGNAL(messageReceived(Tp::ReceivedMessage)),
this,
SLOT(onMessageReceived(Tp::ReceivedMessage))
);
QObject::disconnect(channel.data(),
SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)),
this,
SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString))
);
}
int MessagesModel::unreadCount() const
{
return d->textChannel->messageQueue().size();
}
void MessagesModel::acknowledgeAllMessages()
{
QList<Tp::ReceivedMessage> queue = d->textChannel->messageQueue();
kDebug() << "Conversation Visible, Acknowledging " << queue.size() << " messages.";
d->textChannel->acknowledge(queue);
Q_EMIT unreadCountChanged(queue.size());
}
void MessagesModel::setVisibleToUser(bool visible)
{
kDebug() << visible;
if (d->visible != visible) {
d->visible = visible;
Q_EMIT visibleToUserChanged(d->visible);
}
if (visible) {
acknowledgeAllMessages();
}
}
bool MessagesModel::isVisibleToUser() const
{
return d->visible;
}
MessagesModel::~MessagesModel()
{
kDebug();
delete d;
}
bool MessagesModel::shouldStartOpened() const
{
return d->textChannel->isRequested();
}
|
Load scrollbacklength from config
|
Load scrollbacklength from config
|
C++
|
lgpl-2.1
|
leonhandreke/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals
|
cd8b6bcc5e246a6bff599033ddf390d4c480ebc9
|
webkit/glue/npruntime_util.cc
|
webkit/glue/npruntime_util.cc
|
// Copyright 2008, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "webkit/glue/npruntime_util.h"
// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "c_utility.h"
#endif
#include "base/pickle.h"
namespace webkit_glue {
bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
// If the identifier was null, then we just send a numeric 0. This is to
// support cases where the other end doesn't care about the NPIdentifier
// being serialized, so the bogus value of 0 is really inconsequential.
PrivateIdentifier null_id;
if (!priv) {
priv = &null_id;
priv->isString = false;
priv->value.number = 0;
}
if (!pickle->WriteBool(priv->isString))
return false;
if (priv->isString) {
// Write the null byte for efficiency on the other end.
return pickle->WriteData(
priv->value.string, strlen(priv->value.string) + 1);
}
return pickle->WriteInt(priv->value.number);
}
bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
NPIdentifier* identifier) {
bool is_string;
if (!pickle.ReadBool(pickle_iter, &is_string))
return false;
if (is_string) {
const char* data;
int data_len;
if (!pickle.ReadData(pickle_iter, &data, &data_len))
return false;
DCHECK_EQ(data_len, strlen(data) + 1);
*identifier = NPN_GetStringIdentifier(data);
} else {
int number;
if (!pickle.ReadInt(pickle_iter, &number))
return false;
*identifier = NPN_GetIntIdentifier(number);
}
return true;
}
} // namespace webkit_glue
|
// Copyright 2008, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#include "webkit/glue/npruntime_util.h"
// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "c/c_utility.h"
#endif
#include "base/pickle.h"
namespace webkit_glue {
bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
// If the identifier was null, then we just send a numeric 0. This is to
// support cases where the other end doesn't care about the NPIdentifier
// being serialized, so the bogus value of 0 is really inconsequential.
PrivateIdentifier null_id;
if (!priv) {
priv = &null_id;
priv->isString = false;
priv->value.number = 0;
}
if (!pickle->WriteBool(priv->isString))
return false;
if (priv->isString) {
// Write the null byte for efficiency on the other end.
return pickle->WriteData(
priv->value.string, strlen(priv->value.string) + 1);
}
return pickle->WriteInt(priv->value.number);
}
bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
NPIdentifier* identifier) {
bool is_string;
if (!pickle.ReadBool(pickle_iter, &is_string))
return false;
if (is_string) {
const char* data;
int data_len;
if (!pickle.ReadData(pickle_iter, &data, &data_len))
return false;
DCHECK_EQ(data_len, strlen(data) + 1);
*identifier = NPN_GetStringIdentifier(data);
} else {
int number;
if (!pickle.ReadInt(pickle_iter, &number))
return false;
*identifier = NPN_GetIntIdentifier(number);
}
return true;
}
} // namespace webkit_glue
|
fix kjs build
|
fix kjs build
git-svn-id: http://src.chromium.org/svn/trunk/src@447 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: d0befa79bdf4b9dead9564a9337f3e55a0375ca1
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
d66daf95417bbd9780c1a760b334984b57ad51a9
|
warpcoil/cpp/message_splitter.hpp
|
warpcoil/cpp/message_splitter.hpp
|
#pragma once
#include <array>
#include <silicium/exchange.hpp>
#include <warpcoil/protocol.hpp>
#include <warpcoil/cpp/begin_parse_value.hpp>
#include <warpcoil/cpp/tuple_parser.hpp>
#include <warpcoil/cpp/integer_parser.hpp>
#include <warpcoil/cpp/utf8_parser.hpp>
#include <iostream>
namespace warpcoil
{
namespace cpp
{
template <class AsyncReadStream>
struct buffered_read_stream
{
AsyncReadStream &input;
std::array<std::uint8_t, 512> buffer;
std::size_t buffer_used;
explicit buffered_read_stream(AsyncReadStream &input)
: input(input)
, buffer_used(0)
{
}
};
template <class AsyncReadStream>
struct message_splitter
{
explicit message_splitter(AsyncReadStream &input)
: buffer(input)
, locked(false)
, parsing_header(false)
{
}
template <class ResponseHandler>
void wait_for_response(ResponseHandler handler)
{
assert(!waiting_for_response);
waiting_for_response = [handler](boost::system::error_code const ec, request_id const request) mutable
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(
[&]
{
handler(ec, request);
},
&handler);
};
if (parsing_header)
{
return;
}
set_begin_parse_message(handler);
std::cerr << "begin_parse_message in wait_for_response\n";
begin_parse_message();
}
template <class RequestHandler>
void wait_for_request(RequestHandler handler)
{
assert(!waiting_for_request);
waiting_for_request = [handler](boost::system::error_code const ec, request_id const id,
std::string method) mutable
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(
[&]
{
handler(ec, id, std::move(method));
},
&handler);
};
if (parsing_header)
{
return;
}
set_begin_parse_message(handler);
std::cerr << "begin_parse_message in wait_for_request\n";
begin_parse_message();
}
buffered_read_stream<AsyncReadStream> &lock_input()
{
assert(!locked);
locked = true;
return buffer;
}
void unlock_input()
{
assert(locked);
locked = false;
if (!waiting_for_response && !waiting_for_request)
{
return;
}
std::cerr << "begin_parse_message after unlock_input\n";
begin_parse_message();
}
private:
buffered_read_stream<AsyncReadStream> buffer;
bool locked;
std::function<void()> begin_parse_message;
std::function<void(boost::system::error_code, request_id, std::string)> waiting_for_request;
std::function<void(boost::system::error_code, request_id)> waiting_for_response;
bool parsing_header;
template <class DummyHandler>
struct parse_message_type_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_message_type_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, message_type_int const type)
{
if (!!ec)
{
pipeline.on_error(ec);
return;
}
switch (static_cast<message_type>(type))
{
case message_type::response:
if (!pipeline.waiting_for_response)
{
pipeline.on_error(make_invalid_input_error());
return;
}
begin_parse_value(pipeline.buffer.input, boost::asio::buffer(pipeline.buffer.buffer),
pipeline.buffer.buffer_used, integer_parser<request_id>(),
parse_response_operation<DummyHandler>(pipeline, dummy));
break;
case message_type::request:
if (!pipeline.waiting_for_request)
{
pipeline.on_error(make_invalid_input_error());
return;
}
begin_parse_value(
pipeline.buffer.input, boost::asio::buffer(pipeline.buffer.buffer),
pipeline.buffer.buffer_used,
tuple_parser<integer_parser<request_id>, utf8_parser<integer_parser<std::uint8_t>>>(),
parse_request_operation<DummyHandler>(pipeline, dummy));
break;
default:
pipeline.on_error(make_invalid_input_error());
break;
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_message_type_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
template <class DummyHandler>
struct parse_request_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_request_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, std::tuple<request_id, std::string> request)
{
assert(pipeline.waiting_for_request);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
assert(pipeline.parsing_header);
pipeline.parsing_header = false;
bool const continue_ = pipeline.waiting_for_response != nullptr;
assert(pipeline.waiting_for_request);
Si::exchange(pipeline.waiting_for_request, nullptr)(ec, std::get<0>(request),
std::move(std::get<1>(request)));
if (continue_ && pipeline.waiting_for_response && !pipeline.parsing_header)
{
std::cerr << "begin_parse_message after request\n";
pipeline.begin_parse_message();
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_request_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
template <class DummyHandler>
struct parse_response_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_response_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, request_id const request)
{
assert(pipeline.waiting_for_response);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
assert(pipeline.parsing_header);
pipeline.parsing_header = false;
bool const continue_ = pipeline.waiting_for_request != nullptr;
assert(pipeline.waiting_for_response);
Si::exchange(pipeline.waiting_for_response, nullptr)(ec, request);
if (continue_ && pipeline.waiting_for_request && !pipeline.parsing_header)
{
std::cerr << "begin_parse_message after response\n";
pipeline.begin_parse_message();
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_response_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
void on_error(boost::system::error_code const ec)
{
bool const is_waiting_for_request = waiting_for_request != nullptr;
if (waiting_for_response)
{
Si::exchange(waiting_for_response, nullptr)(ec, 0);
}
//"this" might be destroyed at this point if "waiting_for_request" was empty, so we cannot dereference
//"this" here.
if (is_waiting_for_request)
{
Si::exchange(waiting_for_request, nullptr)(ec, 0, "");
}
}
template <class DummyHandler>
void set_begin_parse_message(DummyHandler &handler)
{
begin_parse_message = [this, handler]()
{
assert(!parsing_header);
assert(waiting_for_response || waiting_for_request);
if (locked)
{
return;
}
parsing_header = true;
begin_parse_value(buffer.input, boost::asio::buffer(buffer.buffer), buffer.buffer_used,
integer_parser<message_type_int>(),
parse_message_type_operation<DummyHandler>(*this, handler));
};
}
};
}
}
|
#pragma once
#include <array>
#include <silicium/exchange.hpp>
#include <warpcoil/protocol.hpp>
#include <warpcoil/cpp/begin_parse_value.hpp>
#include <warpcoil/cpp/tuple_parser.hpp>
#include <warpcoil/cpp/integer_parser.hpp>
#include <warpcoil/cpp/utf8_parser.hpp>
#include <iostream>
namespace warpcoil
{
namespace cpp
{
template <class AsyncReadStream>
struct buffered_read_stream
{
AsyncReadStream &input;
std::array<std::uint8_t, 512> buffer;
std::size_t buffer_used;
explicit buffered_read_stream(AsyncReadStream &input)
: input(input)
, buffer_used(0)
{
}
};
template <class AsyncReadStream>
struct message_splitter
{
explicit message_splitter(AsyncReadStream &input)
: buffer(input)
, locked(false)
, parsing_header(false)
{
}
template <class ResponseHandler>
void wait_for_response(ResponseHandler handler)
{
assert(!waiting_for_response);
waiting_for_response = [handler](boost::system::error_code const ec, request_id const request) mutable
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(
[&]
{
handler(ec, request);
},
&handler);
};
if (parsing_header)
{
return;
}
set_begin_parse_message(handler);
std::cerr << "begin_parse_message in wait_for_response\n";
begin_parse_message();
}
template <class RequestHandler>
void wait_for_request(RequestHandler handler)
{
assert(!waiting_for_request);
waiting_for_request = [handler](boost::system::error_code const ec, request_id const id,
std::string method) mutable
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(
[&]
{
handler(ec, id, std::move(method));
},
&handler);
};
if (parsing_header)
{
return;
}
set_begin_parse_message(handler);
std::cerr << "begin_parse_message in wait_for_request\n";
begin_parse_message();
}
buffered_read_stream<AsyncReadStream> &lock_input()
{
assert(!parsing_header);
assert(!locked);
locked = true;
return buffer;
}
void unlock_input()
{
assert(!parsing_header);
assert(locked);
locked = false;
if (!waiting_for_response && !waiting_for_request)
{
return;
}
std::cerr << "begin_parse_message after unlock_input\n";
begin_parse_message();
}
private:
buffered_read_stream<AsyncReadStream> buffer;
bool locked;
std::function<void()> begin_parse_message;
std::function<void(boost::system::error_code, request_id, std::string)> waiting_for_request;
std::function<void(boost::system::error_code, request_id)> waiting_for_response;
bool parsing_header;
template <class DummyHandler>
struct parse_message_type_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_message_type_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, message_type_int const type)
{
if (!!ec)
{
pipeline.on_error(ec);
return;
}
switch (static_cast<message_type>(type))
{
case message_type::response:
if (!pipeline.waiting_for_response)
{
pipeline.on_error(make_invalid_input_error());
return;
}
begin_parse_value(pipeline.buffer.input, boost::asio::buffer(pipeline.buffer.buffer),
pipeline.buffer.buffer_used, integer_parser<request_id>(),
parse_response_operation<DummyHandler>(pipeline, dummy));
break;
case message_type::request:
if (!pipeline.waiting_for_request)
{
pipeline.on_error(make_invalid_input_error());
return;
}
begin_parse_value(
pipeline.buffer.input, boost::asio::buffer(pipeline.buffer.buffer),
pipeline.buffer.buffer_used,
tuple_parser<integer_parser<request_id>, utf8_parser<integer_parser<std::uint8_t>>>(),
parse_request_operation<DummyHandler>(pipeline, dummy));
break;
default:
pipeline.on_error(make_invalid_input_error());
break;
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_message_type_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
template <class DummyHandler>
struct parse_request_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_request_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, std::tuple<request_id, std::string> request)
{
assert(pipeline.waiting_for_request);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
assert(pipeline.parsing_header);
pipeline.parsing_header = false;
bool const continue_ = pipeline.waiting_for_response != nullptr;
assert(pipeline.waiting_for_request);
Si::exchange(pipeline.waiting_for_request, nullptr)(ec, std::get<0>(request),
std::move(std::get<1>(request)));
if (continue_ && pipeline.waiting_for_response && !pipeline.parsing_header)
{
std::cerr << "begin_parse_message after request\n";
pipeline.begin_parse_message();
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_request_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
template <class DummyHandler>
struct parse_response_operation
{
message_splitter &pipeline;
DummyHandler dummy;
explicit parse_response_operation(message_splitter &pipeline, DummyHandler dummy)
: pipeline(pipeline)
, dummy(std::move(dummy))
{
}
void operator()(boost::system::error_code const ec, request_id const request)
{
assert(pipeline.waiting_for_response);
if (!!ec)
{
pipeline.on_error(ec);
return;
}
assert(pipeline.parsing_header);
pipeline.parsing_header = false;
bool const continue_ = pipeline.waiting_for_request != nullptr;
assert(pipeline.waiting_for_response);
Si::exchange(pipeline.waiting_for_response, nullptr)(ec, request);
if (continue_ && pipeline.waiting_for_request && !pipeline.parsing_header)
{
std::cerr << "begin_parse_message after response\n";
pipeline.begin_parse_message();
}
}
template <class Function>
friend void asio_handler_invoke(Function &&f, parse_response_operation *operation)
{
using boost::asio::asio_handler_invoke;
asio_handler_invoke(f, &operation->dummy);
}
};
void on_error(boost::system::error_code const ec)
{
bool const is_waiting_for_request = waiting_for_request != nullptr;
if (waiting_for_response)
{
Si::exchange(waiting_for_response, nullptr)(ec, 0);
}
//"this" might be destroyed at this point if "waiting_for_request" was empty, so we cannot dereference
//"this" here.
if (is_waiting_for_request)
{
Si::exchange(waiting_for_request, nullptr)(ec, 0, "");
}
}
template <class DummyHandler>
void set_begin_parse_message(DummyHandler &handler)
{
begin_parse_message = [this, handler]()
{
assert(!parsing_header);
assert(waiting_for_response || waiting_for_request);
if (locked)
{
return;
}
parsing_header = true;
begin_parse_value(buffer.input, boost::asio::buffer(buffer.buffer), buffer.buffer_used,
integer_parser<message_type_int>(),
parse_message_type_operation<DummyHandler>(*this, handler));
};
}
};
}
}
|
add assertions to message_splitter
|
add assertions to message_splitter
|
C++
|
mit
|
TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil,TyRoXx/warpcoil
|
7fd2b183dc0f6b952d40724e7057dcad902ad6c6
|
searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp
|
searchlib/src/vespa/searchlib/queryeval/nearest_neighbor_blueprint.cpp
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "emptysearch.h"
#include "nearest_neighbor_blueprint.h"
#include "nearest_neighbor_iterator.h"
#include "nns_index_iterator.h"
#include <vespa/eval/eval/dense_cells_value.h>
#include <vespa/searchlib/fef/termfieldmatchdataarray.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/searchlib/tensor/distance_function_factory.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.queryeval.nearest_neighbor_blueprint");
using vespalib::eval::DenseCellsValue;
using vespalib::eval::Value;
namespace search::queryeval {
namespace {
template<typename LCT, typename RCT>
void
convert_cells(std::unique_ptr<Value> &original, const vespalib::eval::ValueType &want_type)
{
auto old_cells = original->cells().typify<LCT>();
std::vector<RCT> new_cells;
new_cells.reserve(old_cells.size());
for (LCT value : old_cells) {
RCT conv = value;
new_cells.push_back(conv);
}
original = std::make_unique<DenseCellsValue<RCT>>(want_type, std::move(new_cells));
}
template<>
void
convert_cells<float,float>(std::unique_ptr<Value> &, const vespalib::eval::ValueType &) {}
template<>
void
convert_cells<double,double>(std::unique_ptr<Value> &, const vespalib::eval::ValueType &) {}
struct ConvertCellsSelector
{
template <typename LCT, typename RCT>
static auto invoke() { return convert_cells<LCT, RCT>; }
};
} // namespace <unnamed>
NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& field,
const tensor::DenseTensorAttribute& attr_tensor,
std::unique_ptr<Value> query_tensor,
uint32_t target_num_hits, bool approximate, uint32_t explore_additional_hits,
double distance_threshold, double brute_force_limit)
: ComplexLeafBlueprint(field),
_attr_tensor(attr_tensor),
_query_tensor(std::move(query_tensor)),
_target_num_hits(target_num_hits),
_approximate(approximate),
_explore_additional_hits(explore_additional_hits),
_distance_threshold(std::numeric_limits<double>::max()),
_brute_force_limit(brute_force_limit),
_fallback_dist_fun(),
_distance_heap(target_num_hits),
_found_hits(),
_global_filter(GlobalFilter::create())
{
auto lct = _query_tensor->cells().type;
auto rct = _attr_tensor.getTensorType().cell_type();
using MyTypify = vespalib::eval::TypifyCellType;
auto fixup_fun = vespalib::typify_invoke<2,MyTypify,ConvertCellsSelector>(lct, rct);
fixup_fun(_query_tensor, _attr_tensor.getTensorType());
_fallback_dist_fun = search::tensor::make_distance_function(_attr_tensor.getConfig().distance_metric(), rct);
_dist_fun = _fallback_dist_fun.get();
assert(_dist_fun);
auto nns_index = _attr_tensor.nearest_neighbor_index();
if (nns_index) {
_dist_fun = nns_index->distance_function();
assert(_dist_fun);
}
if (distance_threshold < std::numeric_limits<double>::max()) {
_distance_threshold = _dist_fun->convert_threshold(distance_threshold);
_distance_heap.set_distance_threshold(_distance_threshold);
}
uint32_t est_hits = _attr_tensor.getNumDocs();
setEstimate(HitEstimate(est_hits, false));
set_want_global_filter(true);
}
NearestNeighborBlueprint::~NearestNeighborBlueprint() = default;
void
NearestNeighborBlueprint::set_global_filter(const GlobalFilter &global_filter)
{
_global_filter = global_filter.shared_from_this();
auto nns_index = _attr_tensor.nearest_neighbor_index();
LOG(debug, "set_global_filter with: %s / %s / %s",
(_approximate ? "approximate" : "exact"),
(nns_index ? "nns_index" : "no_index"),
(_global_filter->has_filter() ? "has_filter" : "no_filter"));
if (_approximate && nns_index) {
uint32_t est_hits = _attr_tensor.getNumDocs();
if (_global_filter->has_filter()) {
uint32_t max_hits = _global_filter->filter()->countTrueBits();
LOG(debug, "set_global_filter getNumDocs: %u / max_hits %u", est_hits, max_hits);
double max_hit_ratio = static_cast<double>(max_hits) / est_hits;
if (max_hit_ratio < _brute_force_limit) {
_approximate = false;
LOG(debug, "too many hits filtered out, using brute force implementation");
} else {
est_hits = std::min(est_hits, max_hits);
}
}
if (_approximate) {
est_hits = std::min(est_hits, _target_num_hits);
setEstimate(HitEstimate(est_hits, false));
perform_top_k();
LOG(debug, "perform_top_k found %zu hits", _found_hits.size());
}
}
}
void
NearestNeighborBlueprint::perform_top_k()
{
auto nns_index = _attr_tensor.nearest_neighbor_index();
if (_approximate && nns_index) {
auto lhs_type = _query_tensor->type();
auto rhs_type = _attr_tensor.getTensorType();
// different cell types should be converted already
if (lhs_type == rhs_type) {
auto lhs = _query_tensor->cells();
uint32_t k = _target_num_hits;
if (_global_filter->has_filter()) {
auto filter = _global_filter->filter();
_found_hits = nns_index->find_top_k_with_filter(k, lhs, *filter, k + _explore_additional_hits, _distance_threshold);
} else {
_found_hits = nns_index->find_top_k(k, lhs, k + _explore_additional_hits, _distance_threshold);
}
}
}
}
std::unique_ptr<SearchIterator>
NearestNeighborBlueprint::createLeafSearch(const search::fef::TermFieldMatchDataArray& tfmda, bool strict) const
{
assert(tfmda.size() == 1);
fef::TermFieldMatchData &tfmd = *tfmda[0]; // always search in only one field
if (! _found_hits.empty()) {
return NnsIndexIterator::create(tfmd, _found_hits, _dist_fun);
}
const Value &qT = *_query_tensor;
return NearestNeighborIterator::create(strict, tfmd, qT, _attr_tensor,
_distance_heap, _global_filter->filter(), _dist_fun);
}
void
NearestNeighborBlueprint::visitMembers(vespalib::ObjectVisitor& visitor) const
{
ComplexLeafBlueprint::visitMembers(visitor);
visitor.visitString("attribute_tensor", _attr_tensor.getTensorType().to_spec());
visitor.visitString("query_tensor", _query_tensor->type().to_spec());
visitor.visitInt("target_num_hits", _target_num_hits);
visitor.visitBool("approximate", _approximate);
visitor.visitInt("explore_additional_hits", _explore_additional_hits);
}
bool
NearestNeighborBlueprint::always_needs_unpack() const
{
return true;
}
}
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "emptysearch.h"
#include "nearest_neighbor_blueprint.h"
#include "nearest_neighbor_iterator.h"
#include "nns_index_iterator.h"
#include <vespa/eval/eval/dense_cells_value.h>
#include <vespa/searchlib/fef/termfieldmatchdataarray.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/searchlib/tensor/distance_function_factory.h>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.queryeval.nearest_neighbor_blueprint");
using vespalib::eval::DenseCellsValue;
using vespalib::eval::Value;
namespace search::queryeval {
namespace {
template<typename LCT, typename RCT>
void
convert_cells(std::unique_ptr<Value> &original, const vespalib::eval::ValueType &want_type)
{
if constexpr (std::is_same<LCT,RCT>::value) {
return;
} else {
auto old_cells = original->cells().typify<LCT>();
std::vector<RCT> new_cells;
new_cells.reserve(old_cells.size());
for (LCT value : old_cells) {
RCT conv(value);
new_cells.push_back(conv);
}
original = std::make_unique<DenseCellsValue<RCT>>(want_type, std::move(new_cells));
}
}
struct ConvertCellsSelector
{
template <typename LCT, typename RCT>
static auto invoke() { return convert_cells<LCT, RCT>; }
};
} // namespace <unnamed>
NearestNeighborBlueprint::NearestNeighborBlueprint(const queryeval::FieldSpec& field,
const tensor::DenseTensorAttribute& attr_tensor,
std::unique_ptr<Value> query_tensor,
uint32_t target_num_hits, bool approximate, uint32_t explore_additional_hits,
double distance_threshold, double brute_force_limit)
: ComplexLeafBlueprint(field),
_attr_tensor(attr_tensor),
_query_tensor(std::move(query_tensor)),
_target_num_hits(target_num_hits),
_approximate(approximate),
_explore_additional_hits(explore_additional_hits),
_distance_threshold(std::numeric_limits<double>::max()),
_brute_force_limit(brute_force_limit),
_fallback_dist_fun(),
_distance_heap(target_num_hits),
_found_hits(),
_global_filter(GlobalFilter::create())
{
auto lct = _query_tensor->cells().type;
auto rct = _attr_tensor.getTensorType().cell_type();
using MyTypify = vespalib::eval::TypifyCellType;
auto fixup_fun = vespalib::typify_invoke<2,MyTypify,ConvertCellsSelector>(lct, rct);
fixup_fun(_query_tensor, _attr_tensor.getTensorType());
_fallback_dist_fun = search::tensor::make_distance_function(_attr_tensor.getConfig().distance_metric(), rct);
_dist_fun = _fallback_dist_fun.get();
assert(_dist_fun);
auto nns_index = _attr_tensor.nearest_neighbor_index();
if (nns_index) {
_dist_fun = nns_index->distance_function();
assert(_dist_fun);
}
if (distance_threshold < std::numeric_limits<double>::max()) {
_distance_threshold = _dist_fun->convert_threshold(distance_threshold);
_distance_heap.set_distance_threshold(_distance_threshold);
}
uint32_t est_hits = _attr_tensor.getNumDocs();
setEstimate(HitEstimate(est_hits, false));
set_want_global_filter(true);
}
NearestNeighborBlueprint::~NearestNeighborBlueprint() = default;
void
NearestNeighborBlueprint::set_global_filter(const GlobalFilter &global_filter)
{
_global_filter = global_filter.shared_from_this();
auto nns_index = _attr_tensor.nearest_neighbor_index();
LOG(debug, "set_global_filter with: %s / %s / %s",
(_approximate ? "approximate" : "exact"),
(nns_index ? "nns_index" : "no_index"),
(_global_filter->has_filter() ? "has_filter" : "no_filter"));
if (_approximate && nns_index) {
uint32_t est_hits = _attr_tensor.getNumDocs();
if (_global_filter->has_filter()) {
uint32_t max_hits = _global_filter->filter()->countTrueBits();
LOG(debug, "set_global_filter getNumDocs: %u / max_hits %u", est_hits, max_hits);
double max_hit_ratio = static_cast<double>(max_hits) / est_hits;
if (max_hit_ratio < _brute_force_limit) {
_approximate = false;
LOG(debug, "too many hits filtered out, using brute force implementation");
} else {
est_hits = std::min(est_hits, max_hits);
}
}
if (_approximate) {
est_hits = std::min(est_hits, _target_num_hits);
setEstimate(HitEstimate(est_hits, false));
perform_top_k();
LOG(debug, "perform_top_k found %zu hits", _found_hits.size());
}
}
}
void
NearestNeighborBlueprint::perform_top_k()
{
auto nns_index = _attr_tensor.nearest_neighbor_index();
if (_approximate && nns_index) {
auto lhs_type = _query_tensor->type();
auto rhs_type = _attr_tensor.getTensorType();
// different cell types should be converted already
if (lhs_type == rhs_type) {
auto lhs = _query_tensor->cells();
uint32_t k = _target_num_hits;
if (_global_filter->has_filter()) {
auto filter = _global_filter->filter();
_found_hits = nns_index->find_top_k_with_filter(k, lhs, *filter, k + _explore_additional_hits, _distance_threshold);
} else {
_found_hits = nns_index->find_top_k(k, lhs, k + _explore_additional_hits, _distance_threshold);
}
}
}
}
std::unique_ptr<SearchIterator>
NearestNeighborBlueprint::createLeafSearch(const search::fef::TermFieldMatchDataArray& tfmda, bool strict) const
{
assert(tfmda.size() == 1);
fef::TermFieldMatchData &tfmd = *tfmda[0]; // always search in only one field
if (! _found_hits.empty()) {
return NnsIndexIterator::create(tfmd, _found_hits, _dist_fun);
}
const Value &qT = *_query_tensor;
return NearestNeighborIterator::create(strict, tfmd, qT, _attr_tensor,
_distance_heap, _global_filter->filter(), _dist_fun);
}
void
NearestNeighborBlueprint::visitMembers(vespalib::ObjectVisitor& visitor) const
{
ComplexLeafBlueprint::visitMembers(visitor);
visitor.visitString("attribute_tensor", _attr_tensor.getTensorType().to_spec());
visitor.visitString("query_tensor", _query_tensor->type().to_spec());
visitor.visitInt("target_num_hits", _target_num_hits);
visitor.visitBool("approximate", _approximate);
visitor.visitInt("explore_additional_hits", _explore_additional_hits);
}
bool
NearestNeighborBlueprint::always_needs_unpack() const
{
return true;
}
}
|
handle more cell types
|
handle more cell types
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
2cfdd83c8c803015bbfc46db965ca5c2b2d62db6
|
tests/compositeTransformation.cpp
|
tests/compositeTransformation.cpp
|
#include <CompositeTransformation.h>
namespace test {
using namespace std;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
struct CompositeTransformSuite : public ::testing::Test {
struct TestTransformer : public Transformer {
TestTransformer() : Transformer(Transformation::invalid, EventType(), {EventType()}) {}
MOCK_CONST_METHOD1(check, bool(const Events&));
MOCK_METHOD1(call, MetaEvent(const Events&));
virtual MetaEvent operator()(const Events& events) { return call(events); }
MOCK_CONST_METHOD1(print, void(std::ostream&));
};
struct TestTransformation : public Transformation {
TestTransformation() : Transformation(Type::attribute, 1, EventID::any) { }
MOCK_CONST_METHOD1(in, EventTypes(const EventType& goal));
MOCK_CONST_METHOD2(in, EventTypes(const EventType& goal, const EventType& provided));
MOCK_CONST_METHOD1(in, EventIDs(EventID goal));
MOCK_CONST_METHOD2(create, TransPtr(const EventType& out, const EventTypes& in));
MOCK_CONST_METHOD1(print, void(ostream& o));
};
TestTransformation a, e, f;
TestTransformer c, d, g;
CompositeTransformation compTrans, compTrans2;
shared_ptr<const Transformation> bPtr;
const TestTransformation* b=nullptr;
EventType goal, provided, provided2, intermediate, intermediate2;
struct Test0: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 251; }
};
struct Test1: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 252; }
};
void SetUp() {
ValueType goalVT(id::type::Float::value(), 1, 1, false);
AttributeType goalAT(Test0::value(), goalVT, Scale<>(), Dimensionless());
AttributeType int2AT(Test1::value(), goalVT, Scale<std::ratio<1, 1000>>(), Dimensionless());
AttributeType intAT = goalAT;
AttributeType provAT = intAT;
AttributeType prov2AT = int2AT;
intAT.scale().denom(1000);
provAT.scale().denom(1000);
provAT.value().typeId(id::type::Int64::value());
prov2AT.value().typeId(id::type::Int64::value());
goal.add(goalAT);
intermediate.add(intAT);
provided.add(provAT);
intermediate2.add(int2AT);
provided2.add(prov2AT);
bPtr.reset(new TestTransformation());
b=dynamic_cast<const TestTransformation*>(bPtr.get());
ASSERT_NE(b, nullptr);
EXPECT_CALL(a, in(goal, provided))
.Times(1).WillOnce(Return(EventTypes({intermediate})));
EXPECT_CALL(*b, in(intermediate, provided))
.Times(AtLeast(1)).WillRepeatedly(Return(EventTypes({provided})));
EXPECT_CALL(e, in(goal))
.Times(1).WillOnce(Return(EventTypes({intermediate, intermediate2})));
EXPECT_CALL(f, in(intermediate2, provided2))
.Times(1).WillOnce(Return(EventTypes({provided2})));
auto r0 = compTrans.addRootTransformation(TransformationPtr(&a), goal, provided);
ASSERT_TRUE(r0.second);
auto r1 = compTrans.addTransformation(b, r0.first, intermediate, provided);
ASSERT_TRUE(r1.second);
auto r2 = compTrans2.addRootTransformation(TransformationPtr(&e), goal, EventType());
ASSERT_TRUE(r2.second);
auto r3 = compTrans2.addTransformation(b, r2.first, intermediate, provided);
ASSERT_TRUE(r3.second);
auto r4 = compTrans2.addTransformation(TransformationPtr(&f), r2.first, intermediate2, provided2);
ASSERT_TRUE(r4.second);
}
};
TEST_F(CompositeTransformSuite, linearTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans.graph();
ASSERT_EQ(boost::num_vertices(g), 2U);
auto v = boost::vertices(g);
Vertex testAV = *v.first;
const Transformation& testA = *g[testAV].trans();
EXPECT_EQ(testA, a);
auto out = out_edges(testAV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
}
TEST_F(CompositeTransformSuite, linearInTest) {
auto result = compTrans.in();
EXPECT_EQ(result, EventTypes({provided}));
}
TEST_F(CompositeTransformSuite, treeTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans2.graph();
ASSERT_EQ(boost::num_vertices(g), 3U);
auto v = boost::vertices(g);
Vertex testEV = *v.first;
const Transformation& testE = *g[testEV].trans();
EXPECT_EQ(testE, e);
auto out = out_edges(testEV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
Edge testFE = *++out.first;
Vertex testFV = target(testFE, g);
const Transformation& testF = *g[testFV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testF, f);
}
TEST_F(CompositeTransformSuite, treeInTest) {
auto result = compTrans2.in();
ASSERT_FALSE(result.empty());
EXPECT_EQ(result, EventTypes({provided, provided2}));
}
TEST_F(CompositeTransformSuite, linearCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(a, create(goal, EventTypes({intermediate})))
.Times(1).WillOnce(Return(TransPtr(&c, [](const Transformer*){})));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided})))
.Times(1).WillOnce(Return(TransPtr(&d, [](const Transformer*){})));
TransPtr result = compTrans.create();
ASSERT_NE(result, nullptr);
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.1f});
MetaEvent eB(intermediate);
eB.attribute(Test0::value())->value().set(0, 0, {1100.0f});
MetaEvent eC(goal);
eC.attribute(Test0::value())->value().set(0, 0, {1100});
EXPECT_CALL(c, call(Events({&eA})))
.Times(1).WillOnce(Return(eB));
EXPECT_CALL(d, call(Events{&eB}))
.Times(1).WillOnce(Return(eC));
EXPECT_EQ((*result)(Events({&eA})), eC);
}
TEST_F(CompositeTransformSuite, treeCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(e, create(goal, EventTypes({intermediate})))
.Times(1).WillOnce(Return(TransPtr(&c, [](const Transformer*){})));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided})))
.Times(1).WillOnce(Return(TransPtr(&d, [](const Transformer*){})));
EXPECT_CALL(f, create(intermediate, EventTypes({provided})))
.Times(1).WillOnce(Return(TransPtr(&g, [](const Transformer*){})));
TransPtr result = compTrans.create();
ASSERT_NE(result, nullptr);
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.0f});
MetaEvent eB(provided2);
eA.attribute(Test1::value())->value().set(0, 0, {2.0f});
MetaEvent eC(intermediate);
eB.attribute(Test0::value())->value().set(0, 0, {3.0f});
MetaEvent eD(intermediate2);
eB.attribute(Test1::value())->value().set(0, 0, {4.0f});
MetaEvent eE(goal);
eC.attribute(Test0::value())->value().set(0, 0, {5.0f});
EXPECT_CALL(c, call(Events({&eA})))
.Times(1).WillOnce(Return(eC));
EXPECT_CALL(d, call(Events({&eB})))
.Times(1).WillOnce(Return(eD));
EXPECT_CALL(g, call(Events({&eC, &eD})))
.Times(1).WillOnce(Return(eE));
EXPECT_EQ((*result)(Events({&eA, &eB})), eE);
}
}
|
#include <CompositeTransformation.h>
namespace test {
using namespace std;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
struct CompositeTransformSuite : public ::testing::Test {
struct TestTransformer : public Transformer {
TestTransformer() : Transformer(Transformation::invalid, EventType(), {EventType()}) {}
MOCK_CONST_METHOD1(check, bool(const Events&));
MOCK_METHOD1(call, MetaEvent(const Events&));
virtual MetaEvent operator()(const Events& events) { return call(events); }
MOCK_CONST_METHOD1(print, void(std::ostream&));
};
struct TestTransformation : public Transformation {
TestTransformation() : Transformation(Type::attribute, 1, EventID::any) { }
MOCK_CONST_METHOD1(in, EventTypes(const EventType& goal));
MOCK_CONST_METHOD2(in, EventTypes(const EventType& goal, const EventType& provided));
MOCK_CONST_METHOD1(in, EventIDs(EventID goal));
MOCK_CONST_METHOD2(create, TransPtr(const EventType& out, const EventTypes& in));
MOCK_CONST_METHOD1(print, void(ostream& o));
};
TestTransformation a, e, f;
TestTransformer c, d, g;
CompositeTransformation compTrans, compTrans2;
shared_ptr<const Transformation> bPtr;
const TestTransformation* b=nullptr;
EventType goal, provided, provided2, intermediate, intermediate2;
struct Test0: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 251; }
};
struct Test1: public ::id::attribute::Base {
static constexpr const ::id::attribute::ID value() { return 252; }
};
void SetUp() {
ValueType goalVT(id::type::Float::value(), 1, 1, false);
AttributeType goalAT(Test0::value(), goalVT, Scale<>(), Dimensionless());
AttributeType int2AT(Test1::value(), goalVT, Scale<std::ratio<1, 1000>>(), Dimensionless());
AttributeType intAT = goalAT;
AttributeType provAT = intAT;
AttributeType prov2AT = int2AT;
intAT.scale().denom(1000);
provAT.scale().denom(1000);
provAT.value().typeId(id::type::Int64::value());
prov2AT.value().typeId(id::type::Int64::value());
goal.add(goalAT);
intermediate.add(intAT);
provided.add(provAT);
intermediate2.add(int2AT);
provided2.add(prov2AT);
bPtr.reset(new TestTransformation());
b=dynamic_cast<const TestTransformation*>(bPtr.get());
ASSERT_NE(b, nullptr);
EXPECT_CALL(a, in(goal, provided))
.Times(1).WillOnce(Return(EventTypes({intermediate})));
EXPECT_CALL(*b, in(intermediate, provided))
.Times(AtLeast(1)).WillRepeatedly(Return(EventTypes({provided})));
EXPECT_CALL(e, in(goal))
.Times(1).WillOnce(Return(EventTypes({intermediate, intermediate2})));
EXPECT_CALL(f, in(intermediate2, provided2))
.Times(1).WillOnce(Return(EventTypes({provided2})));
auto r0 = compTrans.addRootTransformation(TransformationPtr(&a), goal, provided);
ASSERT_TRUE(r0.second);
auto r1 = compTrans.addTransformation(b, r0.first, intermediate, provided);
ASSERT_TRUE(r1.second);
auto r2 = compTrans2.addRootTransformation(TransformationPtr(&e), goal, EventType());
ASSERT_TRUE(r2.second);
auto r3 = compTrans2.addTransformation(b, r2.first, intermediate, provided);
ASSERT_TRUE(r3.second);
auto r4 = compTrans2.addTransformation(TransformationPtr(&f), r2.first, intermediate2, provided2);
ASSERT_TRUE(r4.second);
}
};
TEST_F(CompositeTransformSuite, linearTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans.graph();
ASSERT_EQ(boost::num_vertices(g), 2U);
auto v = boost::vertices(g);
Vertex testAV = *v.first;
const Transformation& testA = *g[testAV].trans();
EXPECT_EQ(testA, a);
auto out = out_edges(testAV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
}
TEST_F(CompositeTransformSuite, linearInTest) {
auto result = compTrans.in();
EXPECT_EQ(result, EventTypes({provided}));
}
TEST_F(CompositeTransformSuite, treeTest) {
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using Edge = Graph::edge_descriptor;
const Graph& g = compTrans2.graph();
ASSERT_EQ(boost::num_vertices(g), 3U);
auto v = boost::vertices(g);
Vertex testEV = *v.first;
const Transformation& testE = *g[testEV].trans();
EXPECT_EQ(testE, e);
auto out = out_edges(testEV, g);
ASSERT_NE(out.first, out.second);
Edge testBE = *out.first;
Vertex testBV = target(testBE, g);
const Transformation& testB = *g[testBV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testB, *b);
Edge testFE = *++out.first;
Vertex testFV = target(testFE, g);
const Transformation& testF = *g[testFV].trans();
ASSERT_NE(b, nullptr);
EXPECT_EQ(testF, f);
}
TEST_F(CompositeTransformSuite, treeInTest) {
auto result = compTrans2.in();
ASSERT_FALSE(result.empty());
EXPECT_EQ(result, EventTypes({provided, provided2}));
}
TEST_F(CompositeTransformSuite, linearCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(a, create(goal, EventTypes({intermediate})))
.Times(1).WillOnce(Return(TransPtr(&c, [](const Transformer*){})));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided})))
.Times(1).WillOnce(Return(TransPtr(&d, [](const Transformer*){})));
EXPECT_CALL(c, print(_)).Times(1);
EXPECT_CALL(d, print(_)).Times(1);
TransPtr result = compTrans.create();
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"linearComp.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.1f});
MetaEvent eB(intermediate);
eB.attribute(Test0::value())->value().set(0, 0, {1100.0f});
MetaEvent eC(goal);
eC.attribute(Test0::value())->value().set(0, 0, {1100});
EXPECT_CALL(c, call(Events({&eA})))
.Times(1).WillOnce(Return(eB));
EXPECT_CALL(d, call(Events{&eB}))
.Times(1).WillOnce(Return(eC));
EXPECT_EQ((*result)(Events({&eA})), eC);
}
TEST_F(CompositeTransformSuite, treeCreateTest) {
using Events = Transformer::Events;
EXPECT_CALL(e, create(goal, EventTypes({intermediate, intermediate2})))
.Times(1).WillOnce(Return(TransPtr(&c, [](const Transformer*){})));
ASSERT_NE(b, nullptr);
EXPECT_CALL(*b, create(intermediate, EventTypes({provided})))
.Times(1).WillOnce(Return(TransPtr(&d, [](const Transformer*){})));
EXPECT_CALL(f, create(intermediate2, EventTypes({provided2})))
.Times(1).WillOnce(Return(TransPtr(&g, [](const Transformer*){})));
EXPECT_CALL(c, print(_)).Times(1);
EXPECT_CALL(d, print(_)).Times(1);
EXPECT_CALL(g, print(_)).Times(1);
TransPtr result = compTrans2.create();
ASSERT_NE(result, nullptr);
path file = current_path()/"doc"/"treeComp.dot";
ofstream out(file);
out << *result;
MetaEvent eA(provided);
eA.attribute(Test0::value())->value().set(0, 0, {1.0f});
MetaEvent eB(provided2);
eB.attribute(Test1::value())->value().set(0, 0, {2.0f});
MetaEvent eC(intermediate);
eC.attribute(Test0::value())->value().set(0, 0, {3.0f});
MetaEvent eD(intermediate2);
eD.attribute(Test1::value())->value().set(0, 0, {4.0f});
MetaEvent eE(goal);
eE.attribute(Test0::value())->value().set(0, 0, {5.0f});
EXPECT_CALL(c, call(Events({&eA})))
.Times(1).WillOnce(Return(eC));
EXPECT_CALL(d, call(Events({&eB})))
.Times(1).WillOnce(Return(eD));
EXPECT_CALL(g, call(Events({&eC, &eD})))
.Times(1).WillOnce(Return(eE));
EXPECT_EQ((*result)(Events({&eA, &eB})), eE);
}
}
|
Fix errors in compositeTransform test
|
Unit-Test: Fix errors in compositeTransform test
|
C++
|
bsd-3-clause
|
steup/ASEIA,steup/ASEIA
|
0a0ecb5c466e67c1e9757620619cfe9fb89a1abb
|
tests/fakebackend/audiooutput.cpp
|
tests/fakebackend/audiooutput.cpp
|
/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "audiooutput.h"
#include <QVector>
#include <kdebug.h>
#include <config.h>
#ifdef HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <iostream>
namespace Phonon
{
namespace Fake
{
AudioOutput::AudioOutput( QObject* parent )
: AbstractAudioOutput( parent )
, m_device( 1 )
, m_dsp( "/dev/dsp" )
{
}
AudioOutput::~AudioOutput()
{
}
QString AudioOutput::name() const
{
return m_name;
}
float AudioOutput::volume() const
{
return m_volume;
}
int AudioOutput::outputDevice() const
{
return m_device;
}
void AudioOutput::setName( const QString& newName )
{
m_name = newName;
}
void AudioOutput::setVolume( float newVolume )
{
m_volume = newVolume;
emit volumeChanged( m_volume );
}
void AudioOutput::setOutputDevice( int newDevice )
{
Q_ASSERT( newDevice >= 1 );
Q_ASSERT( newDevice <= 2 );
m_device = newDevice;
}
void AudioOutput::processBuffer( const QVector<float>& buffer )
{
//static QFile indump( "indump" );
//if( !indump.isOpen() )
//indump.open( QIODevice::WriteOnly );
//static QFile outdump( "outdump" );
//if( !outdump.isOpen() )
//outdump.open( QIODevice::WriteOnly );
openDevice();
if( !m_dsp.isOpen() )
return;
// we dump the data in /dev/dsp
qint16* pcm = new qint16[ 2*buffer.size() ]; // 2* for stereo
char* towrite = reinterpret_cast<char*>( pcm );
int converted;
for( int i = 0; i < buffer.size(); ++i )
{
//indump.write( QByteArray::number( buffer[ i ] ) + "\n" );
converted = static_cast<qint16>( m_volume * buffer[ i ] * static_cast<float>( 0x7FFF ) );
//outdump.write( QByteArray::number( converted ) + "\n" );
*pcm++ = converted;
*pcm++ = converted;
}
int size = sizeof( qint16 ) * 2 * buffer.size();
int written;
while( size > 0 )
{
written = m_dsp.write( towrite, size );
size = size - written;
if( size > 0 )
{
towrite += written;
kWarning() << "only " << written << " bytes written to /dev/dsp" << endl;
}
}
pcm -= 2*buffer.size();
delete[] pcm;
}
void AudioOutput::openDevice()
{
if( m_dsp.isOpen() )
return;
#ifdef HAVE_SYS_SOUNDCARD_H
if( !m_dsp.open( QIODevice::WriteOnly ) )
kWarning() << "couldn't open /dev/dsp for writing" << endl;
else
{
int fd = m_dsp.handle();
int format = AFMT_S16_LE;
int stereo = 1;
int samplingRate = 44100;
ioctl( fd, SNDCTL_DSP_SETFMT, &format );
ioctl( fd, SNDCTL_DSP_STEREO, &stereo );
ioctl( fd, SNDCTL_DSP_SPEED, &samplingRate );
}
#endif
}
void AudioOutput::closeDevice()
{
m_dsp.close();
}
}} //namespace Phonon::Fake
#include "audiooutput.moc"
// vim: sw=4 ts=4 noet
|
/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "audiooutput.h"
#include <QVector>
#include <kdebug.h>
#include <config.h>
#ifdef HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <iostream>
namespace Phonon
{
namespace Fake
{
AudioOutput::AudioOutput( QObject* parent )
: AbstractAudioOutput( parent )
, m_device( 1 )
, m_dsp( "/dev/dsp" )
{
}
AudioOutput::~AudioOutput()
{
}
QString AudioOutput::name() const
{
return m_name;
}
float AudioOutput::volume() const
{
return m_volume;
}
int AudioOutput::outputDevice() const
{
return m_device;
}
void AudioOutput::setName( const QString& newName )
{
m_name = newName;
}
void AudioOutput::setVolume( float newVolume )
{
m_volume = newVolume;
emit volumeChanged( m_volume );
}
void AudioOutput::setOutputDevice( int newDevice )
{
Q_ASSERT( newDevice >= 1 );
Q_ASSERT( newDevice <= 2 );
m_device = newDevice;
}
void AudioOutput::processBuffer( const QVector<float>& buffer )
{
//static QFile indump( "indump" );
//if( !indump.isOpen() )
//indump.open( QIODevice::WriteOnly );
//static QFile outdump( "outdump" );
//if( !outdump.isOpen() )
//outdump.open( QIODevice::WriteOnly );
openDevice();
if( !m_dsp.isOpen() )
return;
// we dump the data in /dev/dsp
qint16* pcm = new qint16[ 2*buffer.size() ]; // 2* for stereo
char* towrite = reinterpret_cast<char*>( pcm );
int converted;
for( int i = 0; i < buffer.size(); ++i )
{
//indump.write( QByteArray::number( buffer[ i ] ) + "\n" );
converted = static_cast<qint16>( m_volume * buffer[ i ] * static_cast<float>( 0x7FFF ) );
//outdump.write( QByteArray::number( converted ) + "\n" );
*pcm++ = converted;
*pcm++ = converted;
}
int size = sizeof( qint16 ) * 2 * buffer.size();
int written;
while( size > 0 )
{
written = m_dsp.write( towrite, size );
if (written < 0) {
if (errno == EINTR)
continue;
break;
}
size = size - written;
if( size > 0 )
{
towrite += written;
kWarning() << "only " << written << " bytes written to /dev/dsp" << endl;
}
}
pcm -= 2*buffer.size();
delete[] pcm;
}
void AudioOutput::openDevice()
{
if( m_dsp.isOpen() )
return;
#ifdef HAVE_SYS_SOUNDCARD_H
if( !m_dsp.open( QIODevice::WriteOnly ) )
kWarning() << "couldn't open /dev/dsp for writing" << endl;
else
{
int fd = m_dsp.handle();
int format = AFMT_S16_LE;
int stereo = 1;
int samplingRate = 44100;
ioctl( fd, SNDCTL_DSP_SETFMT, &format );
ioctl( fd, SNDCTL_DSP_STEREO, &stereo );
ioctl( fd, SNDCTL_DSP_SPEED, &samplingRate );
}
#endif
}
void AudioOutput::closeDevice()
{
m_dsp.close();
}
}} //namespace Phonon::Fake
#include "audiooutput.moc"
// vim: sw=4 ts=4 noet
|
handle errors of write (I know it's only a fake device, but that shouldn't hinder us to write correct code :)
|
handle errors of write (I know it's only a fake device, but that
shouldn't hinder us to write correct code :)
svn path=/trunk/KDE/kdelibs/phonon/; revision=532142
|
C++
|
lgpl-2.1
|
sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc
|
ab467347f231b72ba7f3803e68348ea771ab3e96
|
Filters/AMR/vtkAMRFlashParticlesReader.cxx
|
Filters/AMR/vtkAMRFlashParticlesReader.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRFlashParticlesReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAMRFlashParticlesReader.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkDataArraySelection.h"
#include "vtkIdList.h"
#include "vtkCellArray.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkPointData.h"
#include "vtkAMRFlashReaderInternal.h"
#define H5_USE_16_API
#include "vtk_hdf5.h" // for the HDF data loading engine
#include <vector>
#include <cassert>
#define FLASH_READER_MAX_DIMS 3
#define FLASH_READER_LEAF_BLOCK 1
#define FLASH_READER_FLASH3_FFV8 8
#define FLASH_READER_FLASH3_FFV9 9
//------------------------------------------------------------------------------
// Description:
// Helper function that reads the particle coordinates
// NOTE: it is assumed that H5DOpen has been called on the
// internal file index this->FileIndex.
void GetParticleCoordinates( hid_t &dataIdx,
std::vector< double > &xcoords, std::vector< double > &ycoords,
std::vector< double > &zcoords,
vtkFlashReaderInternal *iReader,
int NumParticles )
{
assert( "pre: internal reader should not be NULL" && (iReader != NULL) );
hid_t theTypes[3];
theTypes[0] = theTypes[1] = theTypes[3] = H5I_UNINIT;
xcoords.resize( NumParticles );
ycoords.resize( NumParticles );
zcoords.resize( NumParticles );
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
theTypes[0] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
theTypes[1] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
theTypes[2] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
H5Tinsert( theTypes[0], "particle_x", 0, H5T_NATIVE_DOUBLE );
H5Tinsert( theTypes[1], "particle_y", 0, H5T_NATIVE_DOUBLE );
H5Tinsert( theTypes[2], "particle_z", 0, H5T_NATIVE_DOUBLE );
}
// Read the coordinates from the file
switch( iReader->NumberOfDimensions )
{
case 1:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
}
break;
case 2:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
H5Dread(dataIdx,theTypes[1],H5S_ALL,H5S_ALL,H5P_DEFAULT,&ycoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posy",&ycoords[0]);
}
break;
case 3:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
H5Dread(dataIdx,theTypes[1],H5S_ALL,H5S_ALL,H5P_DEFAULT,&ycoords[0]);
H5Dread(dataIdx,theTypes[2],H5S_ALL,H5S_ALL,H5P_DEFAULT,&zcoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posy",&ycoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posz",&zcoords[0]);
}
break;
default:
std::cerr << "ERROR: Undefined dimension!\n" << std::endl;
std::cerr.flush();
return;
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
vtkStandardNewMacro( vtkAMRFlashParticlesReader );
vtkAMRFlashParticlesReader::vtkAMRFlashParticlesReader()
{
this->Internal = new vtkFlashReaderInternal();
this->Initialized = false;
this->Initialize();
}
//------------------------------------------------------------------------------
vtkAMRFlashParticlesReader::~vtkAMRFlashParticlesReader()
{
if( this->Internal != NULL )
{
delete this->Internal;
}
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::PrintSelf( std::ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::ReadMetaData()
{
if( this->Initialized )
{
return;
}
this->Internal->SetFileName( this->FileName );
this->Internal->ReadMetaData();
// In some cases, the FLASH file format may have no blocks but store
// just particles in a single block. However, the AMRBaseParticles reader
// would expect that in this case, the number of blocks is set to 1. The
// following lines of code provide a simple workaround for that.
this->NumberOfBlocks = this->Internal->NumberOfBlocks;
if( this->NumberOfBlocks == 0 && this->Internal->NumberOfParticles > 0)
{
this->NumberOfBlocks=1;
}
this->Initialized = true;
this->SetupParticleDataSelections();
}
//------------------------------------------------------------------------------
int vtkAMRFlashParticlesReader::GetTotalNumberOfParticles()
{
assert( "Internal reader is null" && (this->Internal!=NULL) );
return( this->Internal->NumberOfParticles );
}
//------------------------------------------------------------------------------
vtkPolyData* vtkAMRFlashParticlesReader::GetParticles(
const char *file, const int vtkNotUsed(blkidx) )
{
hid_t dataIdx = H5Dopen( this->Internal->FileIndex, file );
if( dataIdx < 0 )
{
vtkErrorMacro( "Could not open particles file!" );
return NULL;
}
vtkPolyData *particles = vtkPolyData::New();
vtkPoints *positions = vtkPoints::New();
positions->SetDataTypeToDouble();
positions->SetNumberOfPoints( this->Internal->NumberOfParticles );
vtkPointData *pdata = particles->GetPointData();
assert( "pre: PointData is NULL" && (pdata != NULL) );
// Load the particle position arrays by name
std::vector< double > xcoords;
std::vector< double > ycoords;
std::vector< double > zcoords;
GetParticleCoordinates(
dataIdx, xcoords, ycoords, zcoords,
this->Internal, this->Internal->NumberOfParticles );
// Sub-sample particles
int TotalNumberOfParticles = static_cast<int>(xcoords.size());
vtkIdList *ids = vtkIdList::New();
ids->SetNumberOfIds( TotalNumberOfParticles );
vtkIdType NumberOfParticlesLoaded = 0;
for( int i=0; i < TotalNumberOfParticles; ++i )
{
if( i%this->Frequency == 0 )
{
if( this->CheckLocation(xcoords[i],ycoords[i],zcoords[i] ) )
{
int pidx = NumberOfParticlesLoaded;
ids->InsertId( pidx, i );
positions->SetPoint( pidx, xcoords[i], ycoords[i], zcoords[i] );
++NumberOfParticlesLoaded;
} // END if within requested region
} // END if within requested interval
} // END for all particles
xcoords.clear(); ycoords.clear(); zcoords.clear();
ids->SetNumberOfIds( NumberOfParticlesLoaded );
ids->Squeeze();
positions->SetNumberOfPoints( NumberOfParticlesLoaded );
positions->Squeeze();
particles->SetPoints( positions );
positions->Squeeze( );
// Create CellArray consisting of a single polyvertex
vtkCellArray *polyVertex = vtkCellArray::New();
polyVertex ->InsertNextCell( NumberOfParticlesLoaded );
for( vtkIdType idx=0; idx < NumberOfParticlesLoaded; ++idx )
{
polyVertex->InsertCellPoint( idx );
}
particles->SetVerts( polyVertex );
polyVertex->Delete();
// Load particle data arrays
int numArrays = this->ParticleDataArraySelection->GetNumberOfArrays();
for( int i=0; i < numArrays; ++i )
{
const char *name = this->ParticleDataArraySelection->GetArrayName( i );
if( this->ParticleDataArraySelection->ArrayIsEnabled( name ) )
{
int attrIdx = this->Internal->ParticleAttributeNamesToIds[ name ];
hid_t attrType = this->Internal->ParticleAttributeTypes[ attrIdx ];
if( attrType == H5T_NATIVE_DOUBLE )
{
double *data = new double[ this->Internal->NumberOfParticles ];
assert( data != NULL );
if( this->Internal->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
hid_t dataType = H5Tcreate( H5T_COMPOUND, sizeof(double) );
H5Tinsert( dataType, name, 0, H5T_NATIVE_DOUBLE );
H5Dread(dataIdx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT,data);
H5Tclose( dataType );
}
else
{
this->Internal->ReadParticlesComponent( dataIdx, name, data );
}
vtkDataArray *array = vtkDoubleArray::New();
array->SetName( name );
array->SetNumberOfTuples( ids->GetNumberOfIds() );
array->SetNumberOfComponents( 1 );
vtkIdType numIds = ids->GetNumberOfIds();
for( vtkIdType pidx=0; pidx < numIds; ++pidx )
{
vtkIdType particleIdx = ids->GetId( pidx );
array->SetComponent( pidx, 0, data[ particleIdx ] );
} // END for all ids of loaded particles
pdata->AddArray( array );
delete [] data;
}
else if( attrType == H5T_NATIVE_INT )
{
hid_t dataType = H5Tcreate( H5T_COMPOUND, sizeof(int) );
H5Tinsert( dataType, name, 0, H5T_NATIVE_INT );
int *data = new int[ this->Internal->NumberOfParticles ];
assert( data != NULL );
H5Dread( dataIdx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, data );
vtkDataArray *array = vtkIntArray::New();
array->SetName( name );
array->SetNumberOfTuples( ids->GetNumberOfIds() );
array->SetNumberOfComponents( 1 );
vtkIdType numIds = ids->GetNumberOfIds( );
for( vtkIdType pidx=0; pidx < numIds; ++pidx )
{
vtkIdType particleIdx = ids->GetId( pidx );
array->SetComponent( pidx, 0, data[ particleIdx ] );
} // END for all ids of loaded particles
pdata->AddArray( array );
delete [] data;
}
else
{
vtkErrorMacro( "Unsupport array type in HDF5 file!" );
return NULL;
}
} // END if the array is supposed to be loaded
} // END for all arrays
H5Dclose(dataIdx);
return( particles );
}
//------------------------------------------------------------------------------
vtkPolyData* vtkAMRFlashParticlesReader::ReadParticles( const int blkidx )
{
assert( "pre: Internal reader is NULL" && (this->Internal != NULL) );
assert( "pre: Not initialized " && (this->Initialized) );
int NumberOfParticles = this->Internal->NumberOfParticles;
if( NumberOfParticles <= 0 )
{
vtkPolyData *emptyParticles = vtkPolyData::New();
assert( "Cannot create particle dataset" && (emptyParticles != NULL) );
return( emptyParticles );
}
vtkPolyData* particles = this->GetParticles(
this->Internal->ParticleName.c_str(), blkidx );
assert( "partciles should not be NULL " && (particles != NULL) );
return( particles );
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::SetupParticleDataSelections()
{
assert( "pre: Internal reader is NULL" && (this->Internal != NULL) );
unsigned int N =
static_cast<unsigned int>(this->Internal->ParticleAttributeNames.size());
for( unsigned int i=0; i < N; ++i )
{
this->ParticleDataArraySelection->AddArray(
this->Internal->ParticleAttributeNames[ i ].c_str( ) );
} // END for all particles attributes
this->InitializeParticleDataSelections();
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkAMRFlashParticlesReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAMRFlashParticlesReader.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkDataArraySelection.h"
#include "vtkIdList.h"
#include "vtkCellArray.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkPointData.h"
#include "vtkAMRFlashReaderInternal.h"
#define H5_USE_16_API
#include "vtk_hdf5.h" // for the HDF data loading engine
#include <vector>
#include <cassert>
#define FLASH_READER_MAX_DIMS 3
#define FLASH_READER_LEAF_BLOCK 1
#define FLASH_READER_FLASH3_FFV8 8
#define FLASH_READER_FLASH3_FFV9 9
//------------------------------------------------------------------------------
// Description:
// Helper function that reads the particle coordinates
// NOTE: it is assumed that H5DOpen has been called on the
// internal file index this->FileIndex.
void GetParticleCoordinates( hid_t &dataIdx,
std::vector< double > &xcoords, std::vector< double > &ycoords,
std::vector< double > &zcoords,
vtkFlashReaderInternal *iReader,
int NumParticles )
{
assert( "pre: internal reader should not be NULL" && (iReader != NULL) );
hid_t theTypes[3];
theTypes[0] = theTypes[1] = theTypes[2] = H5I_UNINIT;
xcoords.resize( NumParticles );
ycoords.resize( NumParticles );
zcoords.resize( NumParticles );
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
theTypes[0] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
theTypes[1] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
theTypes[2] = H5Tcreate( H5T_COMPOUND, sizeof(double) );
H5Tinsert( theTypes[0], "particle_x", 0, H5T_NATIVE_DOUBLE );
H5Tinsert( theTypes[1], "particle_y", 0, H5T_NATIVE_DOUBLE );
H5Tinsert( theTypes[2], "particle_z", 0, H5T_NATIVE_DOUBLE );
}
// Read the coordinates from the file
switch( iReader->NumberOfDimensions )
{
case 1:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
}
break;
case 2:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
H5Dread(dataIdx,theTypes[1],H5S_ALL,H5S_ALL,H5P_DEFAULT,&ycoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posy",&ycoords[0]);
}
break;
case 3:
if( iReader->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
H5Dread(dataIdx,theTypes[0],H5S_ALL,H5S_ALL,H5P_DEFAULT,&xcoords[0]);
H5Dread(dataIdx,theTypes[1],H5S_ALL,H5S_ALL,H5P_DEFAULT,&ycoords[0]);
H5Dread(dataIdx,theTypes[2],H5S_ALL,H5S_ALL,H5P_DEFAULT,&zcoords[0]);
}
else
{
iReader->ReadParticlesComponent(dataIdx,"Particles/posx",&xcoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posy",&ycoords[0]);
iReader->ReadParticlesComponent(dataIdx,"Particles/posz",&zcoords[0]);
}
break;
default:
std::cerr << "ERROR: Undefined dimension!\n" << std::endl;
std::cerr.flush();
return;
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
vtkStandardNewMacro( vtkAMRFlashParticlesReader );
vtkAMRFlashParticlesReader::vtkAMRFlashParticlesReader()
{
this->Internal = new vtkFlashReaderInternal();
this->Initialized = false;
this->Initialize();
}
//------------------------------------------------------------------------------
vtkAMRFlashParticlesReader::~vtkAMRFlashParticlesReader()
{
if( this->Internal != NULL )
{
delete this->Internal;
}
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::PrintSelf( std::ostream &os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::ReadMetaData()
{
if( this->Initialized )
{
return;
}
this->Internal->SetFileName( this->FileName );
this->Internal->ReadMetaData();
// In some cases, the FLASH file format may have no blocks but store
// just particles in a single block. However, the AMRBaseParticles reader
// would expect that in this case, the number of blocks is set to 1. The
// following lines of code provide a simple workaround for that.
this->NumberOfBlocks = this->Internal->NumberOfBlocks;
if( this->NumberOfBlocks == 0 && this->Internal->NumberOfParticles > 0)
{
this->NumberOfBlocks=1;
}
this->Initialized = true;
this->SetupParticleDataSelections();
}
//------------------------------------------------------------------------------
int vtkAMRFlashParticlesReader::GetTotalNumberOfParticles()
{
assert( "Internal reader is null" && (this->Internal!=NULL) );
return( this->Internal->NumberOfParticles );
}
//------------------------------------------------------------------------------
vtkPolyData* vtkAMRFlashParticlesReader::GetParticles(
const char *file, const int vtkNotUsed(blkidx) )
{
hid_t dataIdx = H5Dopen( this->Internal->FileIndex, file );
if( dataIdx < 0 )
{
vtkErrorMacro( "Could not open particles file!" );
return NULL;
}
vtkPolyData *particles = vtkPolyData::New();
vtkPoints *positions = vtkPoints::New();
positions->SetDataTypeToDouble();
positions->SetNumberOfPoints( this->Internal->NumberOfParticles );
vtkPointData *pdata = particles->GetPointData();
assert( "pre: PointData is NULL" && (pdata != NULL) );
// Load the particle position arrays by name
std::vector< double > xcoords;
std::vector< double > ycoords;
std::vector< double > zcoords;
GetParticleCoordinates(
dataIdx, xcoords, ycoords, zcoords,
this->Internal, this->Internal->NumberOfParticles );
// Sub-sample particles
int TotalNumberOfParticles = static_cast<int>(xcoords.size());
vtkIdList *ids = vtkIdList::New();
ids->SetNumberOfIds( TotalNumberOfParticles );
vtkIdType NumberOfParticlesLoaded = 0;
for( int i=0; i < TotalNumberOfParticles; ++i )
{
if( i%this->Frequency == 0 )
{
if( this->CheckLocation(xcoords[i],ycoords[i],zcoords[i] ) )
{
int pidx = NumberOfParticlesLoaded;
ids->InsertId( pidx, i );
positions->SetPoint( pidx, xcoords[i], ycoords[i], zcoords[i] );
++NumberOfParticlesLoaded;
} // END if within requested region
} // END if within requested interval
} // END for all particles
xcoords.clear(); ycoords.clear(); zcoords.clear();
ids->SetNumberOfIds( NumberOfParticlesLoaded );
ids->Squeeze();
positions->SetNumberOfPoints( NumberOfParticlesLoaded );
positions->Squeeze();
particles->SetPoints( positions );
positions->Squeeze( );
// Create CellArray consisting of a single polyvertex
vtkCellArray *polyVertex = vtkCellArray::New();
polyVertex ->InsertNextCell( NumberOfParticlesLoaded );
for( vtkIdType idx=0; idx < NumberOfParticlesLoaded; ++idx )
{
polyVertex->InsertCellPoint( idx );
}
particles->SetVerts( polyVertex );
polyVertex->Delete();
// Load particle data arrays
int numArrays = this->ParticleDataArraySelection->GetNumberOfArrays();
for( int i=0; i < numArrays; ++i )
{
const char *name = this->ParticleDataArraySelection->GetArrayName( i );
if( this->ParticleDataArraySelection->ArrayIsEnabled( name ) )
{
int attrIdx = this->Internal->ParticleAttributeNamesToIds[ name ];
hid_t attrType = this->Internal->ParticleAttributeTypes[ attrIdx ];
if( attrType == H5T_NATIVE_DOUBLE )
{
double *data = new double[ this->Internal->NumberOfParticles ];
assert( data != NULL );
if( this->Internal->FileFormatVersion < FLASH_READER_FLASH3_FFV8 )
{
hid_t dataType = H5Tcreate( H5T_COMPOUND, sizeof(double) );
H5Tinsert( dataType, name, 0, H5T_NATIVE_DOUBLE );
H5Dread(dataIdx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT,data);
H5Tclose( dataType );
}
else
{
this->Internal->ReadParticlesComponent( dataIdx, name, data );
}
vtkDataArray *array = vtkDoubleArray::New();
array->SetName( name );
array->SetNumberOfTuples( ids->GetNumberOfIds() );
array->SetNumberOfComponents( 1 );
vtkIdType numIds = ids->GetNumberOfIds();
for( vtkIdType pidx=0; pidx < numIds; ++pidx )
{
vtkIdType particleIdx = ids->GetId( pidx );
array->SetComponent( pidx, 0, data[ particleIdx ] );
} // END for all ids of loaded particles
pdata->AddArray( array );
delete [] data;
}
else if( attrType == H5T_NATIVE_INT )
{
hid_t dataType = H5Tcreate( H5T_COMPOUND, sizeof(int) );
H5Tinsert( dataType, name, 0, H5T_NATIVE_INT );
int *data = new int[ this->Internal->NumberOfParticles ];
assert( data != NULL );
H5Dread( dataIdx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, data );
vtkDataArray *array = vtkIntArray::New();
array->SetName( name );
array->SetNumberOfTuples( ids->GetNumberOfIds() );
array->SetNumberOfComponents( 1 );
vtkIdType numIds = ids->GetNumberOfIds( );
for( vtkIdType pidx=0; pidx < numIds; ++pidx )
{
vtkIdType particleIdx = ids->GetId( pidx );
array->SetComponent( pidx, 0, data[ particleIdx ] );
} // END for all ids of loaded particles
pdata->AddArray( array );
delete [] data;
}
else
{
vtkErrorMacro( "Unsupport array type in HDF5 file!" );
return NULL;
}
} // END if the array is supposed to be loaded
} // END for all arrays
H5Dclose(dataIdx);
return( particles );
}
//------------------------------------------------------------------------------
vtkPolyData* vtkAMRFlashParticlesReader::ReadParticles( const int blkidx )
{
assert( "pre: Internal reader is NULL" && (this->Internal != NULL) );
assert( "pre: Not initialized " && (this->Initialized) );
int NumberOfParticles = this->Internal->NumberOfParticles;
if( NumberOfParticles <= 0 )
{
vtkPolyData *emptyParticles = vtkPolyData::New();
assert( "Cannot create particle dataset" && (emptyParticles != NULL) );
return( emptyParticles );
}
vtkPolyData* particles = this->GetParticles(
this->Internal->ParticleName.c_str(), blkidx );
assert( "partciles should not be NULL " && (particles != NULL) );
return( particles );
}
//------------------------------------------------------------------------------
void vtkAMRFlashParticlesReader::SetupParticleDataSelections()
{
assert( "pre: Internal reader is NULL" && (this->Internal != NULL) );
unsigned int N =
static_cast<unsigned int>(this->Internal->ParticleAttributeNames.size());
for( unsigned int i=0; i < N; ++i )
{
this->ParticleDataArraySelection->AddArray(
this->Internal->ParticleAttributeNames[ i ].c_str( ) );
} // END for all particles attributes
this->InitializeParticleDataSelections();
}
|
fix typo
|
fix typo
Change-Id: I8ff2aaff4115274bf95df989a4630128e1e01c9b
|
C++
|
bsd-3-clause
|
biddisco/VTK,aashish24/VTK-old,gram526/VTK,msmolens/VTK,demarle/VTK,candy7393/VTK,mspark93/VTK,jmerkow/VTK,aashish24/VTK-old,ashray/VTK-EVM,biddisco/VTK,demarle/VTK,sankhesh/VTK,msmolens/VTK,gram526/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,mspark93/VTK,keithroe/vtkoptix,SimVascular/VTK,SimVascular/VTK,collects/VTK,biddisco/VTK,sumedhasingla/VTK,ashray/VTK-EVM,biddisco/VTK,berendkleinhaneveld/VTK,collects/VTK,berendkleinhaneveld/VTK,keithroe/vtkoptix,johnkit/vtk-dev,sumedhasingla/VTK,ashray/VTK-EVM,gram526/VTK,collects/VTK,berendkleinhaneveld/VTK,candy7393/VTK,msmolens/VTK,johnkit/vtk-dev,SimVascular/VTK,candy7393/VTK,jmerkow/VTK,keithroe/vtkoptix,biddisco/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,sumedhasingla/VTK,johnkit/vtk-dev,aashish24/VTK-old,sumedhasingla/VTK,gram526/VTK,mspark93/VTK,mspark93/VTK,ashray/VTK-EVM,keithroe/vtkoptix,jmerkow/VTK,sumedhasingla/VTK,aashish24/VTK-old,aashish24/VTK-old,msmolens/VTK,demarle/VTK,sankhesh/VTK,hendradarwin/VTK,biddisco/VTK,ashray/VTK-EVM,johnkit/vtk-dev,keithroe/vtkoptix,msmolens/VTK,sankhesh/VTK,mspark93/VTK,hendradarwin/VTK,sumedhasingla/VTK,hendradarwin/VTK,johnkit/vtk-dev,johnkit/vtk-dev,demarle/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,SimVascular/VTK,aashish24/VTK-old,sankhesh/VTK,hendradarwin/VTK,sankhesh/VTK,gram526/VTK,SimVascular/VTK,SimVascular/VTK,candy7393/VTK,collects/VTK,demarle/VTK,keithroe/vtkoptix,hendradarwin/VTK,jmerkow/VTK,sumedhasingla/VTK,candy7393/VTK,keithroe/vtkoptix,collects/VTK,mspark93/VTK,jmerkow/VTK,msmolens/VTK,ashray/VTK-EVM,collects/VTK,candy7393/VTK,berendkleinhaneveld/VTK,candy7393/VTK,jmerkow/VTK,mspark93/VTK,biddisco/VTK,sankhesh/VTK,demarle/VTK,candy7393/VTK,keithroe/vtkoptix,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,jmerkow/VTK,johnkit/vtk-dev,msmolens/VTK,SimVascular/VTK,jmerkow/VTK,hendradarwin/VTK,hendradarwin/VTK,demarle/VTK,demarle/VTK,gram526/VTK,SimVascular/VTK,msmolens/VTK,gram526/VTK,gram526/VTK
|
bef0d903822736281a3e1e8855812fe23f782219
|
CppImport/src/macro/StaticStuff.cpp
|
CppImport/src/macro/StaticStuff.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "StaticStuff.h"
namespace CppImport {
void StaticStuff::orderNodes(QVector<Model::Node*>& input)
{
qSort(input.begin(), input.end(),
[](Model::Node* e1, Model::Node* e2)
{
if (auto commonAncestor = e1->lowestCommonAncestor(e2))
if (auto list = DCast<Model::List>(commonAncestor))
{
int index1 = -1;
for (auto c : list->children())
if (c == e1 || c->isAncestorOf(e1))
{
index1 = list->indexOf(c);
break;
}
int index2 = -1;
for (auto c : list->children())
if (c == e2 || c->isAncestorOf(e2))
{
index2 = list->indexOf(c);
break;
}
return index1 < index2;
}
return true;
});
}
bool StaticStuff::validContext(Model::Node* node)
{
if (DCast<OOModel::Project>(node))
return true;
else if (DCast<OOModel::Module>(node))
return true;
else if (DCast<OOModel::Class>(node))
return true;
else if (DCast<OOModel::Method>(node))
return true;
else
return false;
}
OOModel::Declaration*StaticStuff::actualContext(Model::Node* node)
{
auto current = node->parent();
while (current)
{
if (auto result = DCast<OOModel::Project>(current))
return result;
else if (auto result = DCast<OOModel::Module>(current))
return result;
else if (auto result = DCast<OOModel::Class>(current))
return result;
else if (auto result = DCast<OOModel::Method>(current))
return result;
else
current = current->parent();
}
Q_ASSERT(false);
}
OOModel::Declaration*StaticStuff::createContext(OOModel::Declaration* actualContext)
{
if (DCast<OOModel::Project>(actualContext))
return new OOModel::Project("Context");
else if (DCast<OOModel::Module>(actualContext))
return new OOModel::Module("Context");
else if (DCast<OOModel::Class>(actualContext))
return new OOModel::Class("Context");
else if (DCast<OOModel::Method>(actualContext))
return new OOModel::Method("Context");
Q_ASSERT(false);
}
Model::Node* StaticStuff::cloneWithMapping(Model::Node* node, NodeMapping* mapping)
{
auto clone = node->clone();
QList<Model::Node*> info;
buildMappingInfo(node, &info);
useMappingInfo(clone, &info, mapping);
return clone;
}
void StaticStuff::removeNode(Model::Node* node, bool removeMetaCalls)
{
if (!node || !node->parent()) return;
if (!removeMetaCalls)
while (auto metaCall = containsMetaCall(node))
{
return;
if (auto declaration = DCast<OOModel::Declaration>(metaCall->parent()->parent()))
{
auto newDeclaration = node->firstAncestorOfType<OOModel::Declaration>();
declaration->metaCalls()->remove(declaration->metaCalls()->indexOf(metaCall));
newDeclaration->metaCalls()->append(metaCall);
}
}
if (auto ooList = DCast<Model::List>(node->parent()))
ooList->remove(ooList->indexOf(node));
else if (auto ooVarDecl = DCast<OOModel::VariableDeclaration>(node->parent()))
{
if (ooVarDecl->initialValue() == node)
ooVarDecl->setInitialValue(nullptr);
}
else if (auto skip = DCast<OOModel::VariableDeclarationExpression>(node->parent()))
removeNode(skip, removeMetaCalls);
else if (auto skip = DCast<OOModel::ExpressionStatement>(node->parent()))
removeNode(skip, removeMetaCalls);
else
qDebug() << "not removed" << node->typeName() << "in" << node->parent()->typeName();
}
void StaticStuff::addNodeToDeclaration(Model::Node* node, OOModel::Declaration* declaration)
{
if (auto ooExpression = DCast<OOModel::Expression>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(new OOModel::ExpressionStatement(ooExpression));
else
qDebug() << "can not insert expression" << ooExpression->typeName() << "into a" << declaration->typeName();
}
else if (auto ooStatement = DCast<OOModel::Statement>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(ooStatement);
else
Q_ASSERT(false);
}
else if (auto ooDeclaration = DCast<OOModel::Declaration>(node))
{
if (auto ooClass = DCast<OOModel::Class>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->classes()->append(ooClass);
else if (auto context = DCast<OOModel::Module>(declaration))
context->classes()->append(ooClass);
else if (auto context = DCast<OOModel::Class>(declaration))
context->classes()->append(ooClass);
else
Q_ASSERT(false);
}
else if (auto ooField = DCast<OOModel::Field>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->fields()->append(ooField);
else if (auto context = DCast<OOModel::Module>(declaration))
context->fields()->append(ooField);
else if (auto context = DCast<OOModel::Class>(declaration))
context->fields()->append(ooField);
else
Q_ASSERT(false);
}
else if (auto ooVarDecl = DCast<OOModel::VariableDeclaration>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(new OOModel::ExpressionStatement(
new OOModel::VariableDeclarationExpression(ooVarDecl)));
else
Q_ASSERT(false);
}
else if (auto ooMethod = DCast<OOModel::Method>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->methods()->append(ooMethod);
else if (auto context = DCast<OOModel::Module>(declaration))
context->methods()->append(ooMethod);
else if (auto context = DCast<OOModel::Class>(declaration))
context->methods()->append(ooMethod);
else
Q_ASSERT(false);
}
else
{
if (auto context = DCast<OOModel::Project>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Module>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Class>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Method>(declaration))
context->subDeclarations()->append(ooDeclaration);
else
Q_ASSERT(false);
}
}
else
Q_ASSERT(false && "not implemented");
}
QVector<Model::Node*> StaticStuff::topLevelNodes(QVector<Model::Node*> input)
{
QSet<Model::Node*> topLevel;
for (auto node : input) topLevel.insert(node);
for (auto node : input)
for (auto other : input)
if (node != other)
if (node->isAncestorOf(other))
topLevel.remove(other);
QVector<Model::Node*> result;
for (auto node : topLevel) result.append(node);
return result;
}
void StaticStuff::buildMappingInfo(Model::Node* node, QList<Model::Node*>* info)
{
info->push_back(node);
for (auto child : node->children())
buildMappingInfo(child, info);
}
void StaticStuff::useMappingInfo(Model::Node* node, QList<Model::Node*>* info, NodeMapping* mapping)
{
mapping->add(info->front(), node);
info->pop_front();
for (auto child : node->children())
useMappingInfo(child, info, mapping);
}
OOModel::MetaCallExpression* StaticStuff::containsMetaCall(Model::Node* node)
{
if (auto metaCall = DCast<OOModel::MetaCallExpression>(node))
return metaCall;
for (auto child : node->children())
if (auto metaCall = containsMetaCall(child))
return metaCall;
return nullptr;
}
bool StaticStuff::stringMatches(const QString& regex, const QString& value)
{
QRegularExpression regEx(regex);
return regEx.match(value).hasMatch();
}
OOModel::Declaration*StaticStuff::findDeclaration(Model::List* list, const QString& name)
{
for (auto i = 0; i < list->size(); i++)
if (auto decl = DCast<OOModel::Declaration>(list->at(i)))
if (decl->name() == name)
return decl;
return nullptr;
}
OOModel::Expression* StaticStuff::createNameExpressionFromString(const QString& input)
{
QString baseCase = "((::)?(\\w+(::|\\.|->))*\\w+(\\*|&)?)";
if (stringMatches("^" + baseCase + "$", input))
{
QRegularExpression regEx("(::|\\.)");
QStringList parts = input.split(regEx);
QString basePart = parts.last();
OOModel::Expression* result = nullptr;
OOModel::ReferenceExpression* current = nullptr;
if (basePart.endsWith("&"))
{
current = new OOModel::ReferenceExpression(basePart.left(basePart.length() - 1));
result = new OOModel::ReferenceTypeExpression(current);
}
else if (basePart.endsWith("*"))
{
current = new OOModel::ReferenceExpression(basePart.left(basePart.length() - 1));
result = new OOModel::PointerTypeExpression(current);
}
else
{
current = new OOModel::ReferenceExpression(basePart);
result = current;
}
for (auto i = parts.size() - 2; i >= 0; i--)
{
QString part = parts[i];
if (part.isEmpty())
{
Q_ASSERT(i == 0);
current->setPrefix(new OOModel::GlobalScopeExpression());
}
else
{
auto next = new OOModel::ReferenceExpression(part);
current->setPrefix(next);
current = next;
}
}
return result;
}
else if (stringMatches("^" + baseCase + "<" + baseCase + ">$", input))
{
QStringList split = input.split("<");
auto baseRef = DCast<OOModel::ReferenceExpression>(createNameExpressionFromString(split[0]));
Q_ASSERT(baseRef);
auto typeArg = createNameExpressionFromString(split[1].left(split[1].length() - 1));
baseRef->typeArguments()->append(typeArg);
return baseRef;
}
else
{
qDebug() << "createReferenceExpressionFromString failed on input:" << input;
return new OOModel::ReferenceExpression(input);
}
}
}
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "StaticStuff.h"
namespace CppImport {
void StaticStuff::orderNodes(QVector<Model::Node*>& input)
{
qSort(input.begin(), input.end(),
[](Model::Node* e1, Model::Node* e2)
{
if (auto commonAncestor = e1->lowestCommonAncestor(e2))
if (auto list = DCast<Model::List>(commonAncestor))
{
int index1 = -1;
for (auto c : list->children())
if (c == e1 || c->isAncestorOf(e1))
{
index1 = list->indexOf(c);
break;
}
int index2 = -1;
for (auto c : list->children())
if (c == e2 || c->isAncestorOf(e2))
{
index2 = list->indexOf(c);
break;
}
return index1 < index2;
}
return true;
});
}
bool StaticStuff::validContext(Model::Node* node)
{
if (DCast<OOModel::Project>(node))
return true;
else if (DCast<OOModel::Module>(node))
return true;
else if (DCast<OOModel::Class>(node))
return true;
else if (DCast<OOModel::Method>(node))
return true;
else
return false;
}
OOModel::Declaration* StaticStuff::actualContext(Model::Node* node)
{
auto current = node->parent();
while (current)
{
if (auto result = DCast<OOModel::Project>(current))
return result;
else if (auto result = DCast<OOModel::Module>(current))
return result;
else if (auto result = DCast<OOModel::Class>(current))
return result;
else if (auto result = DCast<OOModel::Method>(current))
return result;
else
current = current->parent();
}
Q_ASSERT(false);
}
OOModel::Declaration* StaticStuff::createContext(OOModel::Declaration* actualContext)
{
if (DCast<OOModel::Project>(actualContext))
return new OOModel::Project("Context");
else if (DCast<OOModel::Module>(actualContext))
return new OOModel::Module("Context");
else if (DCast<OOModel::Class>(actualContext))
return new OOModel::Class("Context");
else if (DCast<OOModel::Method>(actualContext))
return new OOModel::Method("Context");
Q_ASSERT(false);
}
Model::Node* StaticStuff::cloneWithMapping(Model::Node* node, NodeMapping* mapping)
{
auto clone = node->clone();
QList<Model::Node*> info;
buildMappingInfo(node, &info);
useMappingInfo(clone, &info, mapping);
return clone;
}
void StaticStuff::removeNode(Model::Node* node, bool removeMetaCalls)
{
if (!node || !node->parent()) return;
if (!removeMetaCalls)
while (auto metaCall = containsMetaCall(node))
{
return;
if (auto declaration = DCast<OOModel::Declaration>(metaCall->parent()->parent()))
{
auto newDeclaration = node->firstAncestorOfType<OOModel::Declaration>();
declaration->metaCalls()->remove(declaration->metaCalls()->indexOf(metaCall));
newDeclaration->metaCalls()->append(metaCall);
}
}
if (auto ooList = DCast<Model::List>(node->parent()))
ooList->remove(ooList->indexOf(node));
else if (auto ooVarDecl = DCast<OOModel::VariableDeclaration>(node->parent()))
{
if (ooVarDecl->initialValue() == node)
ooVarDecl->setInitialValue(nullptr);
}
else if (auto skip = DCast<OOModel::VariableDeclarationExpression>(node->parent()))
removeNode(skip, removeMetaCalls);
else if (auto skip = DCast<OOModel::ExpressionStatement>(node->parent()))
removeNode(skip, removeMetaCalls);
else
qDebug() << "not removed" << node->typeName() << "in" << node->parent()->typeName();
}
void StaticStuff::addNodeToDeclaration(Model::Node* node, OOModel::Declaration* declaration)
{
if (auto ooExpression = DCast<OOModel::Expression>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(new OOModel::ExpressionStatement(ooExpression));
else
qDebug() << "can not insert expression" << ooExpression->typeName() << "into a" << declaration->typeName();
}
else if (auto ooStatement = DCast<OOModel::Statement>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(ooStatement);
else
Q_ASSERT(false);
}
else if (auto ooDeclaration = DCast<OOModel::Declaration>(node))
{
if (auto ooClass = DCast<OOModel::Class>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->classes()->append(ooClass);
else if (auto context = DCast<OOModel::Module>(declaration))
context->classes()->append(ooClass);
else if (auto context = DCast<OOModel::Class>(declaration))
context->classes()->append(ooClass);
else
Q_ASSERT(false);
}
else if (auto ooField = DCast<OOModel::Field>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->fields()->append(ooField);
else if (auto context = DCast<OOModel::Module>(declaration))
context->fields()->append(ooField);
else if (auto context = DCast<OOModel::Class>(declaration))
context->fields()->append(ooField);
else
Q_ASSERT(false);
}
else if (auto ooVarDecl = DCast<OOModel::VariableDeclaration>(node))
{
if (auto context = DCast<OOModel::Method>(declaration))
context->items()->append(new OOModel::ExpressionStatement(
new OOModel::VariableDeclarationExpression(ooVarDecl)));
else
Q_ASSERT(false);
}
else if (auto ooMethod = DCast<OOModel::Method>(node))
{
if (auto context = DCast<OOModel::Project>(declaration))
context->methods()->append(ooMethod);
else if (auto context = DCast<OOModel::Module>(declaration))
context->methods()->append(ooMethod);
else if (auto context = DCast<OOModel::Class>(declaration))
context->methods()->append(ooMethod);
else
Q_ASSERT(false);
}
else
{
if (auto context = DCast<OOModel::Project>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Module>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Class>(declaration))
context->subDeclarations()->append(ooDeclaration);
else if (auto context = DCast<OOModel::Method>(declaration))
context->subDeclarations()->append(ooDeclaration);
else
Q_ASSERT(false);
}
}
else
Q_ASSERT(false && "not implemented");
}
QVector<Model::Node*> StaticStuff::topLevelNodes(QVector<Model::Node*> input)
{
QSet<Model::Node*> topLevel;
for (auto node : input) topLevel.insert(node);
for (auto node : input)
for (auto other : input)
if (node != other)
if (node->isAncestorOf(other))
topLevel.remove(other);
QVector<Model::Node*> result;
for (auto node : topLevel) result.append(node);
return result;
}
void StaticStuff::buildMappingInfo(Model::Node* node, QList<Model::Node*>* info)
{
info->push_back(node);
for (auto child : node->children())
buildMappingInfo(child, info);
}
void StaticStuff::useMappingInfo(Model::Node* node, QList<Model::Node*>* info, NodeMapping* mapping)
{
mapping->add(info->front(), node);
info->pop_front();
for (auto child : node->children())
useMappingInfo(child, info, mapping);
}
OOModel::MetaCallExpression* StaticStuff::containsMetaCall(Model::Node* node)
{
if (auto metaCall = DCast<OOModel::MetaCallExpression>(node))
return metaCall;
for (auto child : node->children())
if (auto metaCall = containsMetaCall(child))
return metaCall;
return nullptr;
}
bool StaticStuff::stringMatches(const QString& regex, const QString& value)
{
QRegularExpression regEx(regex);
return regEx.match(value).hasMatch();
}
OOModel::Declaration* StaticStuff::findDeclaration(Model::List* list, const QString& name)
{
for (auto i = 0; i < list->size(); i++)
if (auto decl = DCast<OOModel::Declaration>(list->at(i)))
if (decl->name() == name)
return decl;
return nullptr;
}
OOModel::Expression* StaticStuff::createNameExpressionFromString(const QString& input)
{
QString baseCase = "((::)?(\\w+(::|\\.|->))*\\w+(\\*|&)?)";
if (stringMatches("^" + baseCase + "$", input))
{
QRegularExpression regEx("(::|\\.)");
QStringList parts = input.split(regEx);
QString basePart = parts.last();
OOModel::Expression* result = nullptr;
OOModel::ReferenceExpression* current = nullptr;
if (basePart.endsWith("&"))
{
current = new OOModel::ReferenceExpression(basePart.left(basePart.length() - 1));
result = new OOModel::ReferenceTypeExpression(current);
}
else if (basePart.endsWith("*"))
{
current = new OOModel::ReferenceExpression(basePart.left(basePart.length() - 1));
result = new OOModel::PointerTypeExpression(current);
}
else
{
current = new OOModel::ReferenceExpression(basePart);
result = current;
}
for (auto i = parts.size() - 2; i >= 0; i--)
{
QString part = parts[i];
if (part.isEmpty())
{
Q_ASSERT(i == 0);
current->setPrefix(new OOModel::GlobalScopeExpression());
}
else
{
auto next = new OOModel::ReferenceExpression(part);
current->setPrefix(next);
current = next;
}
}
return result;
}
else if (stringMatches("^" + baseCase + "<" + baseCase + ">$", input))
{
QStringList split = input.split("<");
auto baseRef = DCast<OOModel::ReferenceExpression>(createNameExpressionFromString(split[0]));
Q_ASSERT(baseRef);
auto typeArg = createNameExpressionFromString(split[1].left(split[1].length() - 1));
baseRef->typeArguments()->append(typeArg);
return baseRef;
}
else
{
qDebug() << "createReferenceExpressionFromString failed on input:" << input;
return new OOModel::ReferenceExpression(input);
}
}
}
|
add spaces between method return type and name
|
add spaces between method return type and name
|
C++
|
bsd-3-clause
|
mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,mgalbier/Envision,mgalbier/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,mgalbier/Envision,dimitar-asenov/Envision,mgalbier/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision
|
3e5b56a007b660e44cbcdd58ebc6b5ff61dc9899
|
OpenSim/Common/C3DFileAdapter.cpp
|
OpenSim/Common/C3DFileAdapter.cpp
|
#include "C3DFileAdapter.h"
#include "btkAcquisitionFileReader.h"
#include "btkAcquisition.h"
#include "btkForcePlatformsExtractor.h"
#include "btkGroundReactionWrenchFilter.h"
namespace {
// Function to convert Eigen matrix to SimTK matrix. This can become a lambda
// funciton inside extendRead in future.
template<typename _Scalar, int _Rows, int _Cols>
SimTK::Matrix_<double>
convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>&
eigenMat) {
SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()),
static_cast<int>(eigenMat.cols())};
for(int r = 0; r < eigenMat.rows(); ++r)
for(int c = 0; c < eigenMat.cols(); ++c)
simtkMat(r, c) = eigenMat(r, c);
return simtkMat;
}
} // anonymous namespace
namespace OpenSim {
const std::string C3DFileAdapter::_markers{"markers"};
const std::string C3DFileAdapter::_forces{"forces"};
const std::unordered_map<std::string, size_t>
C3DFileAdapter::_unit_index{{"marker", 0},
{"angle" , 1},
{"force" , 2},
{"moment", 3},
{"power" , 4},
{"scalar", 5}};
C3DFileAdapter*
C3DFileAdapter::clone() const {
return new C3DFileAdapter{*this};
}
C3DFileAdapter::Tables
C3DFileAdapter::read(const std::string& fileName) {
auto abstables = C3DFileAdapter{}.extendRead(fileName);
auto marker_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers));
auto force_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces));
Tables tables{};
tables.emplace(_markers, marker_table);
tables.emplace( _forces, force_table);
return tables;
}
void
C3DFileAdapter::write(const C3DFileAdapter::Tables& tables,
const std::string& fileName) {
throw Exception{"Writing C3D not supported yet."};
}
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
auto reader = btk::AcquisitionFileReader::New();
reader->SetFilename(fileName);
reader->Update();
auto acquisition = reader->GetOutput();
EventTable event_table{};
auto events = acquisition->GetEvents();
for (auto it = events->Begin();
it != events->End();
++it) {
auto et = *it;
event_table.push_back({ et->GetLabel(),
et->GetTime(),
et->GetFrame(),
et->GetDescription() });
}
OutputTables tables{};
auto marker_pts = btk::PointCollection::New();
for(auto it = acquisition->BeginPoint();
it != acquisition->EndPoint();
++it) {
auto pt = *it;
if(pt->GetType() == btk::Point::Marker)
marker_pts->InsertItem(pt);
}
if(marker_pts->GetItemNumber() != 0) {
int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber();
int marker_ncol = marker_pts->GetItemNumber();
std::vector<double> marker_times(marker_nrow);
SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol);
std::vector<std::string> marker_labels{};
for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) {
marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel()));
}
double time_step{1.0 / acquisition->GetPointFrequency()};
for(int f = 0; f < marker_pts->GetFrontItem()->GetFrameNumber(); ++f) {
SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()};
int m{0};
for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) {
auto pt = *it;
row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0),
pt->GetValues().coeff(f, 1),
pt->GetValues().coeff(f, 2)};
}
marker_matrix.updRow(f) = row;
marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
}
// Create the data
auto& marker_table = *new
TimeSeriesTableVec3(marker_times, marker_matrix, marker_labels);
marker_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetPointFrequency()));
marker_table.
updTableMetaData().
setValueForKey("Units",
acquisition->GetPointUnit());
marker_table.updTableMetaData().setValueForKey("events", event_table);
tables.emplace(_markers,
std::shared_ptr<TimeSeriesTableVec3>(&marker_table));
}
// This is probably the right way to get the raw forces data from force
// platforms. Extract the collection of force platforms.
auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
force_platforms_extractor->SetInput(acquisition);
auto force_platform_collection = force_platforms_extractor->GetOutput();
force_platforms_extractor->Update();
std::vector<SimTK::Matrix_<double>> fpCalMatrices{};
std::vector<SimTK::Matrix_<double>> fpCorners{};
std::vector<SimTK::Matrix_<double>> fpOrigins{};
std::vector<unsigned> fpTypes{};
auto fp_force_pts = btk::PointCollection::New();
auto fp_moment_pts = btk::PointCollection::New();
auto fp_position_pts = btk::PointCollection::New();
for(auto platform = force_platform_collection->Begin();
platform != force_platform_collection->End();
++platform) {
const auto& calMatrix = (*platform)->GetCalMatrix();
const auto& corners = (*platform)->GetCorners();
const auto& origins = (*platform)->GetOrigin();
fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix));
fpCorners.push_back(convertToSimtkMatrix(corners));
fpOrigins.push_back(convertToSimtkMatrix(origins));
fpTypes.push_back(static_cast<unsigned>((*platform)->GetType()));
// Get ground reaction wrenches for the force platform.
auto ground_reaction_wrench_filter =
btk::GroundReactionWrenchFilter::New();
ground_reaction_wrench_filter->SetInput(*platform);
auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
ground_reaction_wrench_filter->Update();
for(auto wrench = wrench_collection->Begin();
wrench != wrench_collection->End();
++wrench) {
// Forces time series.
fp_force_pts->InsertItem((*wrench)->GetForce());
// Moment time series.
fp_moment_pts->InsertItem((*wrench)->GetMoment());
// Position time series.
fp_position_pts->InsertItem((*wrench)->GetPosition());
}
}
if(fp_force_pts->GetItemNumber() != 0) {
std::vector<std::string> labels{};
ValueArray<std::string> units{};
for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
auto fp_str = std::to_string(fp);
labels.push_back(SimTK::Value<std::string>("f" + fp_str));
auto force_unit = acquisition->GetPointUnits().
at(_unit_index.at("force"));
units.upd().push_back(SimTK::Value<std::string>(force_unit));
labels.push_back(SimTK::Value<std::string>("m" + fp_str));
auto moment_unit = acquisition->GetPointUnits().
at(_unit_index.at("moment"));
units.upd().push_back(SimTK::Value<std::string>(moment_unit));
labels.push_back(SimTK::Value<std::string>("p" + fp_str));
auto position_unit = acquisition->GetPointUnits().
at(_unit_index.at("marker"));
units.upd().push_back(SimTK::Value<std::string>(position_unit));
}
const size_t nf = fp_force_pts->GetFrontItem()->GetFrameNumber();
std::vector<double> force_times(nf);
SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, labels.size());
double time_step{1.0 / acquisition->GetAnalogFrequency()};
for(int f = 0; f < static_cast<int>(nf); ++f) {
SimTK::RowVector_<SimTK::Vec3>
row{fp_force_pts->GetItemNumber() * 3};
int col{0};
for(auto fit = fp_force_pts->Begin(),
mit = fp_moment_pts->Begin(),
pit = fp_position_pts->Begin();
fit != fp_force_pts->End();
++fit,
++mit,
++pit) {
row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
(*fit)->GetValues().coeff(f, 1),
(*fit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
(*mit)->GetValues().coeff(f, 1),
(*mit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
(*pit)->GetValues().coeff(f, 1),
(*pit)->GetValues().coeff(f, 2)};
++col;
}
force_matrix.updRow(f) = row;
force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
}
auto& force_table =
*(new TimeSeriesTableVec3(force_times, force_matrix, labels));
TimeSeriesTableVec3::DependentsMetaData force_dep_metadata
= force_table.getDependentsMetaData();
// add units to the dependent meta data
force_dep_metadata.setValueArrayForKey("units", units);
force_table.setDependentsMetaData(force_dep_metadata);
force_table.
updTableMetaData().
setValueForKey("CalibrationMatrices", std::move(fpCalMatrices));
force_table.
updTableMetaData().
setValueForKey("Corners", std::move(fpCorners));
force_table.
updTableMetaData().
setValueForKey("Origins", std::move(fpOrigins));
force_table.
updTableMetaData().
setValueForKey("Types", std::move(fpTypes));
force_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetAnalogFrequency()));
tables.emplace(_forces,
std::shared_ptr<TimeSeriesTableVec3>(&force_table));
force_table.updTableMetaData().setValueForKey("events", event_table);
}
return tables;
}
void
C3DFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
throw Exception{"Writing to C3D not supported yet."};
}
} // namespace OpenSim
|
#include "C3DFileAdapter.h"
#include "btkAcquisitionFileReader.h"
#include "btkAcquisition.h"
#include "btkForcePlatformsExtractor.h"
#include "btkGroundReactionWrenchFilter.h"
namespace {
// Function to convert Eigen matrix to SimTK matrix. This can become a lambda
// funciton inside extendRead in future.
template<typename _Scalar, int _Rows, int _Cols>
SimTK::Matrix_<double>
convertToSimtkMatrix(const Eigen::Matrix<_Scalar, _Rows, _Cols>&
eigenMat) {
SimTK::Matrix_<double> simtkMat{static_cast<int>(eigenMat.rows()),
static_cast<int>(eigenMat.cols())};
for(int r = 0; r < eigenMat.rows(); ++r)
for(int c = 0; c < eigenMat.cols(); ++c)
simtkMat(r, c) = eigenMat(r, c);
return simtkMat;
}
} // anonymous namespace
namespace OpenSim {
const std::string C3DFileAdapter::_markers{"markers"};
const std::string C3DFileAdapter::_forces{"forces"};
const std::unordered_map<std::string, size_t>
C3DFileAdapter::_unit_index{{"marker", 0},
{"angle" , 1},
{"force" , 2},
{"moment", 3},
{"power" , 4},
{"scalar", 5}};
C3DFileAdapter*
C3DFileAdapter::clone() const {
return new C3DFileAdapter{*this};
}
C3DFileAdapter::Tables
C3DFileAdapter::read(const std::string& fileName) {
auto abstables = C3DFileAdapter{}.extendRead(fileName);
auto marker_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_markers));
auto force_table =
std::static_pointer_cast<TimeSeriesTableVec3>(abstables.at(_forces));
Tables tables{};
tables.emplace(_markers, marker_table);
tables.emplace( _forces, force_table);
return tables;
}
void
C3DFileAdapter::write(const C3DFileAdapter::Tables& tables,
const std::string& fileName) {
throw Exception{"Writing C3D not supported yet."};
}
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
auto reader = btk::AcquisitionFileReader::New();
reader->SetFilename(fileName);
reader->Update();
auto acquisition = reader->GetOutput();
EventTable event_table{};
auto events = acquisition->GetEvents();
for (auto it = events->Begin();
it != events->End();
++it) {
auto et = *it;
event_table.push_back({ et->GetLabel(),
et->GetTime(),
et->GetFrame(),
et->GetDescription() });
}
OutputTables tables{};
auto marker_pts = btk::PointCollection::New();
for(auto it = acquisition->BeginPoint();
it != acquisition->EndPoint();
++it) {
auto pt = *it;
if(pt->GetType() == btk::Point::Marker)
marker_pts->InsertItem(pt);
}
if(marker_pts->GetItemNumber() != 0) {
int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber();
int marker_ncol = marker_pts->GetItemNumber();
std::vector<double> marker_times(marker_nrow);
SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol);
std::vector<std::string> marker_labels{};
for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) {
marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel()));
}
double time_step{1.0 / acquisition->GetPointFrequency()};
for(int f = 0; f < marker_nrow; ++f) {
SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()};
int m{0};
for(auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) {
auto pt = *it;
row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0),
pt->GetValues().coeff(f, 1),
pt->GetValues().coeff(f, 2)};
}
marker_matrix.updRow(f) = row;
marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
}
// Create the data
auto& marker_table = *new
TimeSeriesTableVec3(marker_times, marker_matrix, marker_labels);
marker_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetPointFrequency()));
marker_table.
updTableMetaData().
setValueForKey("Units",
acquisition->GetPointUnit());
marker_table.updTableMetaData().setValueForKey("events", event_table);
tables.emplace(_markers,
std::shared_ptr<TimeSeriesTableVec3>(&marker_table));
}
// This is probably the right way to get the raw forces data from force
// platforms. Extract the collection of force platforms.
auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
force_platforms_extractor->SetInput(acquisition);
auto force_platform_collection = force_platforms_extractor->GetOutput();
force_platforms_extractor->Update();
std::vector<SimTK::Matrix_<double>> fpCalMatrices{};
std::vector<SimTK::Matrix_<double>> fpCorners{};
std::vector<SimTK::Matrix_<double>> fpOrigins{};
std::vector<unsigned> fpTypes{};
auto fp_force_pts = btk::PointCollection::New();
auto fp_moment_pts = btk::PointCollection::New();
auto fp_position_pts = btk::PointCollection::New();
for(auto platform = force_platform_collection->Begin();
platform != force_platform_collection->End();
++platform) {
const auto& calMatrix = (*platform)->GetCalMatrix();
const auto& corners = (*platform)->GetCorners();
const auto& origins = (*platform)->GetOrigin();
fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix));
fpCorners.push_back(convertToSimtkMatrix(corners));
fpOrigins.push_back(convertToSimtkMatrix(origins));
fpTypes.push_back(static_cast<unsigned>((*platform)->GetType()));
// Get ground reaction wrenches for the force platform.
auto ground_reaction_wrench_filter =
btk::GroundReactionWrenchFilter::New();
ground_reaction_wrench_filter->SetInput(*platform);
auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
ground_reaction_wrench_filter->Update();
for(auto wrench = wrench_collection->Begin();
wrench != wrench_collection->End();
++wrench) {
// Forces time series.
fp_force_pts->InsertItem((*wrench)->GetForce());
// Moment time series.
fp_moment_pts->InsertItem((*wrench)->GetMoment());
// Position time series.
fp_position_pts->InsertItem((*wrench)->GetPosition());
}
}
if(fp_force_pts->GetItemNumber() != 0) {
std::vector<std::string> labels{};
ValueArray<std::string> units{};
for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
auto fp_str = std::to_string(fp);
labels.push_back(SimTK::Value<std::string>("f" + fp_str));
auto force_unit = acquisition->GetPointUnits().
at(_unit_index.at("force"));
units.upd().push_back(SimTK::Value<std::string>(force_unit));
labels.push_back(SimTK::Value<std::string>("m" + fp_str));
auto moment_unit = acquisition->GetPointUnits().
at(_unit_index.at("moment"));
units.upd().push_back(SimTK::Value<std::string>(moment_unit));
labels.push_back(SimTK::Value<std::string>("p" + fp_str));
auto position_unit = acquisition->GetPointUnits().
at(_unit_index.at("marker"));
units.upd().push_back(SimTK::Value<std::string>(position_unit));
}
const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber();
std::vector<double> force_times(nf);
SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, labels.size());
double time_step{1.0 / acquisition->GetAnalogFrequency()};
for(int f = 0; f < nf; ++f) {
SimTK::RowVector_<SimTK::Vec3>
row{fp_force_pts->GetItemNumber() * 3};
int col{0};
for(auto fit = fp_force_pts->Begin(),
mit = fp_moment_pts->Begin(),
pit = fp_position_pts->Begin();
fit != fp_force_pts->End();
++fit,
++mit,
++pit) {
row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
(*fit)->GetValues().coeff(f, 1),
(*fit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
(*mit)->GetValues().coeff(f, 1),
(*mit)->GetValues().coeff(f, 2)};
++col;
row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
(*pit)->GetValues().coeff(f, 1),
(*pit)->GetValues().coeff(f, 2)};
++col;
}
force_matrix.updRow(f) = row;
force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
}
auto& force_table =
*(new TimeSeriesTableVec3(force_times, force_matrix, labels));
TimeSeriesTableVec3::DependentsMetaData force_dep_metadata
= force_table.getDependentsMetaData();
// add units to the dependent meta data
force_dep_metadata.setValueArrayForKey("units", units);
force_table.setDependentsMetaData(force_dep_metadata);
force_table.
updTableMetaData().
setValueForKey("CalibrationMatrices", std::move(fpCalMatrices));
force_table.
updTableMetaData().
setValueForKey("Corners", std::move(fpCorners));
force_table.
updTableMetaData().
setValueForKey("Origins", std::move(fpOrigins));
force_table.
updTableMetaData().
setValueForKey("Types", std::move(fpTypes));
force_table.
updTableMetaData().
setValueForKey("DataRate",
std::to_string(acquisition->GetAnalogFrequency()));
tables.emplace(_forces,
std::shared_ptr<TimeSeriesTableVec3>(&force_table));
force_table.updTableMetaData().setValueForKey("events", event_table);
}
return tables;
}
void
C3DFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
throw Exception{"Writing to C3D not supported yet."};
}
} // namespace OpenSim
|
Make nf an int and use marker_nrow for number of marker frames.
|
Make nf an int and use marker_nrow for number of marker frames.
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
aa1ccd9672ce3b36c5e532e6f4a0ac2286b688cb
|
rx64m_uart_sample/main.cpp
|
rx64m_uart_sample/main.cpp
|
//=====================================================================//
/*! @file
@brief RX64M UART(SCI1)サンプル @n
・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "RX64M/rtc.hpp"
#include "common/delay.hpp"
namespace {
void wait_delay_(uint32_t n)
{
// とりあえず無駄ループ
for(uint32_t i = 0; i < n; ++i) {
asm("nop");
}
}
class cmt_task {
public:
void operator() () {
}
};
device::cmt_io<device::CMT0, cmt_task> cmt_;
typedef utils::fifo<uint8_t, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可
device::SYSTEM::MOSCWTCR = 9; // 1ms wait
// メインクロック強制発振とドライブ能力設定
device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
| device::SYSTEM::MOFCR.MOFXIN.b();
device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作
wait_delay_(5000);
device::SYSTEM::PLLCR.STC = 0b010011; // PLL 10 倍(120MHz)
device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作
wait_delay_(5000);
device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (120/1=120)
| device::SYSTEM::SCKCR.BCK.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (120/1=120)
| device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKC.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60)
device::SYSTEM::SCKCR2.UCK = 0b0100; // USB Clock: 1/5 (120/5=24)
device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択
// タイマー設定(60Hz)
uint8_t cmt_irq_level = 4;
cmt_.start(60, cmt_irq_level);
// SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
utils::format("RX64M start\n");
device::PORT0::PDR.B5 = 1;
device::PORT0::PDR.B7 = 1;
uint32_t cnt = 0;
uint32_t n = 0;
while(1) {
cmt_.sync();
if(sci_.recv_length()) {
auto ch = sci_.getch();
sci_.putch(ch);
}
++cnt;
if(cnt >= 30) {
cnt = 0;
}
device::PORT0::PODR.B7 = (cnt < 10) ? 0 : 1;
utils::delay::micro_second(1);
device::PORT0::PODR.B5 = 0;
utils::delay::micro_second(1);
device::PORT0::PODR.B5 = 1;
if((n % 60) == 0) {
utils::format("%d\n") % (n / 60);
}
++n;
}
}
|
//=====================================================================//
/*! @file
@brief RX64M UART(SCI1)サンプル @n
・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "common/sci_io.hpp"
#include "common/cmt_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "RX64M/rtc.hpp"
#include "common/delay.hpp"
namespace {
class cmt_task {
public:
void operator() () {
}
};
device::cmt_io<device::CMT0, cmt_task> cmt_;
typedef utils::fifo<uint8_t, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
}
extern "C" {
void sci_putch(char ch)
{
sci_.putch(ch);
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可
device::SYSTEM::MOSCWTCR = 9; // 1ms wait
// メインクロック強制発振とドライブ能力設定
device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
| device::SYSTEM::MOFCR.MOFXIN.b();
device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作
while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");
device::SYSTEM::PLLCR.STC = 0b010011; // PLL 10 倍(120MHz)
device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作
while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");
device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (120/1=120)
| device::SYSTEM::SCKCR.BCK.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (120/1=120)
| device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKC.b(1) // 1/2 (120/2=60)
| device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60)
device::SYSTEM::SCKCR2.UCK = 0b0100; // USB Clock: 1/5 (120/5=24)
device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択
// タイマー設定(60Hz)
uint8_t cmt_irq_level = 4;
cmt_.start(60, cmt_irq_level);
// SCI 設定
static const uint8_t sci_level = 2;
sci_.start(115200, sci_level);
utils::format("RX64M start\n");
device::PORT0::PDR.B5 = 1;
device::PORT0::PDR.B7 = 1;
uint32_t cnt = 0;
uint32_t n = 0;
while(1) {
cmt_.sync();
if(sci_.recv_length()) {
auto ch = sci_.getch();
sci_.putch(ch);
}
++cnt;
if(cnt >= 30) {
cnt = 0;
}
device::PORT0::PODR.B7 = (cnt < 10) ? 0 : 1;
utils::delay::micro_second(1);
device::PORT0::PODR.B5 = 0;
utils::delay::micro_second(1);
device::PORT0::PODR.B5 = 1;
if((n % 60) == 0) {
utils::format("%d\n") % (n / 60);
}
++n;
}
}
|
update clock wait
|
update clock wait
|
C++
|
bsd-3-clause
|
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
|
2ad053b19e8a45d6a2e4ee99048039d2ea79dc97
|
t/atomic_ptr_test.cc
|
t/atomic_ptr_test.cc
|
#include "config.h"
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include "atomic.hh"
#include "locks.hh"
#include "threadtests.hh"
#define NUM_THREADS 50
#define NUM_TIMES 1000000
class Doodad : public RCValue {
public:
Doodad() {
numInstances++;
}
Doodad(const Doodad& src) : RCValue(src) {
numInstances++;
}
~Doodad() {
numInstances--;
}
static int getNumInstances() {
return numInstances;
}
private:
static Atomic<int> numInstances;
};
Atomic<int> Doodad::numInstances(0);
class AtomicPtrTest : public Generator<bool> {
public:
AtomicPtrTest(RCPtr<Doodad> *p) : ptr(p) {}
bool operator()() {
for (int i = 0; i < NUM_TIMES; ++i) {
switch (rand() % 7) {
case 0:
ptr->reset(new Doodad);
break;
case 1:
{
RCPtr<Doodad> d(new Doodad);
ptr->reset(d);
}
break;
case 2:
{
RCPtr<Doodad> d(new Doodad);
d.reset();
}
break;
case 3:
{
RCPtr<Doodad> d(*ptr);
d.reset();
}
break;
case 4:
{
while (true) {
RCPtr<Doodad> d1(*ptr);
RCPtr<Doodad> d2(new Doodad(*d1));
if (ptr->cas(d1, d2)) {
break;
}
}
}
break;
case 5:
ptr->reset(new Doodad);
break;
case 6:
{
RCPtr<Doodad> d(*ptr);
d.reset(new Doodad);
}
break;
default:
assert(false);
}
}
return true;
}
private:
RCPtr<Doodad> *ptr;
};
static void testAtomicPtr() {
// Just do a bunch.
RCPtr<Doodad> dd;
AtomicPtrTest *testGen = new AtomicPtrTest(&dd);
getCompletedThreads<bool>(NUM_THREADS, testGen);
delete testGen;
dd.reset();
assert(Doodad::getNumInstances() == 0);
}
static void testOperators() {
RCPtr<Doodad> dd;
assert(!dd);
dd.reset(new Doodad);
assert(dd);
dd.reset();
assert(!dd);
Doodad *d = new Doodad;
dd.reset(d);
assert((void*)(d) == (void*)(&(*dd)));
dd.reset();
assert(Doodad::getNumInstances() == 0);
}
int main() {
alarm(60);
testOperators();
testAtomicPtr();
}
|
#include "config.h"
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include "atomic.hh"
#include "locks.hh"
#include "threadtests.hh"
#define NUM_THREADS 50
#define NUM_TIMES 100000
class Doodad : public RCValue {
public:
Doodad() {
numInstances++;
}
Doodad(const Doodad& src) : RCValue(src) {
numInstances++;
}
~Doodad() {
numInstances--;
}
static int getNumInstances() {
return numInstances;
}
private:
static Atomic<int> numInstances;
};
Atomic<int> Doodad::numInstances(0);
class AtomicPtrTest : public Generator<bool> {
public:
AtomicPtrTest(RCPtr<Doodad> *p) : ptr(p) {}
bool operator()() {
for (int i = 0; i < NUM_TIMES; ++i) {
switch (rand() % 7) {
case 0:
ptr->reset(new Doodad);
break;
case 1:
{
RCPtr<Doodad> d(new Doodad);
ptr->reset(d);
}
break;
case 2:
{
RCPtr<Doodad> d(new Doodad);
d.reset();
}
break;
case 3:
{
RCPtr<Doodad> d(*ptr);
d.reset();
}
break;
case 4:
{
while (true) {
RCPtr<Doodad> d1(*ptr);
RCPtr<Doodad> d2(new Doodad(*d1));
if (ptr->cas(d1, d2)) {
break;
}
}
}
break;
case 5:
ptr->reset(new Doodad);
break;
case 6:
{
RCPtr<Doodad> d(*ptr);
d.reset(new Doodad);
}
break;
default:
assert(false);
}
}
return true;
}
private:
RCPtr<Doodad> *ptr;
};
static void testAtomicPtr() {
// Just do a bunch.
RCPtr<Doodad> dd;
AtomicPtrTest *testGen = new AtomicPtrTest(&dd);
getCompletedThreads<bool>(NUM_THREADS, testGen);
delete testGen;
dd.reset();
assert(Doodad::getNumInstances() == 0);
}
static void testOperators() {
RCPtr<Doodad> dd;
assert(!dd);
dd.reset(new Doodad);
assert(dd);
dd.reset();
assert(!dd);
Doodad *d = new Doodad;
dd.reset(d);
assert((void*)(d) == (void*)(&(*dd)));
dd.reset();
assert(Doodad::getNumInstances() == 0);
}
int main() {
alarm(60);
testOperators();
testAtomicPtr();
}
|
Reduce atomic_ptr_test by 10x rounds so it can complete.
|
Reduce atomic_ptr_test by 10x rounds so it can complete.
(on slow machines)
Change-Id: Ice62f37a5a43790308efe0f62e8c54dea0958f48
Reviewed-on: http://review.northscale.com/2409
Reviewed-by: Dustin Sallings <[email protected]>
Tested-by: Dustin Sallings <[email protected]>
|
C++
|
apache-2.0
|
daverigby/ep-engine,membase/ep-engine,jimwwalker/ep-engine,teligent-ru/ep-engine,owendCB/ep-engine,sriganes/ep-engine,sriganes/ep-engine,membase/ep-engine,zbase/ep-engine,abhinavdangeti/ep-engine,daverigby/kv_engine,zbase/ep-engine,couchbaselabs/ep-engine,membase/ep-engine,teligent-ru/ep-engine,abhinavdangeti/ep-engine,owendCB/ep-engine,zbase/ep-engine,couchbaselabs/ep-engine,couchbase/ep-engine,teligent-ru/ep-engine,jimwwalker/ep-engine,membase/ep-engine,teligent-ru/ep-engine,couchbase/ep-engine,owendCB/ep-engine,owendCB/ep-engine,sriganes/ep-engine,hisundar/ep-engine,abhinavdangeti/ep-engine,hisundar/ep-engine,daverigby/kv_engine,abhinavdangeti/ep-engine,couchbaselabs/ep-engine,zbase/ep-engine,couchbaselabs/ep-engine,sriganes/ep-engine,couchbase/ep-engine,hisundar/ep-engine,daverigby/ep-engine,daverigby/ep-engine,couchbaselabs/ep-engine,couchbase/ep-engine,jimwwalker/ep-engine,daverigby/kv_engine,daverigby/kv_engine,zbase/ep-engine,abhinavdangeti/ep-engine,daverigby/ep-engine,jimwwalker/ep-engine,hisundar/ep-engine
|
7390798b5bbb469e5557b5013aea5af8fc7f6606
|
src/plugins/imageviewer/imageview.cpp
|
src/plugins/imageviewer/imageview.cpp
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Qt Creator.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "imageview.h"
#include <QtCore/QFile>
#include <QtGui/QWheelEvent>
#include <QtGui/QMouseEvent>
#include <QtGui/QGraphicsRectItem>
#include <QtGui/QPixmap>
#include <QtSvg/QGraphicsSvgItem>
#include <QtGui/QImageReader>
#include <qmath.h>
namespace ImageViewer {
namespace Constants {
const qreal DEFAULT_SCALE_FACTOR = 1.2;
}
namespace Internal {
struct ImageViewPrivate
{
ImageViewPrivate() : imageItem(0), backgroundItem(0), outlineItem(0) {}
QGraphicsItem *imageItem;
QGraphicsRectItem *backgroundItem;
QGraphicsRectItem *outlineItem;
};
ImageView::ImageView(QWidget *parent)
: QGraphicsView(parent),
d_ptr(new ImageViewPrivate())
{
setScene(new QGraphicsScene(this));
setTransformationAnchor(AnchorUnderMouse);
setDragMode(ScrollHandDrag);
setViewportUpdateMode(FullViewportUpdate);
setFrameShape(QFrame::NoFrame);
// Prepare background check-board pattern
QPixmap tilePixmap(64, 64);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, 0x20, 0x20, color);
tilePainter.fillRect(0x20, 0x20, 0x20, 0x20, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
}
ImageView::~ImageView()
{
}
void ImageView::drawBackground(QPainter *p, const QRectF &)
{
p->save();
p->resetTransform();
p->drawTiledPixmap(viewport()->rect(), backgroundBrush().texture());
p->restore();
}
bool ImageView::openFile(QString fileName)
{
bool isSvg = false;
QByteArray format = QImageReader::imageFormat(fileName);
// if it is impossible to recognize a file format - file will not be open correctly
if (format.isEmpty())
return false;
if (format.startsWith("svg"))
isSvg = true;
QGraphicsScene *s = scene();
bool drawBackground = (d_ptr->backgroundItem ? d_ptr->backgroundItem->isVisible() : false);
bool drawOutline = (d_ptr->outlineItem ? d_ptr->outlineItem->isVisible() : true);
s->clear();
resetTransform();
// image
if (isSvg) {
d_ptr->imageItem = new QGraphicsSvgItem(fileName);
} else {
QPixmap pixmap(fileName);
d_ptr->imageItem = new QGraphicsPixmapItem(pixmap);
}
d_ptr->imageItem->setFlags(QGraphicsItem::ItemClipsToShape);
d_ptr->imageItem->setCacheMode(QGraphicsItem::NoCache);
d_ptr->imageItem->setZValue(0);
// background item
d_ptr->backgroundItem = new QGraphicsRectItem(d_ptr->imageItem->boundingRect());
d_ptr->backgroundItem->setBrush(Qt::white);
d_ptr->backgroundItem->setPen(Qt::NoPen);
d_ptr->backgroundItem->setVisible(drawBackground);
d_ptr->backgroundItem->setZValue(-1);
// outline
d_ptr->outlineItem = new QGraphicsRectItem(d_ptr->imageItem->boundingRect());
QPen outline(Qt::black, 1, Qt::DashLine);
outline.setCosmetic(true);
d_ptr->outlineItem->setPen(outline);
d_ptr->outlineItem->setBrush(Qt::NoBrush);
d_ptr->outlineItem->setVisible(drawOutline);
d_ptr->outlineItem->setZValue(1);
s->addItem(d_ptr->backgroundItem);
s->addItem(d_ptr->imageItem);
s->addItem(d_ptr->outlineItem);
// if image size is 0x0, then it is not loaded
if (d_ptr->imageItem->boundingRect().height() == 0 && d_ptr->imageItem->boundingRect().width() == 0)
return false;
emitScaleFactor();
return true;
}
void ImageView::setViewBackground(bool enable)
{
if (!d_ptr->backgroundItem)
return;
d_ptr->backgroundItem->setVisible(enable);
}
void ImageView::setViewOutline(bool enable)
{
if (!d_ptr->outlineItem)
return;
d_ptr->outlineItem->setVisible(enable);
}
void ImageView::doScale(qreal factor)
{
scale(factor, factor);
emitScaleFactor();
}
void ImageView::wheelEvent(QWheelEvent *event)
{
qreal factor = qPow(Constants::DEFAULT_SCALE_FACTOR, event->delta() / 240.0);
doScale(factor);
event->accept();
}
void ImageView::zoomIn()
{
doScale(Constants::DEFAULT_SCALE_FACTOR);
}
void ImageView::zoomOut()
{
doScale(1. / Constants::DEFAULT_SCALE_FACTOR);
}
void ImageView::resetToOriginalSize()
{
resetTransform();
emitScaleFactor();
}
void ImageView::fitToScreen()
{
fitInView(d_ptr->imageItem, Qt::KeepAspectRatio);
emitScaleFactor();
}
void ImageView::emitScaleFactor()
{
// get scale factor directly from the transform matrix
qreal factor = transform().m11();
emit scaleFactorChanged(factor);
}
} // namespace Internal
} // namespace ImageView
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Qt Creator.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "imageview.h"
#include <QtCore/QFile>
#include <QtGui/QWheelEvent>
#include <QtGui/QMouseEvent>
#include <QtGui/QGraphicsRectItem>
#include <QtGui/QPixmap>
#include <QtSvg/QGraphicsSvgItem>
#include <QtGui/QImageReader>
#include <qmath.h>
namespace ImageViewer {
namespace Constants {
const qreal DEFAULT_SCALE_FACTOR = 1.2;
}
namespace Internal {
struct ImageViewPrivate
{
ImageViewPrivate() : imageItem(0), backgroundItem(0), outlineItem(0) {}
QGraphicsItem *imageItem;
QGraphicsRectItem *backgroundItem;
QGraphicsRectItem *outlineItem;
};
ImageView::ImageView(QWidget *parent)
: QGraphicsView(parent),
d_ptr(new ImageViewPrivate())
{
setScene(new QGraphicsScene(this));
setTransformationAnchor(AnchorUnderMouse);
setDragMode(ScrollHandDrag);
setViewportUpdateMode(FullViewportUpdate);
setFrameShape(QFrame::NoFrame);
setRenderHint(QPainter::SmoothPixmapTransform);
// Prepare background check-board pattern
QPixmap tilePixmap(64, 64);
tilePixmap.fill(Qt::white);
QPainter tilePainter(&tilePixmap);
QColor color(220, 220, 220);
tilePainter.fillRect(0, 0, 0x20, 0x20, color);
tilePainter.fillRect(0x20, 0x20, 0x20, 0x20, color);
tilePainter.end();
setBackgroundBrush(tilePixmap);
}
ImageView::~ImageView()
{
}
void ImageView::drawBackground(QPainter *p, const QRectF &)
{
p->save();
p->resetTransform();
p->drawTiledPixmap(viewport()->rect(), backgroundBrush().texture());
p->restore();
}
bool ImageView::openFile(QString fileName)
{
bool isSvg = false;
QByteArray format = QImageReader::imageFormat(fileName);
// if it is impossible to recognize a file format - file will not be open correctly
if (format.isEmpty())
return false;
if (format.startsWith("svg"))
isSvg = true;
QGraphicsScene *s = scene();
bool drawBackground = (d_ptr->backgroundItem ? d_ptr->backgroundItem->isVisible() : false);
bool drawOutline = (d_ptr->outlineItem ? d_ptr->outlineItem->isVisible() : true);
s->clear();
resetTransform();
// image
if (isSvg) {
d_ptr->imageItem = new QGraphicsSvgItem(fileName);
} else {
QPixmap pixmap(fileName);
QGraphicsPixmapItem *pixmapItem = new QGraphicsPixmapItem(pixmap);
pixmapItem->setTransformationMode(Qt::SmoothTransformation);
d_ptr->imageItem = pixmapItem;
}
d_ptr->imageItem->setFlags(QGraphicsItem::ItemClipsToShape);
d_ptr->imageItem->setCacheMode(QGraphicsItem::NoCache);
d_ptr->imageItem->setZValue(0);
// background item
d_ptr->backgroundItem = new QGraphicsRectItem(d_ptr->imageItem->boundingRect());
d_ptr->backgroundItem->setBrush(Qt::white);
d_ptr->backgroundItem->setPen(Qt::NoPen);
d_ptr->backgroundItem->setVisible(drawBackground);
d_ptr->backgroundItem->setZValue(-1);
// outline
d_ptr->outlineItem = new QGraphicsRectItem(d_ptr->imageItem->boundingRect());
QPen outline(Qt::black, 1, Qt::DashLine);
outline.setCosmetic(true);
d_ptr->outlineItem->setPen(outline);
d_ptr->outlineItem->setBrush(Qt::NoBrush);
d_ptr->outlineItem->setVisible(drawOutline);
d_ptr->outlineItem->setZValue(1);
s->addItem(d_ptr->backgroundItem);
s->addItem(d_ptr->imageItem);
s->addItem(d_ptr->outlineItem);
// if image size is 0x0, then it is not loaded
if (d_ptr->imageItem->boundingRect().height() == 0 && d_ptr->imageItem->boundingRect().width() == 0)
return false;
emitScaleFactor();
return true;
}
void ImageView::setViewBackground(bool enable)
{
if (!d_ptr->backgroundItem)
return;
d_ptr->backgroundItem->setVisible(enable);
}
void ImageView::setViewOutline(bool enable)
{
if (!d_ptr->outlineItem)
return;
d_ptr->outlineItem->setVisible(enable);
}
void ImageView::doScale(qreal factor)
{
scale(factor, factor);
emitScaleFactor();
}
void ImageView::wheelEvent(QWheelEvent *event)
{
qreal factor = qPow(Constants::DEFAULT_SCALE_FACTOR, event->delta() / 240.0);
doScale(factor);
event->accept();
}
void ImageView::zoomIn()
{
doScale(Constants::DEFAULT_SCALE_FACTOR);
}
void ImageView::zoomOut()
{
doScale(1. / Constants::DEFAULT_SCALE_FACTOR);
}
void ImageView::resetToOriginalSize()
{
resetTransform();
emitScaleFactor();
}
void ImageView::fitToScreen()
{
fitInView(d_ptr->imageItem, Qt::KeepAspectRatio);
emitScaleFactor();
}
void ImageView::emitScaleFactor()
{
// get scale factor directly from the transform matrix
qreal factor = transform().m11();
emit scaleFactorChanged(factor);
}
} // namespace Internal
} // namespace ImageView
|
Use smooth transformation
|
ImageViewer: Use smooth transformation
Merge-request: 2165
Reviewed-by: Thorbjørn Lindeijer <[email protected]>
|
C++
|
lgpl-2.1
|
jonnor/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,renatofilho/QtCreator,colede/qtcreator,Distrotech/qtcreator,malikcjm/qtcreator,richardmg/qtcreator,colede/qtcreator,ostash/qt-creator-i18n-uk,hdweiss/qt-creator-visualizer,azat/qtcreator,maui-packages/qt-creator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,pcacjr/qt-creator,farseerri/git_code,dmik/qt-creator-os2,bakaiadam/collaborative_qt_creator,richardmg/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,duythanhphan/qt-creator,kuba1/qtcreator,yinyunqiao/qtcreator,amyvmiwei/qt-creator,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,dmik/qt-creator-os2,richardmg/qtcreator,danimo/qt-creator,danimo/qt-creator,colede/qtcreator,richardmg/qtcreator,sandsmark/qtcreator-minimap,ostash/qt-creator-i18n-uk,farseerri/git_code,Distrotech/qtcreator,maui-packages/qt-creator,sandsmark/qtcreator-minimap,azat/qtcreator,danimo/qt-creator,sandsmark/qtcreator-minimap,duythanhphan/qt-creator,renatofilho/QtCreator,maui-packages/qt-creator,KDE/android-qt-creator,colede/qtcreator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,farseerri/git_code,xianian/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,azat/qtcreator,martyone/sailfish-qtcreator,KDE/android-qt-creator,pcacjr/qt-creator,darksylinc/qt-creator,darksylinc/qt-creator,darksylinc/qt-creator,farseerri/git_code,dmik/qt-creator-os2,hdweiss/qt-creator-visualizer,kuba1/qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,KDE/android-qt-creator,kuba1/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,azat/qtcreator,darksylinc/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,farseerri/git_code,danimo/qt-creator,omniacreator/qtcreator,yinyunqiao/qtcreator,danimo/qt-creator,yinyunqiao/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,omniacreator/qtcreator,malikcjm/qtcreator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,renatofilho/QtCreator,colede/qtcreator,renatofilho/QtCreator,syntheticpp/qt-creator,colede/qtcreator,KDAB/KDAB-Creator,renatofilho/QtCreator,KDE/android-qt-creator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,jonnor/qt-creator,KDAB/KDAB-Creator,danimo/qt-creator,renatofilho/QtCreator,ostash/qt-creator-i18n-uk,danimo/qt-creator,xianian/qt-creator,richardmg/qtcreator,farseerri/git_code,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,sandsmark/qtcreator-minimap,darksylinc/qt-creator,jonnor/qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,malikcjm/qtcreator,yinyunqiao/qtcreator,syntheticpp/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,ostash/qt-creator-i18n-uk,dmik/qt-creator-os2,danimo/qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,bakaiadam/collaborative_qt_creator,dmik/qt-creator-os2,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,bakaiadam/collaborative_qt_creator,farseerri/git_code,bakaiadam/collaborative_qt_creator,syntheticpp/qt-creator,duythanhphan/qt-creator,pcacjr/qt-creator,richardmg/qtcreator,sandsmark/qtcreator-minimap,AltarBeastiful/qt-creator,Distrotech/qtcreator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,malikcjm/qtcreator,richardmg/qtcreator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,pcacjr/qt-creator,ostash/qt-creator-i18n-uk,farseerri/git_code,pcacjr/qt-creator,yinyunqiao/qtcreator,yinyunqiao/qtcreator,jonnor/qt-creator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,azat/qtcreator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,omniacreator/qtcreator,KDAB/KDAB-Creator,KDAB/KDAB-Creator,duythanhphan/qt-creator,duythanhphan/qt-creator,colede/qtcreator,jonnor/qt-creator,azat/qtcreator,amyvmiwei/qt-creator,pcacjr/qt-creator,KDE/android-qt-creator,omniacreator/qtcreator,malikcjm/qtcreator,maui-packages/qt-creator,syntheticpp/qt-creator,malikcjm/qtcreator,Distrotech/qtcreator,darksylinc/qt-creator,yinyunqiao/qtcreator,dmik/qt-creator-os2,kuba1/qtcreator,martyone/sailfish-qtcreator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,pcacjr/qt-creator,KDE/android-qt-creator,xianian/qt-creator
|
f6d4e6776ef4efb49b48ef6b0533668dc52fc84e
|
plugins/trace_api_plugin/trace_api_plugin.cpp
|
plugins/trace_api_plugin/trace_api_plugin.cpp
|
#include <eosio/trace_api_plugin/trace_api_plugin.hpp>
#include <eosio/trace_api_plugin/abi_data_handler.hpp>
#include <eosio/trace_api_plugin/request_handler.hpp>
#include <eosio/trace_api_plugin/configuration_utils.hpp>
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::configuration_utils;
namespace {
const std::string logger_name("trace_api");
fc::logger _log;
std::string to_detail_string(const std::exception_ptr& e) {
try {
std::rethrow_exception(e);
} catch (fc::exception& er) {
return er.to_detail_string();
} catch (const std::exception& e) {
fc::exception fce(
FC_LOG_MESSAGE(warn, "std::exception: ${what}: ", ("what", e.what())),
fc::std_exception_code,
BOOST_CORE_TYPEID(e).name(),
e.what());
return fce.to_detail_string();
} catch (...) {
fc::unhandled_exception ue(
FC_LOG_MESSAGE(warn, "unknown: ",),
std::current_exception());
return ue.to_detail_string();
}
}
void log_exception( const exception_with_context& e, fc::log_level level ) {
if( _log.is_enabled( level ) ) {
auto detail_string = to_detail_string(std::get<0>(e));
auto context = fc::log_context( level, std::get<1>(e), std::get<2>(e), std::get<3>(e) );
_log.log(fc::log_message( context, detail_string ));
}
}
}
namespace eosio {
/**
* A common source for information shared between the extraction process and the RPC process
*/
struct trace_api_common_impl {
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-dir", bpo::value<bfs::path>()->default_value("traces"),
"the location of the trace directory (absolute path or relative to application data dir)");
cfg_options("trace-slice-stride", bpo::value<uint32_t>()->default_value(10'000),
"the number of blocks each \"slice\" of trace data will contain on the filesystem");
}
void plugin_initialize(const appbase::variables_map& options) {
auto dir_option = options.at("trace-dir").as<bfs::path>();
if (dir_option.is_relative())
trace_dir = app().data_dir() / dir_option;
else
trace_dir = dir_option;
slice_stride = options.at("trace-slice-stride").as<uint32_t>();
}
// common configuration paramters
boost::filesystem::path trace_dir;
uint32_t slice_stride = 0;
};
/**
* Interface with the RPC process
*/
struct trace_api_rpc_plugin_impl {
trace_api_rpc_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-rpc-abi", bpo::value<vector<string>>()->composing(),
"ABIs used when decoding trace RPC responses, specified as \"Key=Value\" pairs in the form <account-name>=<abi-def>\n"
"Where <abi-def> can be:\n"
" a valid JSON-encoded ABI as a string\n"
" an absolute path to a file containing a valid JSON-encoded ABI\n"
" a relative path from `data-dir` to a file containing a valid JSON-encoded ABI\n"
);
cfg_options("trace-no-abis", "Suppress warning about ABIs when non are congigured");
}
void plugin_initialize(const appbase::variables_map& options) {
data_handler = std::make_shared<abi_data_handler>([](const exception_with_context& e){
log_exception(e, fc::log_level::debug);
});
if( options.count("trace-rpc-abi") ) {
const std::vector<std::string> key_value_pairs = options["trace-rpc-abi"].as<std::vector<std::string>>();
for (const auto& entry : key_value_pairs) {
try {
auto kv = parse_kv_pairs(entry);
auto account = chain::name(kv.first);
auto abi = abi_def_from_file_or_str(kv.second);
data_handler->add_abi(account, abi);
} catch (...) {
elog("Malformed trace-rpc-abi provider: \"${val}\"", ("val", entry));
throw;
}
}
} else if (options.count("trace-no-abis") == 0 ) {
wlog("Trace API is not configured with ABIs. Data in actions will appear as hex-encoded blobs in the RPC responses. Use trace-no-abis=true to suppress this warning.");
}
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
std::shared_ptr<abi_data_handler> data_handler;
};
struct trace_api_plugin_impl {
trace_api_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-minimum-irreversible-history-us", bpo::value<uint64_t>()->default_value(-1),
"the minimum amount of history, as defined by time, this node will keep after it becomes irreversible\n"
"this value can be specified as a number of microseconds or\n"
"a value of \"-1\" will disable automatic maintenance of the trace slice files\n"
);
}
void plugin_initialize(const appbase::variables_map& options) {
if( options.count("trace-minimum-irreversible-history-us") ) {
auto value = options.at("trace-minimum-irreversible-history-us").as<uint64_t>();
if ( value == -1 ) {
minimum_irreversible_trace_history = fc::microseconds::maximum();
} else if (value >= 0) {
minimum_irreversible_trace_history = fc::microseconds(value);
} else {
EOS_THROW(chain::plugin_config_exception, "trace-minimum-irreversible-history-us must be either a positive number or -1");
}
}
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
fc::microseconds minimum_irreversible_trace_history = fc::microseconds::maximum();
};
_trace_api_plugin::_trace_api_plugin()
{}
_trace_api_plugin::~_trace_api_plugin()
{}
void _trace_api_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_plugin_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void _trace_api_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
my = std::make_shared<trace_api_plugin_impl>(common);
my->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void _trace_api_plugin::plugin_startup() {
my->plugin_startup();
rpc->plugin_startup();
}
void _trace_api_plugin::plugin_shutdown() {
my->plugin_shutdown();
rpc->plugin_shutdown();
}
void _trace_api_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
trace_api_rpc_plugin::trace_api_rpc_plugin()
{}
trace_api_rpc_plugin::~trace_api_rpc_plugin()
{}
void trace_api_rpc_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_rpc_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_rpc_plugin::plugin_startup() {
rpc->plugin_startup();
}
void trace_api_rpc_plugin::plugin_shutdown() {
rpc->plugin_shutdown();
}
void trace_api_rpc_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
}
|
#include <eosio/trace_api_plugin/trace_api_plugin.hpp>
#include <eosio/trace_api_plugin/abi_data_handler.hpp>
#include <eosio/trace_api_plugin/request_handler.hpp>
#include <eosio/trace_api_plugin/configuration_utils.hpp>
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::configuration_utils;
namespace {
const std::string logger_name("trace_api");
fc::logger _log;
std::string to_detail_string(const std::exception_ptr& e) {
try {
std::rethrow_exception(e);
} catch (fc::exception& er) {
return er.to_detail_string();
} catch (const std::exception& e) {
fc::exception fce(
FC_LOG_MESSAGE(warn, "std::exception: ${what}: ", ("what", e.what())),
fc::std_exception_code,
BOOST_CORE_TYPEID(e).name(),
e.what());
return fce.to_detail_string();
} catch (...) {
fc::unhandled_exception ue(
FC_LOG_MESSAGE(warn, "unknown: ",),
std::current_exception());
return ue.to_detail_string();
}
}
void log_exception( const exception_with_context& e, fc::log_level level ) {
if( _log.is_enabled( level ) ) {
auto detail_string = to_detail_string(std::get<0>(e));
auto context = fc::log_context( level, std::get<1>(e), std::get<2>(e), std::get<3>(e) );
_log.log(fc::log_message( context, detail_string ));
}
}
}
namespace eosio {
/**
* A common source for information shared between the extraction process and the RPC process
*/
struct trace_api_common_impl {
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-dir", bpo::value<bfs::path>()->default_value("traces"),
"the location of the trace directory (absolute path or relative to application data dir)");
cfg_options("trace-slice-stride", bpo::value<uint32_t>()->default_value(10'000),
"the number of blocks each \"slice\" of trace data will contain on the filesystem");
}
void plugin_initialize(const appbase::variables_map& options) {
auto dir_option = options.at("trace-dir").as<bfs::path>();
if (dir_option.is_relative())
trace_dir = app().data_dir() / dir_option;
else
trace_dir = dir_option;
slice_stride = options.at("trace-slice-stride").as<uint32_t>();
}
// common configuration paramters
boost::filesystem::path trace_dir;
uint32_t slice_stride = 0;
};
/**
* Interface with the RPC process
*/
struct trace_api_rpc_plugin_impl {
trace_api_rpc_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-rpc-abi", bpo::value<vector<string>>()->composing(),
"ABIs used when decoding trace RPC responses.\n"
"There must be at least one ABI specified OR the flag trace-no-abis must be used.\n"
"ABIs are specified as \"Key=Value\" pairs in the form <account-name>=<abi-def>\n"
"Where <abi-def> can be:\n"
" a valid JSON-encoded ABI as a string\n"
" an absolute path to a file containing a valid JSON-encoded ABI\n"
" a relative path from `data-dir` to a file containing a valid JSON-encoded ABI\n"
);
cfg_options("trace-no-abis",
"Use to indicate that the RPC responses will not use ABIs.\n"
"Failure to specify this option when there are no trace-rpc-abi configuations will result in an Error.\n"
"This option is mutually exclusive with trace-rpc-api"
);
}
void plugin_initialize(const appbase::variables_map& options) {
data_handler = std::make_shared<abi_data_handler>([](const exception_with_context& e){
log_exception(e, fc::log_level::debug);
});
if( options.count("trace-rpc-abi") ) {
EOS_ASSERT(options.count("trace-no-abis") == 0, chain::plugin_config_exception,
"Trace API is configured with ABIs however trace-no-abis is set");
const std::vector<std::string> key_value_pairs = options["trace-rpc-abi"].as<std::vector<std::string>>();
for (const auto& entry : key_value_pairs) {
try {
auto kv = parse_kv_pairs(entry);
auto account = chain::name(kv.first);
auto abi = abi_def_from_file_or_str(kv.second);
data_handler->add_abi(account, abi);
} catch (...) {
elog("Malformed trace-rpc-abi provider: \"${val}\"", ("val", entry));
throw;
}
}
} else {
EOS_ASSERT(options.count("trace-no-abis") != 0, chain::plugin_config_exception,
"Trace API is not configured with ABIs and trace-no-abis is not set");
}
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
std::shared_ptr<abi_data_handler> data_handler;
};
struct trace_api_plugin_impl {
trace_api_plugin_impl( const std::shared_ptr<trace_api_common_impl>& common )
:common(common) {}
static void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
auto cfg_options = cfg.add_options();
cfg_options("trace-minimum-irreversible-history-us", bpo::value<uint64_t>()->default_value(-1),
"the minimum amount of history, as defined by time, this node will keep after it becomes irreversible\n"
"this value can be specified as a number of microseconds or\n"
"a value of \"-1\" will disable automatic maintenance of the trace slice files\n"
);
}
void plugin_initialize(const appbase::variables_map& options) {
if( options.count("trace-minimum-irreversible-history-us") ) {
auto value = options.at("trace-minimum-irreversible-history-us").as<uint64_t>();
if ( value == -1 ) {
minimum_irreversible_trace_history = fc::microseconds::maximum();
} else if (value >= 0) {
minimum_irreversible_trace_history = fc::microseconds(value);
} else {
EOS_THROW(chain::plugin_config_exception, "trace-minimum-irreversible-history-us must be either a positive number or -1");
}
}
}
void plugin_startup() {
}
void plugin_shutdown() {
}
std::shared_ptr<trace_api_common_impl> common;
fc::microseconds minimum_irreversible_trace_history = fc::microseconds::maximum();
};
_trace_api_plugin::_trace_api_plugin()
{}
_trace_api_plugin::~_trace_api_plugin()
{}
void _trace_api_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_plugin_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void _trace_api_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
my = std::make_shared<trace_api_plugin_impl>(common);
my->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void _trace_api_plugin::plugin_startup() {
my->plugin_startup();
rpc->plugin_startup();
}
void _trace_api_plugin::plugin_shutdown() {
my->plugin_shutdown();
rpc->plugin_shutdown();
}
void _trace_api_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
trace_api_rpc_plugin::trace_api_rpc_plugin()
{}
trace_api_rpc_plugin::~trace_api_rpc_plugin()
{}
void trace_api_rpc_plugin::set_program_options(appbase::options_description& cli, appbase::options_description& cfg) {
trace_api_common_impl::set_program_options(cli, cfg);
trace_api_rpc_plugin_impl::set_program_options(cli, cfg);
}
void trace_api_rpc_plugin::plugin_initialize(const appbase::variables_map& options) {
auto common = std::make_shared<trace_api_common_impl>();
common->plugin_initialize(options);
rpc = std::make_shared<trace_api_rpc_plugin_impl>(common);
rpc->plugin_initialize(options);
}
void trace_api_rpc_plugin::plugin_startup() {
rpc->plugin_startup();
}
void trace_api_rpc_plugin::plugin_shutdown() {
rpc->plugin_shutdown();
}
void trace_api_rpc_plugin::handle_sighup() {
fc::logger::update( logger_name, _log );
}
}
|
change trace-no-abis to be an error if it is not mutually exclusive with trace-rpc-abis or neither is present
|
change trace-no-abis to be an error if it is not mutually exclusive with trace-rpc-abis or neither is present
|
C++
|
mit
|
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
|
7029d2c056559e9d295da1c8b764b97446d8636a
|
src/plugins/regexstore/regexstore.cpp
|
src/plugins/regexstore/regexstore.cpp
|
/***************************************************************************
regexstore.c - Skeleton of a plugin
-------------------
begin : Fri May 21 2010
copyright : (C) 2010 by Markus Raab
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the BSD License (revised). *
* *
***************************************************************************/
/***************************************************************************
* *
* This is the skeleton of the methods you'll have to implement in order *
* to provide a valid plugin. *
* Simple fill the empty functions with your code and you are *
* ready to go. *
* *
***************************************************************************/
#ifndef HAVE_KDBCONFIG
# include "kdbconfig.h"
#endif
#include <regex.h>
#include <string>
#include <fstream>
#include <streambuf>
#include "regexstore.h"
using namespace ckdb;
#include <kdberrors.h>
#include <kdbproposal.h>
int elektraRegexstoreOpen(Plugin *handle ELEKTRA_UNUSED, Key *errorKey ELEKTRA_UNUSED)
{
/* plugin initialization logic */
return 1; /* success */
}
int elektraRegexstoreClose(Plugin *handle ELEKTRA_UNUSED, Key *errorKey ELEKTRA_UNUSED)
{
/* free all plugin resources and shut it down */
return 1; /* success */
}
std::string elektraRegexstorePos(std::string const & str,
std::string const & text,
regmatch_t *offsets,
char index,
Key *parentKey)
{
int pos = index - '0';
if (pos < 0 || pos > 9)
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex Group %d for %s not between 0 and 9 read from %s",
pos, text.c_str(), &index);
return std::string("");
}
if (offsets[pos].rm_so == -1)
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex Group %d missing for %s",
pos, text.c_str());
return std::string("");
}
std::string const & ret = str.substr(offsets[pos].rm_so,
offsets[pos].rm_eo - offsets[pos].rm_so);
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex Group %d ok for %s; GOT:%s",
pos, text.c_str(), ret.c_str());
return ret;
}
#include <iostream>
/** e.g.
configKey = keyNew ("user/map/#2",
KEY_VALUE, "#1 map ([^ \n]*) ([^ \n]*)",
KEY_META, "meta", "1",
KEY_END);
*/
Key *elektraRegexstoreProcess(Key *configKey,
std::string const & str,
Key *parentKey)
{
regex_t regex;
size_t nmatch = 10;
regmatch_t offsets[10];
std::string configString = keyString(configKey);
if (configString.length() < 3 &&
configString[0] != '#' &&
(configString[1] < '0' || configString[1] > '9') &&
configString[2] != ' ')
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"String %s of %s did not start with #<number><space>",
configString.c_str(), keyName(configKey));
return 0;
}
int ret = regcomp(®ex, configString.c_str()+3, REG_EXTENDED);
if (ret != 0)
{
char buffer [1000];
regerror (ret, ®ex, buffer, 999);
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Could not compile regex %s, because: %s",
configString.c_str()+3, buffer);
regfree (®ex);
return 0;
}
ret = regexec(®ex, str.c_str(), nmatch, offsets, 0);
if (ret != 0) /* e.g. REG_NOMATCH */
{
char buffer [1000];
regerror (ret, ®ex, buffer, 999);
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"No regex match, because: %s",
buffer);
regfree (®ex);
return 0;
}
std::string keyname;
// skip user/regexstore ..
if (!strncmp(keyName(configKey), "user", 4))
{
keyname = keyName(configKey)+15;
} else if (!strncmp(keyName(configKey), "system", 6))
{
keyname = keyName(configKey)+17;
}
std::string newkeyname;
for (size_t i=0; i<keyname.size(); ++i)
{
if (keyname[i] == '#')
{
++i;
newkeyname += elektraRegexstorePos(str,
std::string("keyname ")+keyname,
offsets,
keyname[i],
parentKey);
}
else
{
newkeyname += keyname[i];
}
}
Key *toAppend = keyNew (keyName(parentKey), KEY_END);
keyAddName(toAppend, newkeyname.c_str());
keySetString(toAppend,
elektraRegexstorePos(str,
"keystring of "+newkeyname,
offsets,
configString[1],
parentKey).c_str());
keyRewindMeta(configKey);
while (keyNextMeta(configKey))
{
keySetMeta(toAppend,
keyName(keyCurrentMeta(configKey)),
elektraRegexstorePos(str,
std::string("meta")
+keyName(keyCurrentMeta(configKey))
+" of "+newkeyname,
offsets,
keyString(keyCurrentMeta(configKey))[1],
parentKey).c_str());
}
regfree (®ex);
return toAppend;
}
int elektraRegexstoreGet(Plugin *handle ELEKTRA_UNUSED, KeySet *returned, Key *parentKey)
{
static std::string d = "system/elektra/modules/regexstore";
if (keyName(parentKey) == d)
{
KeySet *contract = ksNew (30,
keyNew ("system/elektra/modules/regexstore",
KEY_VALUE, "dbus plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/regexstore/exports", KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/open",
KEY_FUNC, elektraRegexstoreOpen, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/close",
KEY_FUNC, elektraRegexstoreClose, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/get",
KEY_FUNC, elektraRegexstoreGet, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/set",
KEY_FUNC, elektraRegexstoreSet, KEY_END),
#include ELEKTRA_README(regexstore)
keyNew ("system/elektra/modules/regexstore/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; /* success */
}
std::ifstream t(keyString(parentKey));
if (!t.is_open())
{
ELEKTRA_SET_ERRORF (95, parentKey, "could not open file %s",
keyString(parentKey));
return -1;
}
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
KeySet *conf = elektraPluginGetConfig(handle);
ksRewind(conf);
Key *confParent = ksLookupByName(conf, "/regexstore", 0);
if (!confParent)
{
ELEKTRA_SET_ERROR (95, parentKey,
"Key /regexstore not found in configuration");
return -1;
}
ksNext(conf); // skip root
do {
Key *toAppend = elektraRegexstoreProcess(
ksCurrent(conf),
str,
parentKey);
ksAppendKey(returned, toAppend);
}
while(ksNext(conf) && keyIsBelow(confParent, ksCurrent(conf)));
return 1; /* success */
}
int elektraRegexstoreSet(Plugin *handle ELEKTRA_UNUSED, KeySet *returned ELEKTRA_UNUSED, Key *parentKey ELEKTRA_UNUSED)
{
/* set all keys */
return 1; /* success */
}
int elektraRegexstoreError(Plugin *handle ELEKTRA_UNUSED, KeySet *returned ELEKTRA_UNUSED, Key *parentKey ELEKTRA_UNUSED)
{
/* set all keys */
return 1; /* success */
}
extern "C" Plugin *ELEKTRA_PLUGIN_EXPORT(regexstore)
{
return elektraPluginExport("regexstore",
ELEKTRA_PLUGIN_OPEN, &elektraRegexstoreOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraRegexstoreClose,
ELEKTRA_PLUGIN_GET, &elektraRegexstoreGet,
ELEKTRA_PLUGIN_SET, &elektraRegexstoreSet,
ELEKTRA_PLUGIN_END);
}
|
/***************************************************************************
regexstore.c - Skeleton of a plugin
-------------------
begin : Fri May 21 2010
copyright : (C) 2010 by Markus Raab
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the BSD License (revised). *
* *
***************************************************************************/
/***************************************************************************
* *
* This is the skeleton of the methods you'll have to implement in order *
* to provide a valid plugin. *
* Simple fill the empty functions with your code and you are *
* ready to go. *
* *
***************************************************************************/
#ifndef HAVE_KDBCONFIG
# include "kdbconfig.h"
#endif
#include <regex.h>
#include <string>
#include <fstream>
#include <streambuf>
#include "regexstore.h"
using namespace ckdb;
#include <kdberrors.h>
#include <kdbproposal.h>
int elektraRegexstoreOpen(Plugin *handle ELEKTRA_UNUSED, Key *errorKey ELEKTRA_UNUSED)
{
/* plugin initialization logic */
return 1; /* success */
}
int elektraRegexstoreClose(Plugin *handle ELEKTRA_UNUSED, Key *errorKey ELEKTRA_UNUSED)
{
/* free all plugin resources and shut it down */
return 1; /* success */
}
std::string elektraRegexstorePos(std::string const & str,
int offset,
std::string const & text,
regmatch_t *offsets,
char index,
Key *parentKey)
{
int pos = index - '0';
if (pos < 0 || pos > 9)
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex Group %d for %s not between 0 and 9 read from %s",
pos, text.c_str(), &index);
return std::string("");
}
if (offsets[pos].rm_so == -1)
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex Group %d missing for %s",
pos, text.c_str());
return std::string("");
}
return str.substr(
offset + offsets[pos].rm_so,
offsets[pos].rm_eo - offsets[pos].rm_so);
}
/** e.g.
configKey = keyNew ("user/map/#2",
KEY_VALUE, "#1 map ([^ \n]*) ([^ \n]*)",
KEY_META, "meta", "1",
KEY_END);
*/
Key *elektraRegexstoreProcess(Key *configKey,
int *offset,
std::string const & str,
Key *parentKey)
{
regex_t regex;
size_t nmatch = 10;
regmatch_t offsets[10];
std::string configString = keyString(configKey);
if (configString.length() < 3 &&
configString[0] != '#' &&
(configString[1] < '0' || configString[1] > '9') &&
configString[2] != ' ')
{
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"String %s of %s did not start with #<number><space>",
configString.c_str(), keyName(configKey));
return 0;
}
int ret = regcomp(®ex, configString.c_str()+3, REG_EXTENDED);
if (ret != 0)
{
char buffer [1000];
regerror (ret, ®ex, buffer, 999);
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Could not compile regex %s, because: %s",
configString.c_str()+3, buffer);
regfree (®ex);
return 0;
}
ret = regexec(®ex, str.c_str()+*offset, nmatch, offsets, 0);
if (ret == REG_NOMATCH)
{
return 0;
}
if (ret != 0)
{
char buffer [1000];
regerror (ret, ®ex, buffer, 999);
ELEKTRA_ADD_WARNINGF (96,
parentKey,
"Regex exec returned error (not in manual for linux), because: %s",
buffer);
regfree (®ex);
return 0;
}
std::string keyname;
// skip user/regexstore ..
if (!strncmp(keyName(configKey), "user", 4))
{
keyname = keyName(configKey)+15;
} else if (!strncmp(keyName(configKey), "system", 6))
{
keyname = keyName(configKey)+17;
}
std::string newkeyname;
for (size_t i=0; i<keyname.size(); ++i)
{
if (keyname[i] == '#')
{
++i;
newkeyname += elektraRegexstorePos(str,
*offset,
std::string("keyname ")+keyname,
offsets,
keyname[i],
parentKey);
}
else
{
newkeyname += keyname[i];
}
}
Key *toAppend = keyNew (keyName(parentKey), KEY_END);
keyAddName(toAppend, newkeyname.c_str());
keySetString(toAppend,
elektraRegexstorePos(str,
*offset,
"keystring of "+newkeyname,
offsets,
configString[1],
parentKey).c_str());
keyRewindMeta(configKey);
while (keyNextMeta(configKey))
{
keySetMeta(toAppend,
keyName(keyCurrentMeta(configKey)),
elektraRegexstorePos(str,
*offset,
std::string("meta")
+keyName(keyCurrentMeta(configKey))
+" of "+newkeyname,
offsets,
keyString(keyCurrentMeta(configKey))[1],
parentKey).c_str());
}
// update offset for next iteration
*offset += offsets[0].rm_eo;
regfree (®ex);
return toAppend;
}
int elektraRegexstoreGet(Plugin *handle ELEKTRA_UNUSED, KeySet *returned, Key *parentKey)
{
static std::string d = "system/elektra/modules/regexstore";
if (keyName(parentKey) == d)
{
KeySet *contract = ksNew (30,
keyNew ("system/elektra/modules/regexstore",
KEY_VALUE, "regexstore plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/regexstore/exports", KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/open",
KEY_FUNC, elektraRegexstoreOpen, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/close",
KEY_FUNC, elektraRegexstoreClose, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/get",
KEY_FUNC, elektraRegexstoreGet, KEY_END),
keyNew ("system/elektra/modules/regexstore/exports/set",
KEY_FUNC, elektraRegexstoreSet, KEY_END),
#include ELEKTRA_README(regexstore)
keyNew ("system/elektra/modules/regexstore/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; /* success */
}
std::ifstream t(keyString(parentKey));
if (!t.is_open())
{
ELEKTRA_SET_ERRORF (95, parentKey, "could not open file %s",
keyString(parentKey));
return -1;
}
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
KeySet *conf = elektraPluginGetConfig(handle);
ksRewind(conf);
Key *confParent = ksLookupByName(conf, "/regexstore", 0);
if (!confParent)
{
ELEKTRA_SET_ERROR (95, parentKey,
"Key /regexstore not found in configuration");
return -1;
}
ksNext(conf); // skip root
do {
int offset = 0;
Key *toAppend = 0;
do
{
toAppend = elektraRegexstoreProcess(
ksCurrent(conf),
&offset,
str,
parentKey);
ksAppendKey(returned, toAppend);
} while (toAppend);
}
while(ksNext(conf) &&
keyIsBelow(confParent, ksCurrent(conf)));
return 1; /* success */
}
int elektraRegexstoreSet(Plugin *handle ELEKTRA_UNUSED, KeySet *returned ELEKTRA_UNUSED, Key *parentKey ELEKTRA_UNUSED)
{
/* set all keys */
return 1; /* success */
}
int elektraRegexstoreError(Plugin *handle ELEKTRA_UNUSED, KeySet *returned ELEKTRA_UNUSED, Key *parentKey ELEKTRA_UNUSED)
{
/* set all keys */
return 1; /* success */
}
extern "C" Plugin *ELEKTRA_PLUGIN_EXPORT(regexstore)
{
return elektraPluginExport("regexstore",
ELEKTRA_PLUGIN_OPEN, &elektraRegexstoreOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraRegexstoreClose,
ELEKTRA_PLUGIN_GET, &elektraRegexstoreGet,
ELEKTRA_PLUGIN_SET, &elektraRegexstoreSet,
ELEKTRA_PLUGIN_END);
}
|
allow multiple matches in regexstore
|
allow multiple matches in regexstore
|
C++
|
bsd-3-clause
|
petermax2/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,mpranj/libelektra,e1528532/libelektra,petermax2/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,petermax2/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,e1528532/libelektra,e1528532/libelektra,mpranj/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,petermax2/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,BernhardDenner/libelektra,petermax2/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,petermax2/libelektra
|
d08a30280a551fe78f99377d5b5aaaaf7676b8d3
|
esidl/src/cxx.cpp
|
esidl/src/cxx.cpp
|
/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 "cplusplus.h"
#include "info.h"
class Cxx : public CPlusPlus
{
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (element->isSequence(interface) || element->isNative(interface))
{
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
writetab();
element->accept(this);
write(";\n");
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
Cxx(const char* source, FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
CPlusPlus(source, file, stringTypeName, useExceptions)
{
}
virtual void at(const StructType* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
if (!node->isLeaf())
{
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
}
virtual void at(const ExceptDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
virtual void at(const Interface* node)
{
if (node->getAttr() & Interface::ImplementedOn)
{
return;
}
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("class %s", node->getName().c_str());
if (!node->isLeaf())
{
if (node->getExtends())
{
write(" : ");
prefix = "public ";
node->getExtends()->accept(this);
prefix = "";
}
writeln("");
writeln("{");
writeln("public:");
indent();
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
i != node->getMixins()->end();
++i)
{
writeln("// %s", (*i)->getName().c_str());
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
visitInterfaceElement(*i, *j);
}
}
writeln("static const char* iid()");
writeln("{");
indent();
writeln("static const char* const name = \"%s\";",
node->getQualifiedName().c_str());
writeln("return name;");
unindent();
writeln("}");
writeln("static const char* info()");
writeln("{");
indent();
writetab();
write("static const char* const info = ");
indent();
Info info(this, moduleName);
const_cast<Interface*>(node)->accept(&info);
write(";\n");
unindent();
writeln("return info;");
unindent();
writeln("}");
if (Interface* constructor = node->getConstructor())
{
// Process constructors.
constructorMode = true;
for (NodeList::iterator i = constructor->begin();
i != constructor->end();
++i)
{
writetab();
(*i)->accept(this);
}
constructorMode = false;
writeln("static Constructor* getConstructor()");
writeln("{");
indent();
writeln("return constructor;");
unindent();
writeln("}");
writeln("static void setConstructor(Constructor* ctor)");
writeln("{");
indent();
writeln("constructor = ctor;");
unindent();
writeln("}");
unindent();
writeln("private:");
indent();
writeln("static Constructor* constructor;");
}
unindent();
writetab();
write("}");
if (node->getConstructor())
{
write(";\n\n");
writetab();
write("%s::Constructor* %s::constructor __attribute__((weak))",
node->getName().c_str(), node->getName().c_str());
}
}
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
if (node->getName() == "TRUE")
{
write("true");
}
else if (node->getName() == "FALSE")
{
write("false");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
write("typedef ");
}
if (node->isInterface(node->getParent()))
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
else
{
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
at(static_cast<const Member*>(node));
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
}
virtual void at(const ConstDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("static const ");
at(static_cast<const Member*>(node));
write(" = ");
node->getExp()->accept(this);
}
virtual void at(const Attribute* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
CPlusPlus::getter(node);
write(" = 0");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
write(";\n");
writetab();
CPlusPlus::setter(node);
write(" = 0");
}
}
virtual void at(const OpDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
CPlusPlus::at(node);
if (!constructorMode)
{
write(" = 0");
}
else
{
writeln("");
writeln("{");
indent();
writeln("if (constructor)");
indent();
writetab();
write("return constructor->createInstance(");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
if (i != node->begin())
{
write(", ");
}
write("%s", (*i)->getName().c_str());
}
write(");");
writeln("");
unindent();
writeln("else");
indent();
writeln("return 0;");
unindent();
unindent();
writeln("}");
}
}
};
class Import : public Visitor
{
const char* source;
FILE* file;
bool printed;
public:
Import(const char* source, FILE* file) :
source(source),
file(file),
printed(false)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const Include* node)
{
if (!node->isDefinedIn(source))
{
return;
}
if (node->isSystem())
{
fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
else
{
fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
printed = true;
}
bool hasPrinted() const
{
return printed;
}
};
class Predeclaration : public Visitor
{
const char* source;
FILE* file;
public:
Predeclaration(const char* source, FILE* file) :
source(source),
file(file)
{
}
virtual void at(const Node* node)
{
if (!node->isDefinedIn(source))
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
if (!node->hasPredeclarations())
{
return;
}
if (0 < node->getName().size())
{
fprintf(file, "namespace %s\n", node->getName().c_str());
fprintf(file, "{\n");
visitChildren(node);
fprintf(file, "}\n\n");
}
else
{
visitChildren(node);
}
}
virtual void at(const Interface* node)
{
if (!node->isDefinedIn(source) || !node->isLeaf())
{
return;
}
fprintf(file, " class %s;\n", node->getName().c_str());
}
};
void printCxx(const char* source, const char* stringTypeName, bool useExceptions)
{
const std::string filename = getOutputFilename(source, "h");
printf("# %s\n", filename.c_str());
FILE* file = fopen(filename.c_str(), "w");
if (!file)
{
return;
}
std::string included = getIncludedName(filename);
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "#ifndef %s\n", included.c_str());
fprintf(file, "#define %s\n\n", included.c_str());
Import import(source, file);
getSpecification()->accept(&import);
if (import.hasPrinted())
{
fprintf(file, "\n");
}
if (!Node::getFlatNamespace())
{
Predeclaration predeclaration(source, file);
getSpecification()->accept(&predeclaration);
}
Cxx cxx(source, file, stringTypeName, useExceptions);
getSpecification()->accept(&cxx);
fprintf(file, "#endif // %s\n", included.c_str());
fclose(file);
}
|
/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 "cplusplus.h"
#include "info.h"
class Cxx : public CPlusPlus
{
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (element->isSequence(interface) || element->isNative(interface))
{
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
writetab();
element->accept(this);
write(";\n");
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
Cxx(const char* source, FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
CPlusPlus(source, file, stringTypeName, useExceptions)
{
}
virtual void at(const ExceptDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("struct %s", node->getName().c_str());
writeln("");
writeln("{");
indent();
printChildren(node);
unindent();
writetab();
write("}");
}
virtual void at(const Interface* node)
{
if (node->getAttr() & Interface::ImplementedOn)
{
return;
}
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("class %s", node->getName().c_str());
if (!node->isLeaf())
{
if (node->getExtends())
{
write(" : ");
prefix = "public ";
node->getExtends()->accept(this);
prefix = "";
}
writeln("");
writeln("{");
writeln("public:");
indent();
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
i != node->getMixins()->end();
++i)
{
writeln("// %s", (*i)->getName().c_str());
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
visitInterfaceElement(*i, *j);
}
}
writeln("static const char* iid()");
writeln("{");
indent();
writeln("static const char* const name = \"%s\";",
node->getQualifiedName().c_str());
writeln("return name;");
unindent();
writeln("}");
writeln("static const char* info()");
writeln("{");
indent();
writetab();
write("static const char* const info = ");
indent();
Info info(this, moduleName);
const_cast<Interface*>(node)->accept(&info);
write(";\n");
unindent();
writeln("return info;");
unindent();
writeln("}");
if (Interface* constructor = node->getConstructor())
{
// Process constructors.
constructorMode = true;
for (NodeList::iterator i = constructor->begin();
i != constructor->end();
++i)
{
writetab();
(*i)->accept(this);
}
constructorMode = false;
writeln("static Constructor* getConstructor()");
writeln("{");
indent();
writeln("return constructor;");
unindent();
writeln("}");
writeln("static void setConstructor(Constructor* ctor)");
writeln("{");
indent();
writeln("constructor = ctor;");
unindent();
writeln("}");
unindent();
writeln("private:");
indent();
writeln("static Constructor* constructor;");
}
unindent();
writetab();
write("}");
if (node->getConstructor())
{
write(";\n\n");
writetab();
write("%s::Constructor* %s::constructor __attribute__((weak))",
node->getName().c_str(), node->getName().c_str());
}
}
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
if (node->getName() == "TRUE")
{
write("true");
}
else if (node->getName() == "FALSE")
{
write("false");
}
else
{
write("%s", node->getName().c_str());
}
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
write("typedef ");
}
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
at(static_cast<const Member*>(node));
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
}
virtual void at(const ConstDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("static const ");
at(static_cast<const Member*>(node));
write(" = ");
node->getExp()->accept(this);
}
virtual void at(const Attribute* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
CPlusPlus::getter(node);
write(" = 0");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
write(";\n");
writetab();
CPlusPlus::setter(node);
write(" = 0");
}
}
virtual void at(const OpDcl* node)
{
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
CPlusPlus::at(node);
if (!constructorMode)
{
write(" = 0");
}
else
{
writeln("");
writeln("{");
indent();
writeln("if (constructor)");
indent();
writetab();
write("return constructor->createInstance(");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
if (i != node->begin())
{
write(", ");
}
write("%s", (*i)->getName().c_str());
}
write(");");
writeln("");
unindent();
writeln("else");
indent();
writeln("return 0;");
unindent();
unindent();
writeln("}");
}
}
};
class Import : public Visitor
{
const char* source;
FILE* file;
bool printed;
public:
Import(const char* source, FILE* file) :
source(source),
file(file),
printed(false)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const Include* node)
{
if (!node->isDefinedIn(source))
{
return;
}
if (node->isSystem())
{
fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
else
{
fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
}
printed = true;
}
bool hasPrinted() const
{
return printed;
}
};
class Predeclaration : public Visitor
{
const char* source;
FILE* file;
public:
Predeclaration(const char* source, FILE* file) :
source(source),
file(file)
{
}
virtual void at(const Node* node)
{
if (!node->isDefinedIn(source))
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
if (!node->hasPredeclarations())
{
return;
}
if (0 < node->getName().size())
{
fprintf(file, "namespace %s\n", node->getName().c_str());
fprintf(file, "{\n");
visitChildren(node);
fprintf(file, "}\n\n");
}
else
{
visitChildren(node);
}
}
virtual void at(const Interface* node)
{
if (!node->isDefinedIn(source) || !node->isLeaf())
{
return;
}
fprintf(file, " class %s;\n", node->getName().c_str());
}
};
void printCxx(const char* source, const char* stringTypeName, bool useExceptions)
{
const std::string filename = getOutputFilename(source, "h");
printf("# %s\n", filename.c_str());
FILE* file = fopen(filename.c_str(), "w");
if (!file)
{
return;
}
std::string included = getIncludedName(filename);
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "#ifndef %s\n", included.c_str());
fprintf(file, "#define %s\n\n", included.c_str());
Import import(source, file);
getSpecification()->accept(&import);
if (import.hasPrinted())
{
fprintf(file, "\n");
}
if (!Node::getFlatNamespace())
{
Predeclaration predeclaration(source, file);
getSpecification()->accept(&predeclaration);
}
Cxx cxx(source, file, stringTypeName, useExceptions);
getSpecification()->accept(&cxx);
fprintf(file, "#endif // %s\n", included.c_str());
fclose(file);
}
|
Clean up.
|
Clean up.
|
C++
|
apache-2.0
|
josejamilena/es-operating-system,ericmckean/es-operating-system,berkus/es-operating-system,google-code-export/es-operating-system,ericmckean/es-operating-system,google-code-export/es-operating-system,josejamilena/es-operating-system,josejamilena/es-operating-system,berkus/es-operating-system,google-code-export/es-operating-system,ericmckean/es-operating-system,josejamilena/es-operating-system,ericmckean/es-operating-system,berkus/es-operating-system,ericmckean/es-operating-system,google-code-export/es-operating-system,ericmckean/es-operating-system,google-code-export/es-operating-system,berkus/es-operating-system,berkus/es-operating-system,josejamilena/es-operating-system,josejamilena/es-operating-system,ericmckean/es-operating-system,berkus/es-operating-system,josejamilena/es-operating-system,google-code-export/es-operating-system,berkus/es-operating-system,google-code-export/es-operating-system
|
3a1a3a9e00047cdb887c448afef8c335b48262f2
|
src/service/sockets/SocketManager.cpp
|
src/service/sockets/SocketManager.cpp
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd 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.
*/
/*
* @file SocketManager.cpp
* @author Lukasz Wojciechowski <[email protected]>
* @version 1.0
* @brief This file implements socket layer manager for cynara
*/
#include <errno.h>
#include <fcntl.h>
#include <memory>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <systemd/sd-daemon.h>
#include <log/log.h>
#include <common.h>
#include <exceptions/DescriptorNotExistsException.h>
#include <exceptions/InitException.h>
#include <exceptions/NoResponseGeneratedException.h>
#include <exceptions/UnexpectedErrorException.h>
#include <logic/Logic.h>
#include <main/Cynara.h>
#include <protocol/ProtocolAdmin.h>
#include <protocol/ProtocolClient.h>
#include <protocol/ProtocolSignal.h>
#include <stdexcept>
#include "SocketManager.h"
namespace Cynara {
SocketManager::SocketManager() : m_working(false), m_maxDesc(-1) {
FD_ZERO(&m_readSet);
FD_ZERO(&m_writeSet);
}
SocketManager::~SocketManager() {
}
void SocketManager::run(void) {
init();
mainLoop();
}
void SocketManager::init(void) {
LOGI("SocketManger init start");
const std::string clientSocketPath("/run/cynara/cynara.socket");
const std::string adminSocketPath("/run/cynara/cynara-admin.socket");
const mode_t clientSocketUMask(0);
const mode_t adminSocketUMask(0077);
createDomainSocket(ProtocolPtr(new ProtocolClient), clientSocketPath, clientSocketUMask);
createDomainSocket(ProtocolPtr(new ProtocolAdmin), adminSocketPath, adminSocketUMask);
// todo create signal descriptor
LOGI("SocketManger init done");
}
void SocketManager::mainLoop(void) {
LOGI("SocketManger mainLoop start");
m_working = true;
while (m_working) {
fd_set readSet = m_readSet;
fd_set writeSet = m_writeSet;
int ret = select(m_maxDesc + 1, &readSet, &writeSet, nullptr, nullptr);
if (ret < 0) {
switch (errno) {
case EINTR:
continue;
default:
int err = errno;
throw UnexpectedErrorException(err, strerror(err));
}
} else if (ret > 0) {
for (int i = 0; i < m_maxDesc + 1 && ret; ++i) {
if (FD_ISSET(i, &readSet)) {
readyForRead(i);
--ret;
}
if (FD_ISSET(i, &writeSet)) {
readyForWrite(i);
--ret;
}
}
}
}
LOGI("SocketManger mainLoop done");
}
void SocketManager::mainLoopStop(void) {
m_working = false;
}
void SocketManager::readyForRead(int fd) {
LOGD("SocketManger readyForRead on fd [%d] start", fd);
auto &desc = m_fds[fd];
if (desc.isListen()) {
readyForAccept(fd);
return;
}
RawBuffer readBuffer(DEFAULT_BUFFER_SIZE);
ssize_t size = read(fd, readBuffer.data(), DEFAULT_BUFFER_SIZE);
if (size > 0) {
LOGD("read [%zd] bytes", size);
readBuffer.resize(size);
if (handleRead(fd, readBuffer)) {
LOGD("SocketManger readyForRead on fd [%d] successfully done", fd);
return;
}
LOGI("interpreting buffer read from [%d] failed", fd);
} else if (size < 0) {
int err = errno;
switch (err) {
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
case EINTR:
return;
default:
LOGW("While reading from [%d] socket, error [%d]:<%s>",
fd, err, strerror(err));
}
} else {
LOGN("Socket [%d] closed on other end", fd);
}
closeSocket(fd);
LOGD("SocketManger readyForRead on fd [%d] done", fd);
}
void SocketManager::readyForWrite(int fd) {
LOGD("SocketManger readyForWrite on fd [%d] start", fd);
auto &desc = m_fds[fd];
auto &buffer = desc.prepareWriteBuffer();
size_t size = buffer.size();
ssize_t result = write(fd, buffer.data(), size);
if (result == -1) {
int err = errno;
switch (err) {
case EAGAIN:
case EINTR:
// select will trigger write once again, nothing to do
break;
case EPIPE:
default:
LOGD("Error during write to fd [%d]:<%s> ", fd, strerror(err));
closeSocket(fd);
break;
}
return; // We do not want to propagate error to next layer
}
LOGD("written [%zd] bytes", result);
buffer.erase(buffer.begin(), buffer.begin() + result);
if (buffer.empty())
removeWriteSocket(fd);
LOGD("SocketManger readyForWrite on fd [%d] done", fd);
}
void SocketManager::readyForAccept(int fd) {
LOGD("SocketManger readyForAccept on fd [%d] start", fd);
struct sockaddr_un clientAddr;
unsigned int clientLen = sizeof(clientAddr);
int client = accept4(fd, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
if (client == -1) {
int err = errno;
LOGW("Error in accept on socket [%d]: <%s>", fd, strerror(err));
return;
}
LOGD("Accept on sock [%d]. New client socket opened [%d]", fd, client);
auto &description = createDescriptor(client);
description.setListen(false);
description.setProtocol(m_fds[fd].protocol());
addReadSocket(client);
LOGD("SocketManger readyForAccept on fd [%d] done", fd);
}
void SocketManager::closeSocket(int fd) {
LOGD("SocketManger closeSocket fd [%d] start", fd);
removeReadSocket(fd);
removeWriteSocket(fd);
m_fds[fd].clear();
close(fd);
LOGD("SocketManger closeSocket fd [%d] done", fd);
}
bool SocketManager::handleRead(int fd, const RawBuffer &readbuffer) {
LOGD("SocketManger handleRead on fd [%d] start", fd);
auto &desc = m_fds[fd];
desc.pushReadBuffer(readbuffer);
try {
while(true) {
auto req = desc.extractRequest();
if (!req)
break;
LOGD("request extracted");
try {
req->execute(RequestContext(fd, desc.responseTaker(), desc.writeQueue()));
if (desc.hasDataToWrite())
addWriteSocket(fd);
} catch (const NoResponseGeneratedException &ex) {
LOGD("no response generated");
}
}
} catch (const Exception &ex) {
LOGE("Error handling request <%s>. Closing socket", ex.what());
return false;
}
LOGD("SocketManger handleRead on fd [%d] done", fd);
return true;
}
void SocketManager::createDomainSocket(ProtocolPtr protocol, const std::string &path, mode_t mask) {
int fd = getSocketFromSystemD(path);
if (fd == -1)
fd = createDomainSocketHelp(path, mask);
auto &desc = createDescriptor(fd);
desc.setListen(true);
desc.setProtocol(protocol);
addReadSocket(fd);
LOGD("Domain socket: [%d] added.", fd);
}
int SocketManager::createDomainSocketHelp(const std::string &path, mode_t mask) {
int fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
int err = errno;
LOGE("Error during UNIX socket creation: <%s>", strerror(err));
throw InitException();
}
int flags;
if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
flags = 0;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
int err = errno;
close(fd);
LOGE("Error setting \"O_NONBLOCK\" on descriptor [%d] with fcntl: <%s>",
fd, strerror(err));
throw InitException();
}
sockaddr_un serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sun_family = AF_UNIX;
if (path.length() > sizeof(serverAddress.sun_path)) {
LOGE("Path for unix domain socket <%s> is [%zu] bytes long, while it should be maximum "
"[%zu] bytes long", path.c_str(), path.length(), sizeof(serverAddress));
throw InitException();
}
strcpy(serverAddress.sun_path, path.c_str());
unlink(serverAddress.sun_path);
mode_t originalUmask;
originalUmask = umask(mask);
if (bind(fd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
int err = errno;
close(fd);
LOGE("Error in bind socket descriptor [%d] to path <%s>: <%s>",
fd, path.c_str(), strerror(err));
throw InitException();
}
umask(originalUmask);
if (listen(fd, 5) == -1) {
int err = errno;
close(fd);
LOGE("Error setting listen on file descriptor [%d], path <%s>: <%s>",
fd, path.c_str(), strerror(err));
throw InitException();
}
return fd;
}
int SocketManager::getSocketFromSystemD(const std::string &path) {
int n = sd_listen_fds(0);
LOGI("sd_listen_fds returns: [%d]", n);
if (n < 0) {
LOGE("Error in sd_listend_fds");
throw InitException();
}
for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) {
if (sd_is_socket_unix(fd, SOCK_STREAM, 1, path.c_str(), 0) > 0) {
LOGI("Useable socket <%s> was passed by SystemD under descriptor [%d]",
path.c_str(), fd);
return fd;
}
}
LOGI("No useable sockets were passed by systemd.");
return -1;
}
Descriptor &SocketManager::createDescriptor(int fd) {
if (fd > m_maxDesc) {
m_maxDesc = fd;
if (fd >= static_cast<int>(m_fds.size()))
m_fds.resize(fd + 20);
}
auto &desc = m_fds[fd];
desc.setUsed(true);
return desc;
}
void SocketManager::addReadSocket(int fd) {
FD_SET(fd, &m_readSet);
}
void SocketManager::removeReadSocket(int fd) {
FD_CLR(fd, &m_readSet);
}
void SocketManager::addWriteSocket(int fd) {
FD_SET(fd, &m_writeSet);
}
void SocketManager::removeWriteSocket(int fd) {
FD_CLR(fd, &m_writeSet);
}
} // namespace Cynara
|
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd 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.
*/
/*
* @file SocketManager.cpp
* @author Lukasz Wojciechowski <[email protected]>
* @version 1.0
* @brief This file implements socket layer manager for cynara
*/
#include <errno.h>
#include <fcntl.h>
#include <memory>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <systemd/sd-daemon.h>
#include <log/log.h>
#include <common.h>
#include <exceptions/DescriptorNotExistsException.h>
#include <exceptions/InitException.h>
#include <exceptions/NoResponseGeneratedException.h>
#include <exceptions/UnexpectedErrorException.h>
#include <logic/Logic.h>
#include <main/Cynara.h>
#include <protocol/ProtocolAdmin.h>
#include <protocol/ProtocolClient.h>
#include <protocol/ProtocolSignal.h>
#include <stdexcept>
#include "SocketManager.h"
namespace Cynara {
SocketManager::SocketManager() : m_working(false), m_maxDesc(-1) {
FD_ZERO(&m_readSet);
FD_ZERO(&m_writeSet);
}
SocketManager::~SocketManager() {
}
void SocketManager::run(void) {
init();
mainLoop();
}
void SocketManager::init(void) {
LOGI("SocketManger init start");
const std::string clientSocketPath("/run/cynara/cynara.socket");
const std::string adminSocketPath("/run/cynara/cynara-admin.socket");
const mode_t clientSocketUMask(0);
const mode_t adminSocketUMask(0077);
createDomainSocket(ProtocolPtr(new ProtocolClient), clientSocketPath, clientSocketUMask);
createDomainSocket(ProtocolPtr(new ProtocolAdmin), adminSocketPath, adminSocketUMask);
// todo create signal descriptor
LOGI("SocketManger init done");
}
void SocketManager::mainLoop(void) {
LOGI("SocketManger mainLoop start");
m_working = true;
while (m_working) {
fd_set readSet = m_readSet;
fd_set writeSet = m_writeSet;
int ret = select(m_maxDesc + 1, &readSet, &writeSet, nullptr, nullptr);
if (ret < 0) {
switch (errno) {
case EINTR:
continue;
default:
int err = errno;
throw UnexpectedErrorException(err, strerror(err));
}
} else if (ret > 0) {
for (int i = 0; i < m_maxDesc + 1 && ret; ++i) {
if (FD_ISSET(i, &readSet)) {
readyForRead(i);
--ret;
}
if (FD_ISSET(i, &writeSet)) {
readyForWrite(i);
--ret;
}
if (m_fds[i].isUsed() && m_fds[i].hasDataToWrite())
addWriteSocket(i);
}
}
}
LOGI("SocketManger mainLoop done");
}
void SocketManager::mainLoopStop(void) {
m_working = false;
}
void SocketManager::readyForRead(int fd) {
LOGD("SocketManger readyForRead on fd [%d] start", fd);
auto &desc = m_fds[fd];
if (desc.isListen()) {
readyForAccept(fd);
return;
}
RawBuffer readBuffer(DEFAULT_BUFFER_SIZE);
ssize_t size = read(fd, readBuffer.data(), DEFAULT_BUFFER_SIZE);
if (size > 0) {
LOGD("read [%zd] bytes", size);
readBuffer.resize(size);
if (handleRead(fd, readBuffer)) {
LOGD("SocketManger readyForRead on fd [%d] successfully done", fd);
return;
}
LOGI("interpreting buffer read from [%d] failed", fd);
} else if (size < 0) {
int err = errno;
switch (err) {
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
case EINTR:
return;
default:
LOGW("While reading from [%d] socket, error [%d]:<%s>",
fd, err, strerror(err));
}
} else {
LOGN("Socket [%d] closed on other end", fd);
}
closeSocket(fd);
LOGD("SocketManger readyForRead on fd [%d] done", fd);
}
void SocketManager::readyForWrite(int fd) {
LOGD("SocketManger readyForWrite on fd [%d] start", fd);
auto &desc = m_fds[fd];
auto &buffer = desc.prepareWriteBuffer();
size_t size = buffer.size();
ssize_t result = write(fd, buffer.data(), size);
if (result == -1) {
int err = errno;
switch (err) {
case EAGAIN:
case EINTR:
// select will trigger write once again, nothing to do
break;
case EPIPE:
default:
LOGD("Error during write to fd [%d]:<%s> ", fd, strerror(err));
closeSocket(fd);
break;
}
return; // We do not want to propagate error to next layer
}
LOGD("written [%zd] bytes", result);
buffer.erase(buffer.begin(), buffer.begin() + result);
if (buffer.empty())
removeWriteSocket(fd);
LOGD("SocketManger readyForWrite on fd [%d] done", fd);
}
void SocketManager::readyForAccept(int fd) {
LOGD("SocketManger readyForAccept on fd [%d] start", fd);
struct sockaddr_un clientAddr;
unsigned int clientLen = sizeof(clientAddr);
int client = accept4(fd, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK);
if (client == -1) {
int err = errno;
LOGW("Error in accept on socket [%d]: <%s>", fd, strerror(err));
return;
}
LOGD("Accept on sock [%d]. New client socket opened [%d]", fd, client);
auto &description = createDescriptor(client);
description.setListen(false);
description.setProtocol(m_fds[fd].protocol());
addReadSocket(client);
LOGD("SocketManger readyForAccept on fd [%d] done", fd);
}
void SocketManager::closeSocket(int fd) {
LOGD("SocketManger closeSocket fd [%d] start", fd);
removeReadSocket(fd);
removeWriteSocket(fd);
m_fds[fd].clear();
close(fd);
LOGD("SocketManger closeSocket fd [%d] done", fd);
}
bool SocketManager::handleRead(int fd, const RawBuffer &readbuffer) {
LOGD("SocketManger handleRead on fd [%d] start", fd);
auto &desc = m_fds[fd];
desc.pushReadBuffer(readbuffer);
try {
while(true) {
auto req = desc.extractRequest();
if (!req)
break;
LOGD("request extracted");
try {
req->execute(RequestContext(fd, desc.responseTaker(), desc.writeQueue()));
} catch (const NoResponseGeneratedException &ex) {
LOGD("no response generated");
}
}
} catch (const Exception &ex) {
LOGE("Error handling request <%s>. Closing socket", ex.what());
return false;
}
LOGD("SocketManger handleRead on fd [%d] done", fd);
return true;
}
void SocketManager::createDomainSocket(ProtocolPtr protocol, const std::string &path, mode_t mask) {
int fd = getSocketFromSystemD(path);
if (fd == -1)
fd = createDomainSocketHelp(path, mask);
auto &desc = createDescriptor(fd);
desc.setListen(true);
desc.setProtocol(protocol);
addReadSocket(fd);
LOGD("Domain socket: [%d] added.", fd);
}
int SocketManager::createDomainSocketHelp(const std::string &path, mode_t mask) {
int fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
int err = errno;
LOGE("Error during UNIX socket creation: <%s>", strerror(err));
throw InitException();
}
int flags;
if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
flags = 0;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
int err = errno;
close(fd);
LOGE("Error setting \"O_NONBLOCK\" on descriptor [%d] with fcntl: <%s>",
fd, strerror(err));
throw InitException();
}
sockaddr_un serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sun_family = AF_UNIX;
if (path.length() > sizeof(serverAddress.sun_path)) {
LOGE("Path for unix domain socket <%s> is [%zu] bytes long, while it should be maximum "
"[%zu] bytes long", path.c_str(), path.length(), sizeof(serverAddress));
throw InitException();
}
strcpy(serverAddress.sun_path, path.c_str());
unlink(serverAddress.sun_path);
mode_t originalUmask;
originalUmask = umask(mask);
if (bind(fd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
int err = errno;
close(fd);
LOGE("Error in bind socket descriptor [%d] to path <%s>: <%s>",
fd, path.c_str(), strerror(err));
throw InitException();
}
umask(originalUmask);
if (listen(fd, 5) == -1) {
int err = errno;
close(fd);
LOGE("Error setting listen on file descriptor [%d], path <%s>: <%s>",
fd, path.c_str(), strerror(err));
throw InitException();
}
return fd;
}
int SocketManager::getSocketFromSystemD(const std::string &path) {
int n = sd_listen_fds(0);
LOGI("sd_listen_fds returns: [%d]", n);
if (n < 0) {
LOGE("Error in sd_listend_fds");
throw InitException();
}
for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) {
if (sd_is_socket_unix(fd, SOCK_STREAM, 1, path.c_str(), 0) > 0) {
LOGI("Useable socket <%s> was passed by SystemD under descriptor [%d]",
path.c_str(), fd);
return fd;
}
}
LOGI("No useable sockets were passed by systemd.");
return -1;
}
Descriptor &SocketManager::createDescriptor(int fd) {
if (fd > m_maxDesc) {
m_maxDesc = fd;
if (fd >= static_cast<int>(m_fds.size()))
m_fds.resize(fd + 20);
}
auto &desc = m_fds[fd];
desc.setUsed(true);
return desc;
}
void SocketManager::addReadSocket(int fd) {
FD_SET(fd, &m_readSet);
}
void SocketManager::removeReadSocket(int fd) {
FD_CLR(fd, &m_readSet);
}
void SocketManager::addWriteSocket(int fd) {
FD_SET(fd, &m_writeSet);
}
void SocketManager::removeWriteSocket(int fd) {
FD_CLR(fd, &m_writeSet);
}
} // namespace Cynara
|
Move adding sockets to write set to SocketManager main loop
|
Move adding sockets to write set to SocketManager main loop
Change-Id: Id06b23612992e9c134b69e42746f2af44eb0a8ec
|
C++
|
apache-2.0
|
pohly/cynara,Samsung/cynara,pohly/cynara,Samsung/cynara,pohly/cynara,Samsung/cynara
|
5be61fb31c4985a9aafddc3b6f4202375d2d5b19
|
src/slic3r/GUI/ButtonsDescription.hpp
|
src/slic3r/GUI/ButtonsDescription.hpp
|
#ifndef slic3r_ButtonsDescription_hpp
#define slic3r_ButtonsDescription_hpp
#include <wx/dialog.h>
#include <vector>
class ScalableBitmap;
namespace Slic3r {
namespace GUI {
class ButtonsDescription : public wxDialog
{
wxColourPickerCtrl* sys_colour{ nullptr };
wxColourPickerCtrl* mod_colour{ nullptr };
public:
struct Entry {
Entry(ScalableBitmap *bitmap, const std::string &symbol, const std::string &explanation) : bitmap(bitmap), symbol(symbol), explanation(explanation) {}
ScalableBitmap *bitmap;
std::string symbol;
std::string explanation;
};
ButtonsDescription(wxWindow* parent, const std::vector<Entry> &entries);
~ButtonsDescription() {}
static void FillSizerWithTextColorDescriptions(wxSizer* sizer, wxWindow* parent, wxColourPickerCtrl** sys_colour, wxColourPickerCtrl** mod_colour);
private:
std::vector<Entry> m_entries;
};
} // GUI
} // Slic3r
#endif
|
#ifndef slic3r_ButtonsDescription_hpp
#define slic3r_ButtonsDescription_hpp
#include <wx/dialog.h>
#include <vector>
class ScalableBitmap;
class wxColourPickerCtrl;
namespace Slic3r {
namespace GUI {
class ButtonsDescription : public wxDialog
{
wxColourPickerCtrl* sys_colour{ nullptr };
wxColourPickerCtrl* mod_colour{ nullptr };
public:
struct Entry {
Entry(ScalableBitmap *bitmap, const std::string &symbol, const std::string &explanation) : bitmap(bitmap), symbol(symbol), explanation(explanation) {}
ScalableBitmap *bitmap;
std::string symbol;
std::string explanation;
};
ButtonsDescription(wxWindow* parent, const std::vector<Entry> &entries);
~ButtonsDescription() {}
static void FillSizerWithTextColorDescriptions(wxSizer* sizer, wxWindow* parent, wxColourPickerCtrl** sys_colour, wxColourPickerCtrl** mod_colour);
private:
std::vector<Entry> m_entries;
};
} // GUI
} // Slic3r
#endif
|
Fix build on Linux (gcc 8.4)
|
Fix build on Linux (gcc 8.4)
|
C++
|
agpl-3.0
|
prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r
|
f3deb1a13521349b979b1d101dda335aa80c58d7
|
src/store/naive/simple_collection.cpp
|
src/store/naive/simple_collection.cpp
|
/*
* Copyright 2006-2007 FLWOR Foundation.
* Author: David Graf ([email protected])
*
*/
#include "util/rchandle.h"
#include "store/naive/simple_collection.h"
namespace xqp
{
typedef rchandle<PlanIterator> PlanIter_t;
SimpleCollection::SimpleCollection()
{
}
SimpleCollection::~SimpleCollection()
{
}
PlanIter_t SimpleCollection::getIterator ( bool isNeeded )
{
return rchandle<PlanIterator> ( NULL );
}
void SimpleCollection::addToCollection ( Item_t item, int32_t position )
{
}
void SimpleCollection::addToCollection ( PlanIter_t& items, int32_t position )
{
}
void SimpleCollection::addToCollection ( std::iostream& stream, int32_t position )
{
}
void SimpleCollection::deleteFromCollection ( int32_t position )
{
}
Item_t SimpleCollection::getURI()
{
return rchandle<Item> ( NULL );
}
} /* namespace xqp */
|
/*
* Copyright 2006-2007 FLWOR Foundation.
* Author: David Graf ([email protected])
*
*/
#include "util/rchandle.h"
#include "store/naive/simple_collection.h"
#include "store/naive/node_items.h"
namespace xqp
{
typedef rchandle<Iterator> Iterator_t;
/*******************************************************************************
********************************************************************************/
SimpleCollection::SimpleCollection()
{
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::~SimpleCollection()
{
}
/*******************************************************************************
Reads the whole Collection from beginning to end; it is allowed to have several
concurrent iterators on the same Collection.
IN idsNeeded: whether the returned items contain ids, e.g. for sorting
RET Iterator: which iterates over the complete Collection
Ids == false is likely to be faster. 'idsNeeded' should only be set to true
if clients wants to sort or compare the items or sub-items generated from the
returned iterator.
********************************************************************************/
Iterator_t SimpleCollection::getIterator ( bool idsNeeded )
{
return rchandle<Iterator> ( NULL );
}
/*******************************************************************************
Inserts data into the collection
IN item: to insert
IN position: Where to insert the item. Default -1, which means it is attached
to the end.
********************************************************************************/
void SimpleCollection::addToCollection ( Item_t item, int32_t position )
{
}
/*******************************************************************************
Inserts data into the collection
IN iterator: which produces the items to insert
IN position: Where to insert the item. Default -1, which means it is
attached to the end.
********************************************************************************/
void SimpleCollection::addToCollection ( Iterator_t& items, int32_t position )
{
}
/*******************************************************************************
Inserts data into the collection
TODO loading from SAX & DOM
IN stream: which streams the data to insert (e.g. from a file)
IN position: Where to insert the item. Default -1, which means it is
attached to the end.
********************************************************************************/
void SimpleCollection::addToCollection ( std::iostream& stream, int32_t position )
{
}
/*******************************************************************************
Deletes an item of the collection.
IN position: of the items which will be deleted
********************************************************************************/
void SimpleCollection::deleteFromCollection ( int32_t position )
{
}
/*******************************************************************************
Returns the URI of the collection
RET uri
********************************************************************************/
Item_t SimpleCollection::getURI()
{
return rchandle<Item> ( NULL );
}
} /* namespace xqp */
|
use Iterator instead of PlanIter
|
use Iterator instead of PlanIter
|
C++
|
apache-2.0
|
cezarfx/zorba,28msec/zorba,bgarrels/zorba,cezarfx/zorba,bgarrels/zorba,28msec/zorba,bgarrels/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,cezarfx/zorba,28msec/zorba,cezarfx/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,bgarrels/zorba,bgarrels/zorba,cezarfx/zorba,28msec/zorba,bgarrels/zorba,28msec/zorba,bgarrels/zorba,bgarrels/zorba,cezarfx/zorba,28msec/zorba,28msec/zorba
|
1b720f069038ce3dca9ce7fe929b809fe878f34e
|
test/runner_test.cpp
|
test/runner_test.cpp
|
/*
Copyright (c) 2012 by Procera Networks, Inc. ("PROCERA")
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
THE SOFTWARE IS PROVIDED "AS IS" AND PROCERA DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL PROCERA BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "test.hpp"
#include "runner.hpp"
#include "nexus.hpp"
using namespace koi;
using namespace std;
using namespace boost;
using namespace boost::posix_time;
namespace {
struct transition {
State from;
State to;
};
void test_transition(const char* tname, runner& r, transition* tbl, size_t len) {
for (size_t i = 0; i < len; ++i) {
r._state = tbl[i].from;
r._check_elector_transition();
if (r._state != tbl[i].to) {
printf("%s: from %s expected %s, was %s\n",
tname,
state_to_string(tbl[i].from),
state_to_string(tbl[i].to),
state_to_string(r._state));
}
REQUIRE(r._state == tbl[i].to);
}
}
}
TEST_CASE("runner/elector_transition", "Verify elector induced state transitions") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
transition master_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Live },
{ S_Stopped, S_Master },
{ S_Live, S_Master },
{ S_Slave, S_Master },
{ S_Master, S_Master }
};
transition nonmaster_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Live },
{ S_Stopped, S_Live },
{ S_Live, S_Live },
{ S_Slave, S_Slave },
{ S_Master, S_Slave }
};
transition disabled_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Stopped },
{ S_Stopped, S_Stopped },
{ S_Live, S_Stopped },
{ S_Slave, S_Stopped },
{ S_Master, S_Stopped }
};
r._enabled = true;
r._elector._master_uuid = cfg._uuid;
test_transition("master", r, master_transitions, ASIZE(master_transitions));
r._elector._master_uuid = uuid();
test_transition("nonmaster", r, nonmaster_transitions, ASIZE(nonmaster_transitions));
r._enabled = false;
r._elector._master_uuid = cfg._uuid;
test_transition("disabled-1", r, disabled_transitions, ASIZE(disabled_transitions));
r._elector._master_uuid = uuid();
test_transition("disabled-2", r, disabled_transitions, ASIZE(disabled_transitions));
r.stop();
}
TEST_CASE("runner/forget_failure", "forget_failure should move state from Failed to Disconnected") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
r._state = S_Failed;
r.forget_failure();
REQUIRE(r._state == S_Disconnected);
}
TEST_CASE("runner/check_timeouts", "Test timeout state transitions") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
cfg._runner_elector_gone_time = 100*units::milli;
cfg._runner_elector_lost_time = 50*units::milli;
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
ptime t0 = microsec_clock::universal_time();
ptime t1 = t0 + milliseconds(10);
ptime t2 = t0 + milliseconds(70);
ptime t3 = t0 + milliseconds(150);
r._elector._last_seen = t0;
r._warned_elector_lost = false;
r._state = S_Master;
r._check_timeouts(t1);
REQUIRE(r._warned_elector_lost == false);
REQUIRE(r._state == S_Master);
r._check_timeouts(t2);
REQUIRE(r._warned_elector_lost == true);
REQUIRE(r._state == S_Master);
r._check_timeouts(t3);
REQUIRE(r._warned_elector_lost == true);
REQUIRE(r._state == S_Slave);
}
|
/*
Copyright (c) 2012 by Procera Networks, Inc. ("PROCERA")
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
THE SOFTWARE IS PROVIDED "AS IS" AND PROCERA DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL PROCERA BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "test.hpp"
#include "runner.hpp"
#include "nexus.hpp"
using namespace koi;
using namespace std;
using namespace boost;
using namespace boost::posix_time;
namespace {
struct transition {
State from;
State to;
};
void test_transition(const char* tname, runner& r, transition* tbl, size_t len) {
for (size_t i = 0; i < len; ++i) {
r._state = tbl[i].from;
r._check_elector_transition();
if (r._state != tbl[i].to) {
printf("%s: from %s expected %s, was %s\n",
tname,
state_to_string(tbl[i].from),
state_to_string(tbl[i].to),
state_to_string(r._state));
}
REQUIRE(r._state == tbl[i].to);
}
}
}
TEST_CASE("runner/elector_transition", "Verify elector induced state transitions") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
transition master_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Live },
{ S_Stopped, S_Live },
{ S_Live, S_Master },
{ S_Slave, S_Master },
{ S_Master, S_Master }
};
transition nonmaster_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Live },
{ S_Stopped, S_Live },
{ S_Live, S_Live },
{ S_Slave, S_Slave },
{ S_Master, S_Slave }
};
transition disabled_transitions[] = {
{ S_Failed, S_Failed },
{ S_Disconnected, S_Stopped },
{ S_Stopped, S_Stopped },
{ S_Live, S_Stopped },
{ S_Slave, S_Stopped },
{ S_Master, S_Stopped }
};
r._enabled = true;
r._elector._master_uuid = cfg._uuid;
test_transition("master", r, master_transitions, ASIZE(master_transitions));
r._elector._master_uuid = uuid();
test_transition("nonmaster", r, nonmaster_transitions, ASIZE(nonmaster_transitions));
r._enabled = false;
r._elector._master_uuid = cfg._uuid;
test_transition("disabled-1", r, disabled_transitions, ASIZE(disabled_transitions));
r._elector._master_uuid = uuid();
test_transition("disabled-2", r, disabled_transitions, ASIZE(disabled_transitions));
r.stop();
}
TEST_CASE("runner/forget_failure", "forget_failure should move state from Failed to Disconnected") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
r._state = S_Failed;
r.forget_failure();
REQUIRE(r._state == S_Disconnected);
}
TEST_CASE("runner/check_timeouts", "Test timeout state transitions") {
vector<string> configs;
configs << "../test/test.conf";
settings cfg;
char tmp[] = "koi";
char* argv[1] = { tmp };
bool ok = cfg.boot(configs, false);
REQUIRE(ok);
cfg._runner_elector_gone_time = 100*units::milli;
cfg._runner_elector_lost_time = 50*units::milli;
net::io_service io_service;
nexus nex(io_service, cfg);
runner r(nex);
ok = r.init();
REQUIRE(ok);
r.start();
ptime t0 = microsec_clock::universal_time();
ptime t1 = t0 + milliseconds(10);
ptime t2 = t0 + milliseconds(70);
ptime t3 = t0 + milliseconds(150);
r._elector._last_seen = t0;
r._warned_elector_lost = false;
r._state = S_Master;
r._check_timeouts(t1);
REQUIRE(r._warned_elector_lost == false);
REQUIRE(r._state == S_Master);
r._check_timeouts(t2);
REQUIRE(r._warned_elector_lost == true);
REQUIRE(r._state == S_Master);
r._check_timeouts(t3);
REQUIRE(r._warned_elector_lost == true);
REQUIRE(r._state == S_Slave);
}
|
Fix state transition test-case that broke in d768330
|
Fix state transition test-case that broke in d768330
|
C++
|
isc
|
yogarajbaskaravel/koi,krig/koi,yogarajbaskaravel/koi,krig/koi,yogarajbaskaravel/koi,krig/koi,krig/koi,yogarajbaskaravel/koi
|
82f0d1a2a844af16cb604b78651da4734d2aec9e
|
test/test_buffer.cpp
|
test/test_buffer.cpp
|
/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.space_in_last_buffer() == 0);
TEST_CHECK(buffer_list.empty());
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
char data2[1024];
ret = b.append(data2, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
|
/*
Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
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 Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>
#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"
#include "test.hpp"
using namespace libtorrent;
/*
template<class T>
T const& min_(T const& x, T const& y)
{
return x < y ? x : y;
}
void test_speed()
{
buffer b;
char data[32];
srand(0);
boost::timer t;
int const iterations = 5000000;
int const step = iterations / 20;
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
b.insert(data, data + n);
}
else
{
b.erase(min_(b.size(), n));
}
}
float t1 = t.elapsed();
std::cerr << "buffer elapsed: " << t.elapsed() << "\n";
std::vector<char> v;
srand(0);
t.restart();
for (int i = 0; i < iterations; ++i)
{
int x = rand();
if (i % step == 0) std::cerr << ".";
std::size_t n = rand() % 32;
n = 32;
if (x % 2)
{
v.insert(v.end(), data, data + n);
}
else
{
v.erase(v.begin(), v.begin() + min_(v.size(), n));
}
}
float t2 = t.elapsed();
std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";
assert(t1 < t2);
}
*/
// -- test buffer --
void test_buffer()
{
char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
buffer b;
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 0);
TEST_CHECK(b.empty());
b.resize(10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(b.capacity() == 10);
std::memcpy(b.begin(), data, 10);
b.reserve(50);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
TEST_CHECK(b.capacity() == 50);
b.erase(b.begin() + 6, b.end());
TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 6);
b.insert(b.begin(), data + 5, data + 10);
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 11);
TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);
b.clear();
TEST_CHECK(b.size() == 0);
TEST_CHECK(b.capacity() == 50);
b.insert(b.end(), data, data + 10);
TEST_CHECK(b.size() == 10);
TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
b.erase(b.begin(), b.end());
TEST_CHECK(b.capacity() == 50);
TEST_CHECK(b.size() == 0);
buffer().swap(b);
TEST_CHECK(b.capacity() == 0);
}
// -- test chained buffer --
std::set<char*> buffer_list;
void free_buffer(char* m)
{
std::set<char*>::iterator i = buffer_list.find(m);
TEST_CHECK(i != buffer_list.end());
buffer_list.erase(i);
std::free(m);
}
char* allocate_buffer(int size)
{
char* mem = (char*)std::malloc(size);
buffer_list.insert(mem);
return mem;
}
template <class T>
int copy_buffers(T const& b, char* target)
{
int copied = 0;
for (typename T::const_iterator i = b.begin()
, end(b.end()); i != end; ++i)
{
memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
target += libtorrent::asio::buffer_size(*i);
copied += libtorrent::asio::buffer_size(*i);
}
return copied;
}
bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
if (size == 0) return true;
std::vector<char> flat(size);
std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
int copied = copy_buffers(iovec2, &flat[0]);
TEST_CHECK(copied == size);
return std::memcmp(&flat[0], mem, size) == 0;
}
void test_chained_buffer()
{
char data[] = "foobar";
{
chained_buffer b;
TEST_CHECK(b.empty());
TEST_EQUAL(b.capacity(), 0);
TEST_EQUAL(b.size(), 0);
TEST_EQUAL(b.space_in_last_buffer(), 0);
TEST_CHECK(buffer_list.empty());
// there are no buffers, we should not be able to allocate
// an appendix in an existing buffer
TEST_EQUAL(b.allocate_appendix(1), 0);
char* b1 = allocate_buffer(512);
std::memcpy(b1, data, 6);
b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
TEST_EQUAL(buffer_list.size(), 1);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 6);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
b.pop_front(3);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 3);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
bool ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.capacity() == 512);
TEST_CHECK(b.size() == 9);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 12);
char data2[1024];
ret = b.append(data2, 1024);
TEST_CHECK(ret == false);
char* b2 = allocate_buffer(512);
std::memcpy(b2, data, 6);
b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 2);
char* b3 = allocate_buffer(512);
std::memcpy(b3, data, 6);
b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
TEST_CHECK(buffer_list.size() == 3);
TEST_CHECK(b.capacity() == 512 * 3);
TEST_CHECK(b.size() == 21);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));
for (int i = 1; i < 21; ++i)
TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));
b.pop_front(5 + 6);
TEST_CHECK(buffer_list.size() == 2);
TEST_CHECK(b.capacity() == 512 * 2);
TEST_CHECK(b.size() == 10);
TEST_CHECK(!b.empty());
TEST_CHECK(b.space_in_last_buffer() == 512 - 6);
char const* str = "obarfooba";
TEST_CHECK(compare_chained_buffer(b, str, 9));
for (int i = 0; i < 9; ++i)
{
b.pop_front(1);
++str;
TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
TEST_CHECK(b.size() == 9 - i);
}
char* b4 = allocate_buffer(20);
std::memcpy(b4, data, 6);
std::memcpy(b4 + 6, data, 6);
b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
TEST_CHECK(b.space_in_last_buffer() == 8);
ret = b.append(data, 6);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 2);
std::cout << b.space_in_last_buffer() << std::endl;
ret = b.append(data, 2);
TEST_CHECK(ret == true);
TEST_CHECK(b.space_in_last_buffer() == 0);
std::cout << b.space_in_last_buffer() << std::endl;
char* b5 = allocate_buffer(20);
std::memcpy(b4, data, 6);
b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);
b.pop_front(22);
TEST_CHECK(b.size() == 5);
}
TEST_CHECK(buffer_list.empty());
}
int test_main()
{
test_buffer();
test_chained_buffer();
return 0;
}
|
tweak chained buffer test
|
tweak chained buffer test
git-svn-id: 6ed3528c1be4534134272ad6dd050eeaa1f628d3@9927 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
|
C++
|
bsd-3-clause
|
svn2github/libtorrent-trunk,svn2github/libtorrent-trunk,svn2github/libtorrent-trunk,svn2github/libtorrent-trunk
|
f12d42c23df584831266e7d962bdf4191e6cd928
|
xls/netlist/function_extractor.cc
|
xls/netlist/function_extractor.cc
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/netlist/function_extractor.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_split.h"
#include "absl/types/variant.h"
#include "xls/common/logging/logging.h"
#include "xls/common/status/ret_check.h"
#include "xls/common/status/status_macros.h"
#include "xls/netlist/lib_parser.h"
#include "xls/netlist/netlist.pb.h"
namespace xls {
namespace netlist {
namespace function {
namespace {
constexpr const char kDirectionKey[] = "direction";
constexpr const char kFunctionKey[] = "function";
constexpr const char kNextStateKey[] = "next_state";
constexpr const char kStateFunctionKey[] = "state_function";
constexpr const char kInputValue[] = "input";
constexpr const char kOutputValue[] = "output";
constexpr const char kPinKind[] = "pin";
constexpr const char kFfKind[] = "ff";
constexpr const char kStateTableKind[] = "statetable";
// Translates an individual signal value char to the protobuf equivalent.
xabsl::StatusOr<StateTableSignal> LibertyToTableSignal(
const std::string& input) {
XLS_RET_CHECK(input.size() == 1) << input;
char signal = input[0];
XLS_RET_CHECK(signal == '-' || signal == 'H' || signal == 'L' ||
signal == 'N' || signal == 'T' || signal == 'X');
switch (signal) {
case '-':
return STATE_TABLE_SIGNAL_DONTCARE;
case 'H':
return STATE_TABLE_SIGNAL_HIGH;
case 'L':
return STATE_TABLE_SIGNAL_LOW;
case 'N':
return STATE_TABLE_SIGNAL_NOCHANGE;
case 'T':
return STATE_TABLE_SIGNAL_TOGGLE;
case 'X':
return STATE_TABLE_SIGNAL_X;
default:
XLS_LOG(FATAL) << "Invalid input signal!";
}
}
absl::string_view SanitizeRow(const absl::string_view& row) {
// Remove newlines, whitespace, and occasional extraneous slash characters
// from a row in the state table: there are rows that appear as, for example:
// X X X : Y : Z ,\
// It makes life a lot easier if we can just deal with the range from X to Z.
absl::string_view result = absl::StripAsciiWhitespace(row);
if (result[0] == '\\') {
result.remove_prefix(1);
}
result = absl::StripAsciiWhitespace(result);
return result;
}
// Parses a textual Liberty statetable entry to a proto.
// This doesn't attempt to _validate_ the specified state table; it only
// proto-izes it.
// Returns a map of internal signal to state table defining its behavior.
absl::Status ProcessStateTable(const cell_lib::Block& table_def,
CellLibraryEntryProto* proto) {
StateTableProto* table = proto->mutable_state_table();
for (absl::string_view name : absl::StrSplit(table_def.args[0], ' ')) {
table->add_input_names(name);
}
for (absl::string_view name : absl::StrSplit(table_def.args[1], ' ')) {
table->add_internal_names(name);
}
XLS_RET_CHECK(table_def.entries.size() == 1);
XLS_RET_CHECK(
absl::holds_alternative<cell_lib::KVEntry>(table_def.entries[0]));
const cell_lib::KVEntry& table_entry =
absl::get<cell_lib::KVEntry>(table_def.entries[0]);
// Table entries are, sadly, strings, such as:
// " L H L : - : H,
// H L H : - : L,
// ... "
// So we gotta comma separate then colon separate them to get the important
// bits. The first column is the input signals, ordered as in the first arg.
std::vector<std::string> rows =
absl::StrSplit(table_entry.value, ',', absl::SkipWhitespace());
for (const std::string& raw_row : rows) {
absl::string_view source_row = SanitizeRow(raw_row);
std::vector<std::string> fields =
absl::StrSplit(source_row, ':', absl::SkipWhitespace());
XLS_RET_CHECK(fields.size() == 3)
<< "Improperly formatted row: " << source_row;
std::vector<std::string> inputs =
absl::StrSplit(fields[0], ' ', absl::SkipWhitespace());
std::vector<std::string> internal_inputs =
absl::StrSplit(fields[1], ' ', absl::SkipWhitespace());
std::vector<std::string> internal_outputs =
absl::StrSplit(fields[2], ' ', absl::SkipWhitespace());
StateTableRow* row = table->add_rows();
for (int i = 0; i < inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(inputs[i]));
(*row->mutable_input_signals())[table->input_names()[i]] = signal;
}
for (int i = 0; i < internal_inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(internal_inputs[i]));
(*row->mutable_internal_signals())[table->internal_names()[i]] = signal;
}
for (int i = 0; i < internal_inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(internal_outputs[i]));
(*row->mutable_output_signals())[table->internal_names()[i]] = signal;
}
}
return absl::OkStatus();
}
// Gets input and output pin names and output pin functions and adds them to the
// entry proto.
absl::Status ExtractFromPin(const cell_lib::Block& pin,
CellLibraryEntryProto* entry_proto) {
// I've yet to see an example where this isn't the case.
std::string name = pin.args[0];
absl::optional<bool> is_output;
std::string function;
for (const cell_lib::BlockEntry& entry : pin.entries) {
const auto* kv_entry = absl::get_if<cell_lib::KVEntry>(&entry);
if (kv_entry) {
if (kv_entry->key == kDirectionKey) {
if (kv_entry->value == kOutputValue) {
is_output = true;
} else if (kv_entry->value == kInputValue) {
is_output = false;
} else {
// "internal" is at least one add'l direction.
// We don't care about such pins.
return absl::OkStatus();
}
} else if (kv_entry->key == kFunctionKey ||
kv_entry->key == kStateFunctionKey) {
// "function" and "state_function" seem to be handlable in the same way:
// state_function can deal with special cases that function can't (such
// as use of internal ports)...but the internal logic appears to be the
// same.
function = kv_entry->value;
}
}
}
if (is_output == absl::nullopt) {
return absl::InvalidArgumentError(
absl::StrFormat("Pin %s has no direction entry!", name));
}
if (is_output.value()) {
OutputPinProto* output_pin = entry_proto->add_output_pins();
output_pin->set_name(name);
if (!function.empty()) {
// Some output pins lack associated functions.
// Ignore them for now (during baseline dev). If they turn out to be
// important, I'll circle back.
output_pin->set_function(function);
}
} else {
entry_proto->add_input_names(name);
}
return absl::OkStatus();
}
// If we see a ff (flop-flop) block, it contains a "next_state" field, with the
// function calculating the output value of the cell after the next clock.
// Since all our current (logic-checking) purposes are clockless, this is
// equivalent to being the "function" of an output pin. All known FF cells have
// a single output pin, so we sanity check for that.
// If so, then we replace that function with the one from the next_state field.
absl::Status ExtractFromFf(const cell_lib::Block& ff,
CellLibraryEntryProto* entry_proto) {
entry_proto->set_kind(netlist::CellKindProto::FLOP);
for (const cell_lib::BlockEntry& entry : ff.entries) {
const auto* kv_entry = absl::get_if<cell_lib::KVEntry>(&entry);
if (kv_entry && kv_entry->key == kNextStateKey) {
std::string next_state_function = kv_entry->value;
XLS_RET_CHECK(entry_proto->output_pins_size() == 1);
entry_proto->mutable_output_pins(0)->set_function(next_state_function);
}
}
return absl::OkStatus();
}
absl::Status ExtractFromCell(const cell_lib::Block& cell,
CellLibraryEntryProto* entry_proto) {
// I've yet to see an example where this isn't the case.
entry_proto->set_name(cell.args[0]);
// Default kind; overridden only if necessary.
entry_proto->set_kind(netlist::CellKindProto::OTHER);
for (const cell_lib::BlockEntry& entry : cell.entries) {
if (absl::holds_alternative<std::unique_ptr<cell_lib::Block>>(entry)) {
auto& block_entry = absl::get<std::unique_ptr<cell_lib::Block>>(entry);
if (block_entry->kind == kPinKind) {
XLS_RETURN_IF_ERROR(ExtractFromPin(*block_entry.get(), entry_proto));
} else if (block_entry->kind == kFfKind) {
// If it's a flip-flop, we need to replace the pin's output function
// with its next_state function.
XLS_RETURN_IF_ERROR(ExtractFromFf(*block_entry.get(), entry_proto));
} else if (block_entry->kind == kStateTableKind) {
XLS_RETURN_IF_ERROR(ProcessStateTable(*block_entry.get(), entry_proto));
}
}
}
return absl::OkStatus();
}
} // namespace
xabsl::StatusOr<CellLibraryProto> ExtractFunctions(
cell_lib::CharStream* stream) {
cell_lib::Scanner scanner(stream);
absl::flat_hash_set<std::string> kind_allowlist(
{"library", "cell", "pin", "direction", "function", "ff", "next_state",
"statetable"});
cell_lib::Parser parser(&scanner);
XLS_ASSIGN_OR_RETURN(std::unique_ptr<cell_lib::Block> block,
parser.ParseLibrary());
CellLibraryProto proto;
for (const cell_lib::BlockEntry& entry : block->entries) {
if (absl::holds_alternative<std::unique_ptr<cell_lib::Block>>(entry)) {
auto& block_entry = absl::get<std::unique_ptr<cell_lib::Block>>(entry);
if (block_entry->kind == "cell") {
CellLibraryEntryProto* entry_proto = proto.add_entries();
XLS_RETURN_IF_ERROR(ExtractFromCell(*block_entry.get(), entry_proto));
}
}
}
return proto;
}
} // namespace function
} // namespace netlist
} // namespace xls
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/netlist/function_extractor.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_split.h"
#include "absl/types/variant.h"
#include "xls/common/logging/logging.h"
#include "xls/common/status/ret_check.h"
#include "xls/common/status/status_macros.h"
#include "xls/netlist/lib_parser.h"
#include "xls/netlist/netlist.pb.h"
namespace xls {
namespace netlist {
namespace function {
namespace {
constexpr const char kDirectionKey[] = "direction";
constexpr const char kFunctionKey[] = "function";
constexpr const char kNextStateKey[] = "next_state";
constexpr const char kStateFunctionKey[] = "state_function";
constexpr const char kInputValue[] = "input";
constexpr const char kOutputValue[] = "output";
constexpr const char kPinKind[] = "pin";
constexpr const char kFfKind[] = "ff";
constexpr const char kStateTableKind[] = "statetable";
// Translates an individual signal value char to the protobuf equivalent.
xabsl::StatusOr<StateTableSignal> LibertyToTableSignal(
const std::string& input) {
XLS_RET_CHECK(input.size() == 1) << input;
char signal = input[0];
XLS_RET_CHECK(signal == '-' || signal == 'H' || signal == 'L' ||
signal == 'N' || signal == 'T' || signal == 'X');
switch (signal) {
case '-':
return STATE_TABLE_SIGNAL_DONTCARE;
case 'H':
return STATE_TABLE_SIGNAL_HIGH;
case 'L':
return STATE_TABLE_SIGNAL_LOW;
case 'N':
return STATE_TABLE_SIGNAL_NOCHANGE;
case 'T':
return STATE_TABLE_SIGNAL_TOGGLE;
case 'X':
return STATE_TABLE_SIGNAL_X;
default:
XLS_LOG(FATAL) << "Invalid input signal!";
}
}
absl::string_view SanitizeRow(const absl::string_view& row) {
// Remove newlines, whitespace, and occasional extraneous slash characters
// from a row in the state table: there are rows that appear as, for example:
// X X X : Y : Z ,\
// It makes life a lot easier if we can just deal with the range from X to Z.
absl::string_view result = absl::StripAsciiWhitespace(row);
if (result[0] == '\\') {
result.remove_prefix(1);
}
result = absl::StripAsciiWhitespace(result);
return result;
}
// Parses a textual Liberty statetable entry to a proto.
// This doesn't attempt to _validate_ the specified state table; it only
// proto-izes it.
// Returns a map of internal signal to state table defining its behavior.
absl::Status ProcessStateTable(const cell_lib::Block& table_def,
CellLibraryEntryProto* proto) {
StateTableProto* table = proto->mutable_state_table();
for (absl::string_view name : absl::StrSplit(table_def.args[0], ' ')) {
table->add_input_names(std::string(name));
}
for (absl::string_view name : absl::StrSplit(table_def.args[1], ' ')) {
table->add_internal_names(std::string(name));
}
XLS_RET_CHECK(table_def.entries.size() == 1);
XLS_RET_CHECK(
absl::holds_alternative<cell_lib::KVEntry>(table_def.entries[0]));
const cell_lib::KVEntry& table_entry =
absl::get<cell_lib::KVEntry>(table_def.entries[0]);
// Table entries are, sadly, strings, such as:
// " L H L : - : H,
// H L H : - : L,
// ... "
// So we gotta comma separate then colon separate them to get the important
// bits. The first column is the input signals, ordered as in the first arg.
std::vector<std::string> rows =
absl::StrSplit(table_entry.value, ',', absl::SkipWhitespace());
for (const std::string& raw_row : rows) {
absl::string_view source_row = SanitizeRow(raw_row);
std::vector<std::string> fields =
absl::StrSplit(source_row, ':', absl::SkipWhitespace());
XLS_RET_CHECK(fields.size() == 3)
<< "Improperly formatted row: " << source_row;
std::vector<std::string> inputs =
absl::StrSplit(fields[0], ' ', absl::SkipWhitespace());
std::vector<std::string> internal_inputs =
absl::StrSplit(fields[1], ' ', absl::SkipWhitespace());
std::vector<std::string> internal_outputs =
absl::StrSplit(fields[2], ' ', absl::SkipWhitespace());
StateTableRow* row = table->add_rows();
for (int i = 0; i < inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(inputs[i]));
(*row->mutable_input_signals())[table->input_names()[i]] = signal;
}
for (int i = 0; i < internal_inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(internal_inputs[i]));
(*row->mutable_internal_signals())[table->internal_names()[i]] = signal;
}
for (int i = 0; i < internal_inputs.size(); i++) {
XLS_ASSIGN_OR_RETURN(StateTableSignal signal,
LibertyToTableSignal(internal_outputs[i]));
(*row->mutable_output_signals())[table->internal_names()[i]] = signal;
}
}
return absl::OkStatus();
}
// Gets input and output pin names and output pin functions and adds them to the
// entry proto.
absl::Status ExtractFromPin(const cell_lib::Block& pin,
CellLibraryEntryProto* entry_proto) {
// I've yet to see an example where this isn't the case.
std::string name = pin.args[0];
absl::optional<bool> is_output;
std::string function;
for (const cell_lib::BlockEntry& entry : pin.entries) {
const auto* kv_entry = absl::get_if<cell_lib::KVEntry>(&entry);
if (kv_entry) {
if (kv_entry->key == kDirectionKey) {
if (kv_entry->value == kOutputValue) {
is_output = true;
} else if (kv_entry->value == kInputValue) {
is_output = false;
} else {
// "internal" is at least one add'l direction.
// We don't care about such pins.
return absl::OkStatus();
}
} else if (kv_entry->key == kFunctionKey ||
kv_entry->key == kStateFunctionKey) {
// "function" and "state_function" seem to be handlable in the same way:
// state_function can deal with special cases that function can't (such
// as use of internal ports)...but the internal logic appears to be the
// same.
function = kv_entry->value;
}
}
}
if (is_output == absl::nullopt) {
return absl::InvalidArgumentError(
absl::StrFormat("Pin %s has no direction entry!", name));
}
if (is_output.value()) {
OutputPinProto* output_pin = entry_proto->add_output_pins();
output_pin->set_name(name);
if (!function.empty()) {
// Some output pins lack associated functions.
// Ignore them for now (during baseline dev). If they turn out to be
// important, I'll circle back.
output_pin->set_function(function);
}
} else {
entry_proto->add_input_names(name);
}
return absl::OkStatus();
}
// If we see a ff (flop-flop) block, it contains a "next_state" field, with the
// function calculating the output value of the cell after the next clock.
// Since all our current (logic-checking) purposes are clockless, this is
// equivalent to being the "function" of an output pin. All known FF cells have
// a single output pin, so we sanity check for that.
// If so, then we replace that function with the one from the next_state field.
absl::Status ExtractFromFf(const cell_lib::Block& ff,
CellLibraryEntryProto* entry_proto) {
entry_proto->set_kind(netlist::CellKindProto::FLOP);
for (const cell_lib::BlockEntry& entry : ff.entries) {
const auto* kv_entry = absl::get_if<cell_lib::KVEntry>(&entry);
if (kv_entry && kv_entry->key == kNextStateKey) {
std::string next_state_function = kv_entry->value;
XLS_RET_CHECK(entry_proto->output_pins_size() == 1);
entry_proto->mutable_output_pins(0)->set_function(next_state_function);
}
}
return absl::OkStatus();
}
absl::Status ExtractFromCell(const cell_lib::Block& cell,
CellLibraryEntryProto* entry_proto) {
// I've yet to see an example where this isn't the case.
entry_proto->set_name(cell.args[0]);
// Default kind; overridden only if necessary.
entry_proto->set_kind(netlist::CellKindProto::OTHER);
for (const cell_lib::BlockEntry& entry : cell.entries) {
if (absl::holds_alternative<std::unique_ptr<cell_lib::Block>>(entry)) {
auto& block_entry = absl::get<std::unique_ptr<cell_lib::Block>>(entry);
if (block_entry->kind == kPinKind) {
XLS_RETURN_IF_ERROR(ExtractFromPin(*block_entry.get(), entry_proto));
} else if (block_entry->kind == kFfKind) {
// If it's a flip-flop, we need to replace the pin's output function
// with its next_state function.
XLS_RETURN_IF_ERROR(ExtractFromFf(*block_entry.get(), entry_proto));
} else if (block_entry->kind == kStateTableKind) {
XLS_RETURN_IF_ERROR(ProcessStateTable(*block_entry.get(), entry_proto));
}
}
}
return absl::OkStatus();
}
} // namespace
xabsl::StatusOr<CellLibraryProto> ExtractFunctions(
cell_lib::CharStream* stream) {
cell_lib::Scanner scanner(stream);
absl::flat_hash_set<std::string> kind_allowlist(
{"library", "cell", "pin", "direction", "function", "ff", "next_state",
"statetable"});
cell_lib::Parser parser(&scanner);
XLS_ASSIGN_OR_RETURN(std::unique_ptr<cell_lib::Block> block,
parser.ParseLibrary());
CellLibraryProto proto;
for (const cell_lib::BlockEntry& entry : block->entries) {
if (absl::holds_alternative<std::unique_ptr<cell_lib::Block>>(entry)) {
auto& block_entry = absl::get<std::unique_ptr<cell_lib::Block>>(entry);
if (block_entry->kind == "cell") {
CellLibraryEntryProto* entry_proto = proto.add_entries();
XLS_RETURN_IF_ERROR(ExtractFromCell(*block_entry.get(), entry_proto));
}
}
}
return proto;
}
} // namespace function
} // namespace netlist
} // namespace xls
|
Fix compile error: either gcc doesn't like absl::string_view -> std::string implicit conversion or internal absl has different operators defined.
|
Fix compile error: either gcc doesn't like absl::string_view -> std::string implicit conversion or internal absl has different operators defined.
PiperOrigin-RevId: 324645189
|
C++
|
apache-2.0
|
google/xls,google/xls,google/xls,google/xls,google/xls,google/xls
|
cc0be6ba4138432d7356147faaa538e69f2b09ef
|
tutorials/proof/ProcFileElements.C
|
tutorials/proof/ProcFileElements.C
|
//////////////////////////////////////////////////////////////////////////
// //
// ProcFileElements //
// //
// This class holds information about the processed elements of a file. //
// Used for testing. //
// //
//////////////////////////////////////////////////////////////////////////
#include "ProcFileElements.h"
#include "TCollection.h"
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::Compare(const TObject *o) const
{
// Compare this element with 'e'.
// Return
// -1 this should come first
// 0 same
// 1 e should come first
const ProcFileElements::ProcFileElement *e =
dynamic_cast<const ProcFileElements::ProcFileElement *>(o);
if (!e) return -1;
if (fFirst == e->fFirst) {
// They start at the same point
return 0;
} else if (fFirst < e->fFirst) {
// This starts first
return -1;
} else {
// e starts first
return 1;
}
}
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::Overlapping(ProcFileElement *e)
{
// Check overlapping status of this element with 'e'.
// Return
// -1 not overlapping
// 0 adjacent
// 1 overlapping
if (!e) return -1;
if (fFirst == 0 && fLast == -1) {
// We cover the full range, so we overlap
return 1;
}
if (fFirst < e->fFirst) {
if (fLast >= 0) {
if (fLast < e->fFirst - 1) {
// Disjoint
return -1;
} else {
// We somehow overlap
if (fLast == e->fFirst - 1) {
// Just adjacent
return 0;
} else {
// Real overlap
return 1;
}
}
} else {
// Always overlapping
return 1;
}
} else if (fFirst == e->fFirst) {
// Overlapping or illy adjacent
if (fFirst == fLast || e->fFirst == e->fLast) return 0;
return 1;
} else {
// The other way around
if (e->fLast >= 0) {
if (e->fLast < fFirst - 1) {
// Disjoint
return -1;
} else {
// We somehow overlap
if (e->fLast == fFirst - 1) {
// Just adjacent
return 0;
} else {
// Real overlap
return 1;
}
}
} else {
// Always overlapping
return 1;
}
}
// Should never be here
Warning("Overlapping", "should never be here!");
return -1;
}
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::MergeElement(ProcFileElement *e)
{
// Merge this element with element 'e'.
// Return -1 if it cannot be done, i.e. thei are disjoint; 0 otherwise
// Check if it can be done
if (Overlapping(e) < 0) return -1;
// Ok, we can merge: set the lower bound
if (e->fFirst < fFirst) fFirst = e->fFirst;
// Set the upper bound
if (fLast == -1 || e->fLast == -1) {
fLast = -1;
} else {
if (fLast < e->fLast) fLast = e->fLast;
}
// Done
return 0;
}
//_______________________________________________________________________
void ProcFileElements::ProcFileElement::Print(Option_t *) const
{
// Print range of this element
Printf("\tfirst: %lld\t last: %lld", fFirst, fLast);
}
//_______________________________________________________________________
Int_t ProcFileElements::Add(Long64_t fst, Long64_t lst)
{
// Add a new element to the list
// Return 1 if a new element has been added, 0 if it has been merged
// with an existing one, -1 in case of error
if (!fElements) fElements = new TSortedList;
if (!fElements) {
Error("Add", "could not create internal list!");
return -1;
}
// Create (tempoarry element)
ProcFileElements::ProcFileElement *ne =
new ProcFileElements::ProcFileElement(fst, lst);
// Check if if it is adjacent or overalapping with an existing one
TIter nxe(fElements);
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) {
if (e->MergeElement(ne) == 0) break;
}
Int_t rc = 0;
// Remove and re-add the merged element to sort correctly its possibly new position
if (e) {
fElements->Remove(e);
fElements->Add(e);
SafeDelete(ne);
} else {
// Add the new element
fElements->Add(ne);
rc = 1;
}
// New overall ranges
if (fElements) {
if ((e = (ProcFileElements::ProcFileElement *) fElements->First())) fFirst = e->fFirst;
if ((e = (ProcFileElements::ProcFileElement *) fElements->Last())) fLast = e->fLast;
}
// Done
return rc;
}
//_______________________________________________________________________
void ProcFileElements::Print(Option_t *) const
{
// Print info about this processed file
Printf("--- ProcFileElements ----------------------------------------");
Printf(" File: %s", fName.Data());
Printf(" # proc elements: %d", fElements ? fElements->GetSize() : 0);
TIter nxe(fElements);
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) { e->Print(); }
Printf(" Raw overall range: [%lld, %lld]", fFirst, fLast);
Printf("-------------------------------------------------------------");
}
//_______________________________________________________________________
Int_t ProcFileElements::Merge(TCollection *li)
{
// Merge this object with those in the list
// Return number of elements added
if (!li) return -1;
if (li->GetSize() <= 0) return 0;
Int_t nadd = 0;
TIter nxo(li);
ProcFileElements *pfe = 0;
while ((pfe = (ProcFileElements *) nxo())) {
if (strcmp(GetName(), pfe->GetName()))
Warning("Merge", "merging objects of different name! ('%s' != '%s')",
GetName(), pfe->GetName());
TIter nxe(pfe->GetListOfElements());
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) {
Int_t rc = Add(e->fFirst, e->fLast);
if (rc == 1) nadd++;
}
}
// Done
return nadd;
}
|
//////////////////////////////////////////////////////////////////////////
// //
// ProcFileElements //
// //
// This class holds information about the processed elements of a file. //
// Used for testing. //
// //
//////////////////////////////////////////////////////////////////////////
#include "ProcFileElements.h"
#include "TCollection.h"
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::Compare(const TObject *o) const
{
// Compare this element with 'e'.
// Return
// -1 this should come first
// 0 same
// 1 e should come first
const ProcFileElements::ProcFileElement *e =
dynamic_cast<const ProcFileElements::ProcFileElement *>(o);
if (!e) return -1;
if (fFirst == e->fFirst) {
// They start at the same point
return 0;
} else if (fFirst < e->fFirst) {
// This starts first
return -1;
} else {
// e starts first
return 1;
}
}
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::Overlapping(ProcFileElement *e)
{
// Check overlapping status of this element with 'e'.
// Return
// -1 not overlapping
// 0 adjacent
// 1 overlapping
if (!e) return -1;
if (fFirst == 0 && fLast == -1) {
// We cover the full range, so we overlap
return 1;
}
if (fFirst < e->fFirst) {
if (fLast >= 0) {
if (fLast < e->fFirst - 1) {
// Disjoint
return -1;
} else {
// We somehow overlap
if (fLast == e->fFirst - 1) {
// Just adjacent
return 0;
} else {
// Real overlap
return 1;
}
}
} else {
// Always overlapping
return 1;
}
} else if (fFirst == e->fFirst) {
// Overlapping or adjacent
if (fFirst == fLast || e->fFirst == e->fLast) return 0;
return 1;
} else {
// The other way around
if (e->fLast >= 0) {
if (e->fLast < fFirst - 1) {
// Disjoint
return -1;
} else {
// We somehow overlap
if (e->fLast == fFirst - 1) {
// Just adjacent
return 0;
} else {
// Real overlap
return 1;
}
}
} else {
// Always overlapping
return 1;
}
}
// Should never be here
Warning("Overlapping", "should never be here!");
return -1;
}
//_______________________________________________________________________
Int_t ProcFileElements::ProcFileElement::MergeElement(ProcFileElement *e)
{
// Merge this element with element 'e'.
// Return -1 if it cannot be done, i.e. thei are disjoint; 0 otherwise
// Check if it can be done
if (Overlapping(e) < 0) return -1;
// Ok, we can merge: set the lower bound
if (e->fFirst < fFirst) fFirst = e->fFirst;
// Set the upper bound
if (fLast == -1 || e->fLast == -1) {
fLast = -1;
} else {
if (fLast < e->fLast) fLast = e->fLast;
}
// Done
return 0;
}
//_______________________________________________________________________
void ProcFileElements::ProcFileElement::Print(Option_t *) const
{
// Print range of this element
Printf("\tfirst: %lld\t last: %lld", fFirst, fLast);
}
//_______________________________________________________________________
Int_t ProcFileElements::Add(Long64_t fst, Long64_t lst)
{
// Add a new element to the list
// Return 1 if a new element has been added, 0 if it has been merged
// with an existing one, -1 in case of error
if (!fElements) fElements = new TSortedList;
if (!fElements) {
Error("Add", "could not create internal list!");
return -1;
}
// Create (temporary element)
ProcFileElements::ProcFileElement *ne =
new ProcFileElements::ProcFileElement(fst, lst);
// Check if if it is adjacent or overlapping with an existing one
TIter nxe(fElements);
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) {
if (e->MergeElement(ne) == 0) break;
}
Int_t rc = 0;
// Remove and re-add the merged element to sort correctly its possibly new position
if (e) {
fElements->Remove(e);
fElements->Add(e);
SafeDelete(ne);
} else {
// Add the new element
fElements->Add(ne);
rc = 1;
}
// Make sure that all what can be merged is merged (because of the order, some elements
// which could be merged are not merged, making the determination of fFirst and fLast below
// to give incorrect values)
ProcFileElements::ProcFileElement *ep = 0, *en = 0;
TObjLink *olp = fElements->FirstLink(), *oln = 0;
while (olp && (ep = (ProcFileElements::ProcFileElement *) olp->GetObject())) {
oln = olp->Next();
while (oln) {
if ((en = (ProcFileElements::ProcFileElement *) oln->GetObject())) {
if (ep->MergeElement(en) == 0) {
fElements->Remove(en);
delete en;
}
}
oln = oln->Next();
}
olp = olp->Next();
}
// New overall ranges
if ((e = (ProcFileElements::ProcFileElement *) fElements->First())) fFirst = e->fFirst;
if ((e = (ProcFileElements::ProcFileElement *) fElements->Last())) fLast = e->fLast;
// Done
return rc;
}
//_______________________________________________________________________
void ProcFileElements::Print(Option_t *) const
{
// Print info about this processed file
Printf("--- ProcFileElements ----------------------------------------");
Printf(" File: %s", fName.Data());
Printf(" # proc elements: %d", fElements ? fElements->GetSize() : 0);
TIter nxe(fElements);
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) { e->Print(); }
Printf(" Raw overall range: [%lld, %lld]", fFirst, fLast);
Printf("-------------------------------------------------------------");
}
//_______________________________________________________________________
Int_t ProcFileElements::Merge(TCollection *li)
{
// Merge this object with those in the list
// Return number of elements added
if (!li) return -1;
if (li->GetSize() <= 0) return 0;
Int_t nadd = 0;
TIter nxo(li);
ProcFileElements *pfe = 0;
while ((pfe = (ProcFileElements *) nxo())) {
if (strcmp(GetName(), pfe->GetName()))
Warning("Merge", "merging objects of different name! ('%s' != '%s')",
GetName(), pfe->GetName());
TIter nxe(pfe->GetListOfElements());
ProcFileElements::ProcFileElement *e = 0;
while ((e = (ProcFileElements::ProcFileElement *)nxe())) {
Int_t rc = Add(e->fFirst, e->fLast);
if (rc == 1) nadd++;
}
}
// Done
return nadd;
}
|
Add loop to make sure that all overlapping or adjacent elements are merged
|
Add loop to make sure that all overlapping or adjacent elements are merged
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@45643 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
alexschlueter/cern-root,bbockelm/root,abhinavmoudgil95/root,mhuwiler/rootauto,abhinavmoudgil95/root,veprbl/root,beniz/root,omazapa/root-old,sirinath/root,esakellari/my_root_for_test,lgiommi/root,vukasinmilosevic/root,gganis/root,sbinet/cxx-root,arch1tect0r/root,alexschlueter/cern-root,zzxuanyuan/root,sbinet/cxx-root,CristinaCristescu/root,bbockelm/root,alexschlueter/cern-root,georgtroska/root,zzxuanyuan/root,karies/root,zzxuanyuan/root-compressor-dummy,nilqed/root,alexschlueter/cern-root,root-mirror/root,krafczyk/root,vukasinmilosevic/root,0x0all/ROOT,zzxuanyuan/root,veprbl/root,cxx-hep/root-cern,jrtomps/root,abhinavmoudgil95/root,sawenzel/root,vukasinmilosevic/root,simonpf/root,root-mirror/root,gbitzes/root,Duraznos/root,thomaskeck/root,karies/root,karies/root,jrtomps/root,georgtroska/root,buuck/root,BerserkerTroll/root,agarciamontoro/root,georgtroska/root,sawenzel/root,esakellari/my_root_for_test,satyarth934/root,karies/root,smarinac/root,mhuwiler/rootauto,root-mirror/root,jrtomps/root,esakellari/root,gbitzes/root,buuck/root,smarinac/root,veprbl/root,omazapa/root-old,simonpf/root,mhuwiler/rootauto,arch1tect0r/root,beniz/root,arch1tect0r/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,esakellari/root,simonpf/root,pspe/root,omazapa/root-old,Y--/root,olifre/root,sbinet/cxx-root,omazapa/root-old,simonpf/root,agarciamontoro/root,perovic/root,vukasinmilosevic/root,sawenzel/root,nilqed/root,esakellari/root,pspe/root,veprbl/root,0x0all/ROOT,abhinavmoudgil95/root,arch1tect0r/root,gbitzes/root,cxx-hep/root-cern,karies/root,satyarth934/root,georgtroska/root,davidlt/root,zzxuanyuan/root,Duraznos/root,veprbl/root,gbitzes/root,dfunke/root,veprbl/root,sawenzel/root,krafczyk/root,arch1tect0r/root,smarinac/root,mhuwiler/rootauto,arch1tect0r/root,mkret2/root,omazapa/root,simonpf/root,BerserkerTroll/root,sirinath/root,agarciamontoro/root,davidlt/root,bbockelm/root,buuck/root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,bbockelm/root,nilqed/root,arch1tect0r/root,Duraznos/root,Y--/root,buuck/root,abhinavmoudgil95/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,beniz/root,sbinet/cxx-root,buuck/root,buuck/root,mhuwiler/rootauto,olifre/root,esakellari/my_root_for_test,CristinaCristescu/root,beniz/root,pspe/root,satyarth934/root,thomaskeck/root,lgiommi/root,agarciamontoro/root,agarciamontoro/root,satyarth934/root,esakellari/my_root_for_test,thomaskeck/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,pspe/root,olifre/root,gbitzes/root,BerserkerTroll/root,lgiommi/root,CristinaCristescu/root,jrtomps/root,0x0all/ROOT,vukasinmilosevic/root,evgeny-boger/root,georgtroska/root,pspe/root,bbockelm/root,sirinath/root,omazapa/root,krafczyk/root,gganis/root,root-mirror/root,perovic/root,CristinaCristescu/root,sbinet/cxx-root,simonpf/root,zzxuanyuan/root,zzxuanyuan/root,mkret2/root,krafczyk/root,vukasinmilosevic/root,lgiommi/root,evgeny-boger/root,root-mirror/root,perovic/root,esakellari/my_root_for_test,smarinac/root,CristinaCristescu/root,esakellari/my_root_for_test,mkret2/root,dfunke/root,gbitzes/root,dfunke/root,krafczyk/root,perovic/root,dfunke/root,esakellari/my_root_for_test,zzxuanyuan/root,lgiommi/root,satyarth934/root,cxx-hep/root-cern,mkret2/root,sirinath/root,bbockelm/root,omazapa/root,Y--/root,veprbl/root,abhinavmoudgil95/root,davidlt/root,gganis/root,nilqed/root,omazapa/root,omazapa/root,mkret2/root,Y--/root,agarciamontoro/root,pspe/root,zzxuanyuan/root,sbinet/cxx-root,dfunke/root,krafczyk/root,smarinac/root,0x0all/ROOT,Duraznos/root,Y--/root,nilqed/root,Y--/root,georgtroska/root,thomaskeck/root,omazapa/root,georgtroska/root,jrtomps/root,pspe/root,agarciamontoro/root,sirinath/root,esakellari/root,esakellari/root,Y--/root,Duraznos/root,BerserkerTroll/root,davidlt/root,nilqed/root,sawenzel/root,perovic/root,omazapa/root,vukasinmilosevic/root,omazapa/root-old,nilqed/root,zzxuanyuan/root-compressor-dummy,mkret2/root,georgtroska/root,pspe/root,mattkretz/root,sawenzel/root,esakellari/root,omazapa/root,olifre/root,root-mirror/root,sirinath/root,satyarth934/root,pspe/root,krafczyk/root,dfunke/root,Duraznos/root,mkret2/root,buuck/root,lgiommi/root,Duraznos/root,Y--/root,thomaskeck/root,davidlt/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,olifre/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,pspe/root,vukasinmilosevic/root,arch1tect0r/root,gganis/root,simonpf/root,sawenzel/root,0x0all/ROOT,vukasinmilosevic/root,root-mirror/root,agarciamontoro/root,gbitzes/root,beniz/root,arch1tect0r/root,mattkretz/root,zzxuanyuan/root,smarinac/root,davidlt/root,agarciamontoro/root,sbinet/cxx-root,BerserkerTroll/root,omazapa/root-old,smarinac/root,lgiommi/root,abhinavmoudgil95/root,bbockelm/root,cxx-hep/root-cern,bbockelm/root,abhinavmoudgil95/root,smarinac/root,krafczyk/root,mattkretz/root,smarinac/root,Duraznos/root,sirinath/root,thomaskeck/root,olifre/root,cxx-hep/root-cern,bbockelm/root,beniz/root,Y--/root,BerserkerTroll/root,satyarth934/root,sbinet/cxx-root,perovic/root,gganis/root,esakellari/root,satyarth934/root,evgeny-boger/root,mattkretz/root,buuck/root,zzxuanyuan/root,sawenzel/root,thomaskeck/root,omazapa/root-old,olifre/root,buuck/root,mhuwiler/rootauto,perovic/root,arch1tect0r/root,dfunke/root,mhuwiler/rootauto,sawenzel/root,abhinavmoudgil95/root,0x0all/ROOT,sbinet/cxx-root,gganis/root,BerserkerTroll/root,gganis/root,sbinet/cxx-root,simonpf/root,Y--/root,jrtomps/root,root-mirror/root,gbitzes/root,mattkretz/root,beniz/root,mattkretz/root,esakellari/root,gganis/root,omazapa/root,Duraznos/root,nilqed/root,davidlt/root,omazapa/root,CristinaCristescu/root,evgeny-boger/root,thomaskeck/root,jrtomps/root,BerserkerTroll/root,karies/root,satyarth934/root,omazapa/root,olifre/root,olifre/root,alexschlueter/cern-root,dfunke/root,simonpf/root,veprbl/root,davidlt/root,beniz/root,abhinavmoudgil95/root,davidlt/root,bbockelm/root,alexschlueter/cern-root,nilqed/root,lgiommi/root,esakellari/root,simonpf/root,beniz/root,omazapa/root-old,olifre/root,evgeny-boger/root,beniz/root,zzxuanyuan/root,arch1tect0r/root,olifre/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,veprbl/root,mkret2/root,nilqed/root,simonpf/root,karies/root,jrtomps/root,esakellari/root,karies/root,omazapa/root-old,smarinac/root,davidlt/root,CristinaCristescu/root,dfunke/root,lgiommi/root,evgeny-boger/root,sawenzel/root,sirinath/root,perovic/root,agarciamontoro/root,georgtroska/root,mkret2/root,Duraznos/root,veprbl/root,evgeny-boger/root,mattkretz/root,mhuwiler/rootauto,karies/root,georgtroska/root,krafczyk/root,perovic/root,Duraznos/root,davidlt/root,perovic/root,gbitzes/root,cxx-hep/root-cern,sirinath/root,gganis/root,BerserkerTroll/root,jrtomps/root,omazapa/root-old,0x0all/ROOT,abhinavmoudgil95/root,omazapa/root-old,mkret2/root,mattkretz/root,CristinaCristescu/root,evgeny-boger/root,dfunke/root,root-mirror/root,mattkretz/root,lgiommi/root,buuck/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,sirinath/root,alexschlueter/cern-root,CristinaCristescu/root,jrtomps/root,karies/root,mkret2/root,esakellari/my_root_for_test,sbinet/cxx-root,0x0all/ROOT,bbockelm/root,root-mirror/root,mattkretz/root,sawenzel/root,krafczyk/root,vukasinmilosevic/root,sirinath/root,buuck/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,lgiommi/root,vukasinmilosevic/root,BerserkerTroll/root,mattkretz/root,esakellari/my_root_for_test,evgeny-boger/root,dfunke/root,cxx-hep/root-cern,mhuwiler/rootauto,CristinaCristescu/root,beniz/root,karies/root,gganis/root,agarciamontoro/root,evgeny-boger/root,mhuwiler/rootauto,pspe/root,gbitzes/root,perovic/root,krafczyk/root,Y--/root,nilqed/root,CristinaCristescu/root,gganis/root,esakellari/root,veprbl/root,cxx-hep/root-cern,esakellari/my_root_for_test,satyarth934/root,0x0all/ROOT
|
222e2c0f1376cdb6af8494c9ea190fef441ea832
|
chrome/browser/ui/webui/options2/chromeos/stats_options_handler.cc
|
chrome/browser/ui/webui/options2/chromeos/stats_options_handler.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"
namespace chromeos {
StatsOptionsHandler::StatsOptionsHandler() {
}
// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
}
// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
base::Unretained(this)));
}
void StatsOptionsHandler::HandleMetricsReportingCheckbox(
const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
const bool enabled = (checked_str == "true");
UserMetrics::RecordAction(
enabled ?
UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}
} // namespace chromeos
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"
using content::UserMetricsAction;
namespace chromeos {
StatsOptionsHandler::StatsOptionsHandler() {
}
// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
}
// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
base::Unretained(this)));
}
void StatsOptionsHandler::HandleMetricsReportingCheckbox(
const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
const bool enabled = (checked_str == "true");
content::RecordAction(
enabled ?
UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}
} // namespace chromeos
|
Fix CrOS Official build from options2 copy.
|
Fix CrOS Official build from options2 copy.
BUG=none
TEST=none
TBR=csilv
Review URL: http://codereview.chromium.org/8907049
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@114493 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium
|
d5bb2b9d8b280d90c4fd86d919aa0e85fa6a0fdf
|
ui/gfx/compositor/compositor_cc.cc
|
ui/gfx/compositor/compositor_cc.cc
|
// 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 "ui/gfx/compositor/compositor_cc.h"
#include "base/command_line.h"
#include "third_party/skia/include/images/SkImageEncoder.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositor.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFloatPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h"
#include "ui/gfx/compositor/compositor_switches.h"
#include "ui/gfx/compositor/test_web_graphics_context_3d.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_surface.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/scoped_make_current.h"
#include "webkit/glue/webthread_impl.h"
#include "webkit/gpu/webgraphicscontext3d_in_process_impl.h"
namespace {
const double kDefaultRefreshRate = 60.0;
webkit_glue::WebThreadImpl* g_compositor_thread = NULL;
// If true a context is used that results in no rendering to the screen.
bool test_context_enabled = false;
} // anonymous namespace
namespace ui {
SharedResourcesCC::SharedResourcesCC() : initialized_(false) {
}
SharedResourcesCC::~SharedResourcesCC() {
}
// static
SharedResourcesCC* SharedResourcesCC::GetInstance() {
// We use LeakySingletonTraits so that we don't race with
// the tear down of the gl_bindings.
SharedResourcesCC* instance = Singleton<SharedResourcesCC,
LeakySingletonTraits<SharedResourcesCC> >::get();
if (instance->Initialize()) {
return instance;
} else {
instance->Destroy();
return NULL;
}
}
bool SharedResourcesCC::Initialize() {
if (initialized_)
return true;
{
// The following line of code exists soley to disable IO restrictions
// on this thread long enough to perform the GL bindings.
// TODO(wjmaclean) Remove this when GL initialisation cleaned up.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!gfx::GLSurface::InitializeOneOff() ||
gfx::GetGLImplementation() == gfx::kGLImplementationNone) {
LOG(ERROR) << "Could not load the GL bindings";
return false;
}
}
surface_ = gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1));
if (!surface_.get()) {
LOG(ERROR) << "Unable to create offscreen GL surface.";
return false;
}
context_ = gfx::GLContext::CreateGLContext(
NULL, surface_.get(), gfx::PreferIntegratedGpu);
if (!context_.get()) {
LOG(ERROR) << "Unable to create GL context.";
return false;
}
initialized_ = true;
return true;
}
void SharedResourcesCC::Destroy() {
context_ = NULL;
surface_ = NULL;
initialized_ = false;
}
gfx::ScopedMakeCurrent* SharedResourcesCC::GetScopedMakeCurrent() {
DCHECK(initialized_);
if (initialized_)
return new gfx::ScopedMakeCurrent(context_.get(), surface_.get());
else
return NULL;
}
void* SharedResourcesCC::GetDisplay() {
return surface_->GetDisplay();
}
gfx::GLShareGroup* SharedResourcesCC::GetShareGroup() {
DCHECK(initialized_);
return context_->share_group();
}
TextureCC::TextureCC()
: texture_id_(0),
flipped_(false) {
}
void TextureCC::SetCanvas(const SkCanvas& canvas,
const gfx::Point& origin,
const gfx::Size& overall_size) {
NOTREACHED();
}
void TextureCC::Draw(const ui::TextureDrawParams& params,
const gfx::Rect& clip_bounds_in_texture) {
NOTREACHED();
}
CompositorCC::CompositorCC(CompositorDelegate* delegate,
gfx::AcceleratedWidget widget,
const gfx::Size& size)
: Compositor(delegate, size),
widget_(widget),
root_web_layer_(WebKit::WebLayer::create(this)) {
WebKit::WebLayerTreeView::Settings settings;
CommandLine* command_line = CommandLine::ForCurrentProcess();
settings.showFPSCounter =
command_line->HasSwitch(switches::kUIShowFPSCounter);
settings.showPlatformLayerTree =
command_line->HasSwitch(switches::kUIShowLayerTree);
settings.refreshRate = kDefaultRefreshRate;
settings.partialSwapEnabled =
command_line->HasSwitch(switches::kUIEnablePartialSwap);
#ifndef WEBCOMPOSITOR_HAS_INITIALIZE
settings.enableCompositorThread = !!g_compositor_thread;
#endif
host_ = WebKit::WebLayerTreeView::create(this, root_web_layer_, settings);
root_web_layer_.setAnchorPoint(WebKit::WebFloatPoint(0.f, 0.f));
OnWidgetSizeChanged();
}
CompositorCC::~CompositorCC() {
// There's a cycle between |root_web_layer_| and |host_|, which results in
// leaking and/or crashing. Explicitly set the root layer to NULL so the cycle
// is broken.
host_.setRootLayer(NULL);
}
void CompositorCC::Initialize(bool use_thread) {
if (use_thread)
g_compositor_thread = new webkit_glue::WebThreadImpl("Browser Compositor");
#ifdef WEBCOMPOSITOR_HAS_INITIALIZE
WebKit::WebCompositor::initialize(g_compositor_thread);
#else
if (use_thread)
WebKit::WebCompositor::setThread(g_compositor_thread);
#endif
}
void CompositorCC::Terminate() {
#ifdef WEBCOMPOSITOR_HAS_INITIALIZE
WebKit::WebCompositor::shutdown();
#endif
if (g_compositor_thread) {
delete g_compositor_thread;
g_compositor_thread = NULL;
}
}
Texture* CompositorCC::CreateTexture() {
NOTREACHED();
return NULL;
}
void CompositorCC::Blur(const gfx::Rect& bounds) {
NOTIMPLEMENTED();
}
void CompositorCC::ScheduleDraw() {
if (g_compositor_thread)
host_.composite();
else
Compositor::ScheduleDraw();
}
void CompositorCC::OnNotifyStart(bool clear) {
}
void CompositorCC::OnNotifyEnd() {
}
void CompositorCC::OnWidgetSizeChanged() {
host_.setViewportSize(size());
root_web_layer_.setBounds(size());
}
void CompositorCC::OnRootLayerChanged() {
root_web_layer_.removeAllChildren();
if (root_layer())
root_web_layer_.addChild(root_layer()->web_layer());
}
void CompositorCC::DrawTree() {
host_.composite();
}
bool CompositorCC::ReadPixels(SkBitmap* bitmap, const gfx::Rect& bounds) {
if (bounds.right() > size().width() || bounds.bottom() > size().height())
return false;
// Convert to OpenGL coordinates.
gfx::Point new_origin(bounds.x(),
size().height() - bounds.height() - bounds.y());
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
bounds.width(), bounds.height());
bitmap->allocPixels();
SkAutoLockPixels lock_image(*bitmap);
unsigned char* pixels = static_cast<unsigned char*>(bitmap->getPixels());
if (host_.compositeAndReadback(pixels,
gfx::Rect(new_origin, bounds.size()))) {
SwizzleRGBAToBGRAAndFlip(pixels, bounds.size());
return true;
}
return false;
}
void CompositorCC::animateAndLayout(double frameBeginTime) {
}
void CompositorCC::applyScrollAndScale(const WebKit::WebSize& scrollDelta,
float scaleFactor) {
}
void CompositorCC::applyScrollDelta(const WebKit::WebSize&) {
}
WebKit::WebGraphicsContext3D* CompositorCC::createContext3D() {
WebKit::WebGraphicsContext3D* context;
if (test_context_enabled) {
context = new TestWebGraphicsContext3D();
} else {
gfx::GLShareGroup* share_group =
SharedResourcesCC::GetInstance()->GetShareGroup();
context = new webkit::gpu::WebGraphicsContext3DInProcessImpl(
widget_, share_group);
}
WebKit::WebGraphicsContext3D::Attributes attrs;
context->initialize(attrs, 0, true);
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kDisableUIVsync)) {
context->makeContextCurrent();
gfx::GLContext* gl_context = gfx::GLContext::GetCurrent();
gl_context->SetSwapInterval(1);
gl_context->ReleaseCurrent(NULL);
}
return context;
}
void CompositorCC::didRebindGraphicsContext(bool success) {
}
void CompositorCC::scheduleComposite() {
ScheduleDraw();
}
void CompositorCC::notifyNeedsComposite() {
ScheduleDraw();
}
Compositor* Compositor::Create(CompositorDelegate* owner,
gfx::AcceleratedWidget widget,
const gfx::Size& size) {
return new CompositorCC(owner, widget, size);
}
COMPOSITOR_EXPORT void SetupTestCompositor() {
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableTestCompositor)) {
test_context_enabled = true;
}
}
COMPOSITOR_EXPORT void DisableTestCompositor() {
test_context_enabled = false;
}
} // namespace ui
|
// 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 "ui/gfx/compositor/compositor_cc.h"
#include "base/command_line.h"
#include "third_party/skia/include/images/SkImageEncoder.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositor.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFloatPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h"
#include "ui/gfx/compositor/compositor_switches.h"
#include "ui/gfx/compositor/test_web_graphics_context_3d.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_surface.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/scoped_make_current.h"
#include "webkit/glue/webthread_impl.h"
#include "webkit/gpu/webgraphicscontext3d_in_process_impl.h"
namespace {
webkit_glue::WebThreadImpl* g_compositor_thread = NULL;
// If true a context is used that results in no rendering to the screen.
bool test_context_enabled = false;
} // anonymous namespace
namespace ui {
SharedResourcesCC::SharedResourcesCC() : initialized_(false) {
}
SharedResourcesCC::~SharedResourcesCC() {
}
// static
SharedResourcesCC* SharedResourcesCC::GetInstance() {
// We use LeakySingletonTraits so that we don't race with
// the tear down of the gl_bindings.
SharedResourcesCC* instance = Singleton<SharedResourcesCC,
LeakySingletonTraits<SharedResourcesCC> >::get();
if (instance->Initialize()) {
return instance;
} else {
instance->Destroy();
return NULL;
}
}
bool SharedResourcesCC::Initialize() {
if (initialized_)
return true;
{
// The following line of code exists soley to disable IO restrictions
// on this thread long enough to perform the GL bindings.
// TODO(wjmaclean) Remove this when GL initialisation cleaned up.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!gfx::GLSurface::InitializeOneOff() ||
gfx::GetGLImplementation() == gfx::kGLImplementationNone) {
LOG(ERROR) << "Could not load the GL bindings";
return false;
}
}
surface_ = gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1));
if (!surface_.get()) {
LOG(ERROR) << "Unable to create offscreen GL surface.";
return false;
}
context_ = gfx::GLContext::CreateGLContext(
NULL, surface_.get(), gfx::PreferIntegratedGpu);
if (!context_.get()) {
LOG(ERROR) << "Unable to create GL context.";
return false;
}
initialized_ = true;
return true;
}
void SharedResourcesCC::Destroy() {
context_ = NULL;
surface_ = NULL;
initialized_ = false;
}
gfx::ScopedMakeCurrent* SharedResourcesCC::GetScopedMakeCurrent() {
DCHECK(initialized_);
if (initialized_)
return new gfx::ScopedMakeCurrent(context_.get(), surface_.get());
else
return NULL;
}
void* SharedResourcesCC::GetDisplay() {
return surface_->GetDisplay();
}
gfx::GLShareGroup* SharedResourcesCC::GetShareGroup() {
DCHECK(initialized_);
return context_->share_group();
}
TextureCC::TextureCC()
: texture_id_(0),
flipped_(false) {
}
void TextureCC::SetCanvas(const SkCanvas& canvas,
const gfx::Point& origin,
const gfx::Size& overall_size) {
NOTREACHED();
}
void TextureCC::Draw(const ui::TextureDrawParams& params,
const gfx::Rect& clip_bounds_in_texture) {
NOTREACHED();
}
CompositorCC::CompositorCC(CompositorDelegate* delegate,
gfx::AcceleratedWidget widget,
const gfx::Size& size)
: Compositor(delegate, size),
widget_(widget),
root_web_layer_(WebKit::WebLayer::create(this)) {
WebKit::WebLayerTreeView::Settings settings;
CommandLine* command_line = CommandLine::ForCurrentProcess();
settings.showFPSCounter =
command_line->HasSwitch(switches::kUIShowFPSCounter);
settings.showPlatformLayerTree =
command_line->HasSwitch(switches::kUIShowLayerTree);
settings.partialSwapEnabled =
command_line->HasSwitch(switches::kUIEnablePartialSwap);
#ifndef WEBCOMPOSITOR_HAS_INITIALIZE
settings.enableCompositorThread = !!g_compositor_thread;
#endif
host_ = WebKit::WebLayerTreeView::create(this, root_web_layer_, settings);
root_web_layer_.setAnchorPoint(WebKit::WebFloatPoint(0.f, 0.f));
OnWidgetSizeChanged();
}
CompositorCC::~CompositorCC() {
// There's a cycle between |root_web_layer_| and |host_|, which results in
// leaking and/or crashing. Explicitly set the root layer to NULL so the cycle
// is broken.
host_.setRootLayer(NULL);
}
void CompositorCC::Initialize(bool use_thread) {
if (use_thread)
g_compositor_thread = new webkit_glue::WebThreadImpl("Browser Compositor");
#ifdef WEBCOMPOSITOR_HAS_INITIALIZE
WebKit::WebCompositor::initialize(g_compositor_thread);
#else
if (use_thread)
WebKit::WebCompositor::setThread(g_compositor_thread);
#endif
}
void CompositorCC::Terminate() {
#ifdef WEBCOMPOSITOR_HAS_INITIALIZE
WebKit::WebCompositor::shutdown();
#endif
if (g_compositor_thread) {
delete g_compositor_thread;
g_compositor_thread = NULL;
}
}
Texture* CompositorCC::CreateTexture() {
NOTREACHED();
return NULL;
}
void CompositorCC::Blur(const gfx::Rect& bounds) {
NOTIMPLEMENTED();
}
void CompositorCC::ScheduleDraw() {
if (g_compositor_thread)
host_.composite();
else
Compositor::ScheduleDraw();
}
void CompositorCC::OnNotifyStart(bool clear) {
}
void CompositorCC::OnNotifyEnd() {
}
void CompositorCC::OnWidgetSizeChanged() {
host_.setViewportSize(size());
root_web_layer_.setBounds(size());
}
void CompositorCC::OnRootLayerChanged() {
root_web_layer_.removeAllChildren();
if (root_layer())
root_web_layer_.addChild(root_layer()->web_layer());
}
void CompositorCC::DrawTree() {
host_.composite();
}
bool CompositorCC::ReadPixels(SkBitmap* bitmap, const gfx::Rect& bounds) {
if (bounds.right() > size().width() || bounds.bottom() > size().height())
return false;
// Convert to OpenGL coordinates.
gfx::Point new_origin(bounds.x(),
size().height() - bounds.height() - bounds.y());
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
bounds.width(), bounds.height());
bitmap->allocPixels();
SkAutoLockPixels lock_image(*bitmap);
unsigned char* pixels = static_cast<unsigned char*>(bitmap->getPixels());
if (host_.compositeAndReadback(pixels,
gfx::Rect(new_origin, bounds.size()))) {
SwizzleRGBAToBGRAAndFlip(pixels, bounds.size());
return true;
}
return false;
}
void CompositorCC::animateAndLayout(double frameBeginTime) {
}
void CompositorCC::applyScrollAndScale(const WebKit::WebSize& scrollDelta,
float scaleFactor) {
}
void CompositorCC::applyScrollDelta(const WebKit::WebSize&) {
}
WebKit::WebGraphicsContext3D* CompositorCC::createContext3D() {
WebKit::WebGraphicsContext3D* context;
if (test_context_enabled) {
context = new TestWebGraphicsContext3D();
} else {
gfx::GLShareGroup* share_group =
SharedResourcesCC::GetInstance()->GetShareGroup();
context = new webkit::gpu::WebGraphicsContext3DInProcessImpl(
widget_, share_group);
}
WebKit::WebGraphicsContext3D::Attributes attrs;
context->initialize(attrs, 0, true);
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kDisableUIVsync)) {
context->makeContextCurrent();
gfx::GLContext* gl_context = gfx::GLContext::GetCurrent();
gl_context->SetSwapInterval(1);
gl_context->ReleaseCurrent(NULL);
}
return context;
}
void CompositorCC::didRebindGraphicsContext(bool success) {
}
void CompositorCC::scheduleComposite() {
ScheduleDraw();
}
void CompositorCC::notifyNeedsComposite() {
ScheduleDraw();
}
Compositor* Compositor::Create(CompositorDelegate* owner,
gfx::AcceleratedWidget widget,
const gfx::Size& size) {
return new CompositorCC(owner, widget, size);
}
COMPOSITOR_EXPORT void SetupTestCompositor() {
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableTestCompositor)) {
test_context_enabled = true;
}
}
COMPOSITOR_EXPORT void DisableTestCompositor() {
test_context_enabled = false;
}
} // namespace ui
|
Revert 115887 - Fixes assertion failure in multithreaded compositor.
|
Revert 115887 - Fixes assertion failure in multithreaded compositor.
Right now, it seems as if we are always defaulting to 60fps for the frame rate in WebKit. This patch sets the frame rate for the browser compositor to the same default.
Review URL: http://codereview.chromium.org/8953039
[email protected]
Review URL: http://codereview.chromium.org/9049008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@115891 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Chilledheart/chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,robclark/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,anirudhSK/chromium,M4sse/chromium.src,Just-D/chromium-1,ltilve/chromium,robclark/chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,dednal/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,keishi/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,rogerwang/chromium,patrickm/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ltilve/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,keishi/chromium,anirudhSK/chromium,rogerwang/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,rogerwang/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,littlstar/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,robclark/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,patrickm/chromium.src,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,keishi/chromium,hujiajie/pa-chromium,robclark/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,M4sse/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,rogerwang/chromium,Fireblend/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,patrickm/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,patrickm/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,robclark/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,anirudhSK/chromium,timopulkkinen/BubbleFish,keishi/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,keishi/chromium,keishi/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,ltilve/chromium,ltilve/chromium,jaruba/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,littlstar/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,robclark/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,ltilve/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,dednal/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,robclark/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,anirudhSK/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium
|
5fc8999a5e1bd3674b57fe1e15d4e68f5081c4a4
|
tester/AssetTest.cpp
|
tester/AssetTest.cpp
|
/**
* @file AssetTest.cpp
* @brief Asset class tester.
* @author zer0
* @date 2016-04-03
*/
#include <gtest/gtest.h>
#include <libtbag/Asset.hpp>
using namespace libtbag;
TEST(AssetStaticTest, PathOperators)
{
# if defined(WIN32) || defined(_WIN32)
EXPECT_EQ(GetPathSeparator(), '\\');
EXPECT_EQ(GetPathSplitter(), ';');
EXPECT_STREQ(GetHomeEnvName(), "USERPROFILE");
# else
EXPECT_EQ(GetPathSeparator(), '/');
EXPECT_EQ(GetPathSplitter(), ':');
EXPECT_STREQ(GetHomeEnvName(), "HOME");
# endif
}
TEST(AssetStaticTest, CopyOperators)
{
Asset asset1 = Asset(Asset::default_setting());
Asset asset2 = asset1;
Asset asset3;
asset3 = asset1;
ASSERT_EQ(asset2.size(), asset1.size());
ASSERT_EQ(asset3.size(), asset1.size());
}
TEST(AssetStaticTest, insertDir_getDir)
{
std::string key = "key";
std::string value = "value";
Asset asset;
asset.insertDir(key, value);
ASSERT_EQ(asset.size(), 1U);
ASSERT_EQ(value, asset.getDir(key));
}
// Fixture.
class AssetTest : public ::testing::Test
{
public:
Asset _asset;
std::string _temp1;
std::string _temp2;
std::string _temp3;
public:
AssetTest() : _asset(Asset::default_setting()) {
}
public:
virtual void SetUp() {
_temp1 = std::string("1TEMP1");
_temp2 = std::string("2TEMP2");
_temp3 = std::string("3TEMP3");
}
virtual void TearDown() {
}
};
TEST_F(AssetTest, getHomeDir)
{
std::string dir = Asset::getHomeDir();
ASSERT_GT(dir.size(), 0U);
ASSERT_EQ(dir, _asset.getDir(Asset::getHomeDirKeyName()));
}
TEST_F(AssetTest, getExeDir)
{
std::string dir = Asset::getExeDir();
ASSERT_GT(dir.size(), 0U);
ASSERT_EQ(dir, _asset.getDir(Asset::getExeDirKeyName()));
}
|
/**
* @file AssetTest.cpp
* @brief Asset class tester.
* @author zer0
* @date 2016-04-03
*/
#include <gtest/gtest.h>
#include <libtbag/Asset.hpp>
using namespace libtbag;
TEST(AssetStaticTest, PathOperators)
{
# if defined(WIN32) || defined(_WIN32)
EXPECT_EQ(GetPathSeparator(), '\\');
EXPECT_EQ(GetPathSplitter(), ';');
EXPECT_STREQ(GetHomeEnvName(), "USERPROFILE");
# else
EXPECT_EQ(GetPathSeparator(), '/');
EXPECT_EQ(GetPathSplitter(), ':');
EXPECT_STREQ(GetHomeEnvName(), "HOME");
# endif
}
TEST(AssetStaticTest, CopyOperators)
{
Asset asset1 = Asset(Asset::default_setting());
Asset asset2 = asset1;
Asset asset3;
asset3 = asset1;
ASSERT_EQ(asset2.size(), asset1.size());
ASSERT_EQ(asset3.size(), asset1.size());
}
TEST(AssetStaticTest, MoveOperators)
{
auto rvalue_test = []() -> Asset {
return Asset();
};
#if defined(__COMP_LLVM__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wpessimizing-move"
#endif
Asset asset1 = std::move(rvalue_test());
Asset asset2;
#if defined(__COMP_LLVM__)
# pragma GCC diagnostic pop
#endif
asset2 = rvalue_test();
ASSERT_EQ(asset1.size(), asset2.size());
}
TEST(AssetStaticTest, insertDir_getDir)
{
std::string key = "key";
std::string value = "value";
Asset asset;
asset.insertDir(key, value);
ASSERT_EQ(asset.size(), 1U);
ASSERT_EQ(value, asset.getDir(key));
}
// Fixture.
class AssetTest : public ::testing::Test
{
public:
Asset _asset;
std::string _temp1;
std::string _temp2;
std::string _temp3;
public:
AssetTest() : _asset(Asset::default_setting()) {
}
public:
virtual void SetUp() {
_temp1 = std::string("1TEMP1");
_temp2 = std::string("2TEMP2");
_temp3 = std::string("3TEMP3");
}
virtual void TearDown() {
}
};
TEST_F(AssetTest, getHomeDir)
{
std::string dir = Asset::getHomeDir();
ASSERT_GT(dir.size(), 0U);
ASSERT_EQ(dir, _asset.getDir(Asset::getHomeDirKeyName()));
}
TEST_F(AssetTest, getExeDir)
{
std::string dir = Asset::getExeDir();
ASSERT_GT(dir.size(), 0U);
ASSERT_EQ(dir, _asset.getDir(Asset::getExeDirKeyName()));
}
|
Test the move operators of Asset class.
|
Test the move operators of Asset class.
|
C++
|
mit
|
osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag
|
ea9704225a1c7aab6682ed1aa09dc155b70de767
|
examples/aout.cpp
|
examples/aout.cpp
|
#include <random>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include "caf/all.hpp"
#include "caf/io/all.hpp"
using namespace caf;
using std::endl;
void caf_main(actor_system& system) {
for (int i = 1; i <= 50; ++i) {
system.spawn([i](blocking_actor* self) {
aout(self) << "Hi there! This is actor nr. "
<< i << "!" << endl;
std::random_device rd;
std::default_random_engine re(rd());
std::chrono::milliseconds tout{re() % 10};
self->delayed_send(self, tout, 42);
self->receive(
[i, self](int) {
aout(self) << "Actor nr. "
<< i << " says goodbye!" << endl;
}
);
});
}
}
CAF_MAIN()
|
#include <random>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include "caf/all.hpp"
using namespace caf;
using std::endl;
void caf_main(actor_system& system) {
for (int i = 1; i <= 50; ++i) {
system.spawn([i](blocking_actor* self) {
aout(self) << "Hi there! This is actor nr. "
<< i << "!" << endl;
std::random_device rd;
std::default_random_engine re(rd());
std::chrono::milliseconds tout{re() % 10};
self->delayed_send(self, tout, 42);
self->receive(
[i, self](int) {
aout(self) << "Actor nr. "
<< i << " says goodbye!" << endl;
}
);
});
}
}
CAF_MAIN()
|
Remove unnecessary include
|
Remove unnecessary include
|
C++
|
bsd-3-clause
|
DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework
|
52d7f7b9506714453789b7cd3ffaf58296af54a0
|
test/testzillians-compiler/ThorScriptTreeTest/StructureVerificationVisitorTest/StructureVerificationVisitorTest.cpp
|
test/testzillians-compiler/ThorScriptTreeTest/StructureVerificationVisitorTest/StructureVerificationVisitorTest.cpp
|
/**
* Zillians MMO
* Copyright (C) 2007-2010 Zillians.com, Inc.
* For more information see http://www.zillians.com
*
* Zillians MMO is the library and runtime for massive multiplayer online game
* development in utility computing model, which runs as a service for every
* developer to build their virtual world running on our GPU-assisted machines.
*
* This is a close source library intended to be used solely within Zillians.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
* COPYRIGHT HOLDER(S) 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 "core/Prerequisite.h"
#include "compiler/tree/ASTNode.h"
#include "compiler/tree/ASTNodeFactory.h"
#include "compiler/tree/visitor/stage1/StructureVerificationVisitor.h"
#include "compiler/tree/visitor/general/PrettyPrintVisitor.h"
#include "../ASTNodeSamples.h"
#include <iostream>
#include <string>
#include <limits>
#define BOOST_TEST_MODULE ThorScriptTreeTest_StructureVerificationVisitorTest
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
using namespace zillians;
using namespace zillians::compiler::tree;
using namespace zillians::compiler::tree::visitor;
BOOST_AUTO_TEST_SUITE( ThorScriptTreeTest_GenericVisitorTestSuite )
BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_GenericVisitorTestCase1 )
{
stage1::StructureVerificationVisitor<Composed::FALSE> v;
ASTNode* program = createSample3();
v.visit(*program);
BOOST_CHECK(v.passed == true);
}
BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_GenericVisitorTestCase2 )
{
stage1::StructureVerificationVisitor<Composed::FALSE> v;
ASTNode* program = createSample4();
v.visit(*program);
BOOST_CHECK(v.passed == false);
if(!v.passed)
{
PrettyPrintVisitor printer;
foreach(i, v.unspecified_nodes)
printer.visit(**i);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
/**
* Zillians MMO
* Copyright (C) 2007-2010 Zillians.com, Inc.
* For more information see http://www.zillians.com
*
* Zillians MMO is the library and runtime for massive multiplayer online game
* development in utility computing model, which runs as a service for every
* developer to build their virtual world running on our GPU-assisted machines.
*
* This is a close source library intended to be used solely within Zillians.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
* COPYRIGHT HOLDER(S) 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 "core/Prerequisite.h"
#include "compiler/tree/ASTNode.h"
#include "compiler/tree/ASTNodeFactory.h"
#include "compiler/tree/visitor/stage1/StructureVerificationVisitor.h"
#include "compiler/tree/visitor/general/PrettyPrintVisitor.h"
#include "../ASTNodeSamples.h"
#include <iostream>
#include <string>
#include <limits>
#define BOOST_TEST_MODULE ThorScriptTreeTest_StructureVerificationVisitorTest
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
using namespace zillians;
using namespace zillians::compiler::tree;
using namespace zillians::compiler::tree::visitor;
BOOST_AUTO_TEST_SUITE( ThorScriptTreeTest_GenericVisitorTestSuite )
BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_GenericVisitorTestCase1 )
{
stage1::StructureVerificationVisitor<Composed::FALSE> v;
ASTNode* program = createSample3();
v.visit(*program);
BOOST_CHECK(v.passed == true && "since there's no unspecified type specifier in sample3, structure verification should pass");
}
BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_GenericVisitorTestCase2 )
{
stage1::StructureVerificationVisitor<Composed::FALSE> v;
ASTNode* program = createSample4();
v.visit(*program);
BOOST_CHECK(v.passed == false && "since there's unspecified type specifier in sample3, structure verification should fail");
if(!v.passed)
{
BOOST_CHECK(v.unspecified_nodes.size() == 4 && "that's the total number of unspecified type specifier in sample4");
PrettyPrintVisitor printer;
foreach(i, v.unspecified_nodes)
printer.visit(**i);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
add terminate function in GenericDoubleVisitor
|
add terminate function in GenericDoubleVisitor
|
C++
|
agpl-3.0
|
zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language,zillians/supercell_language
|
755a6c0a46f07cdadb06821ced904af458fbf4e3
|
tools/replay/tests/test_replay.cc
|
tools/replay/tests/test_replay.cc
|
#include <chrono>
#include <thread>
#include <QDebug>
#include <QEventLoop>
#include "catch2/catch.hpp"
#include "common/util.h"
#include "tools/replay/replay.h"
#include "tools/replay/util.h"
const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2";
const std::string TEST_RLOG_CHECKSUM = "5b966d4bb21a100a8c4e59195faeb741b975ccbe268211765efd1763d892bfb3";
bool donload_to_file(const std::string &url, const std::string &local_file, int chunk_size = 5 * 1024 * 1024, int retries = 3) {
do {
if (httpDownload(url, local_file, chunk_size)) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
} while (--retries >= 0);
return false;
}
TEST_CASE("httpMultiPartDownload") {
char filename[] = "/tmp/XXXXXX";
close(mkstemp(filename));
const size_t chunk_size = 5 * 1024 * 1024;
std::string content;
SECTION("download to file") {
REQUIRE(donload_to_file(TEST_RLOG_URL, filename, chunk_size));
content = util::read_file(filename);
}
SECTION("download to buffer") {
for (int i = 0; i < 3 && content.empty(); ++i) {
content = httpGet(TEST_RLOG_URL, chunk_size);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
REQUIRE(!content.empty());
}
REQUIRE(content.size() == 9112651);
REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM);
}
int random_int(int min, int max) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return dist(rng);
}
TEST_CASE("FileReader") {
auto enable_local_cache = GENERATE(true, false);
std::string cache_file = cacheFilePath(TEST_RLOG_URL);
system(("rm " + cache_file + " -f").c_str());
FileReader reader(enable_local_cache);
std::string content = reader.read(TEST_RLOG_URL);
REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM);
if (enable_local_cache) {
REQUIRE(sha256(util::read_file(cache_file)) == TEST_RLOG_CHECKSUM);
} else {
REQUIRE(util::file_exists(cache_file) == false);
}
}
TEST_CASE("LogReader") {
SECTION("corrupt log") {
FileReader reader(true);
std::string corrupt_content = reader.read(TEST_RLOG_URL);
corrupt_content.resize(corrupt_content.length() / 2);
corrupt_content = decompressBZ2(corrupt_content);
LogReader log;
REQUIRE(log.load((std::byte *)corrupt_content.data(), corrupt_content.size()));
REQUIRE(log.events.size() > 0);
}
}
void read_segment(int n, const SegmentFile &segment_file, uint32_t flags) {
QEventLoop loop;
Segment segment(n, segment_file, flags);
QObject::connect(&segment, &Segment::loadFinished, [&]() {
REQUIRE(segment.isLoaded() == true);
REQUIRE(segment.log != nullptr);
REQUIRE(segment.frames[RoadCam] != nullptr);
if (flags & REPLAY_FLAG_DCAM) {
REQUIRE(segment.frames[DriverCam] != nullptr);
}
if (flags & REPLAY_FLAG_ECAM) {
REQUIRE(segment.frames[WideRoadCam] != nullptr);
}
// test LogReader & FrameReader
REQUIRE(segment.log->events.size() > 0);
REQUIRE(std::is_sorted(segment.log->events.begin(), segment.log->events.end(), Event::lessThan()));
for (auto cam : ALL_CAMERAS) {
auto &fr = segment.frames[cam];
if (!fr) continue;
if (cam == RoadCam || cam == WideRoadCam) {
REQUIRE(fr->getFrameCount() == 1200);
}
std::unique_ptr<uint8_t[]> yuv_buf = std::make_unique<uint8_t[]>(fr->getYUVSize());
// sequence get 100 frames
for (int i = 0; i < 100; ++i) {
REQUIRE(fr->get(i, yuv_buf.get()));
}
}
loop.quit();
});
loop.exec();
}
TEST_CASE("Route") {
// Create a local route from remote for testing
Route remote_route(DEMO_ROUTE);
REQUIRE(remote_route.load());
char tmp_path[] = "/tmp/root_XXXXXX";
const std::string data_dir = mkdtemp(tmp_path);
const std::string route_name = DEMO_ROUTE.mid(17).toStdString();
for (int i = 0; i < 2; ++i) {
std::string log_path = util::string_format("%s/%s--%d/", data_dir.c_str(), route_name.c_str(), i);
util::create_directories(log_path, 0755);
REQUIRE(donload_to_file(remote_route.at(i).rlog.toStdString(), log_path + "rlog.bz2"));
REQUIRE(donload_to_file(remote_route.at(i).road_cam.toStdString(), log_path + "fcamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).driver_cam.toStdString(), log_path + "dcamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).wide_road_cam.toStdString(), log_path + "ecamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).qcamera.toStdString(), log_path + "qcamera.ts"));
}
SECTION("Local route") {
auto flags = GENERATE(REPLAY_FLAG_DCAM | REPLAY_FLAG_ECAM, REPLAY_FLAG_QCAMERA);
Route route(DEMO_ROUTE, QString::fromStdString(data_dir));
REQUIRE(route.load());
REQUIRE(route.segments().size() == 2);
for (int i = 0; i < route.segments().size(); ++i) {
read_segment(i, route.at(i), flags);
}
};
SECTION("Remote route") {
auto flags = GENERATE(REPLAY_FLAG_DCAM | REPLAY_FLAG_ECAM, REPLAY_FLAG_QCAMERA);
Route route(DEMO_ROUTE);
REQUIRE(route.load());
REQUIRE(route.segments().size() == 11);
for (int i = 0; i < 2; ++i) {
read_segment(i, route.at(i), flags);
}
};
}
// helper class for unit tests
class TestReplay : public Replay {
public:
TestReplay(const QString &route, uint8_t flags = REPLAY_FLAG_NO_FILE_CACHE) : Replay(route, {}, {}, nullptr, flags) {}
void test_seek();
void testSeekTo(int seek_to);
};
void TestReplay::testSeekTo(int seek_to) {
seekTo(seek_to, false);
while (true) {
std::unique_lock lk(stream_lock_);
stream_cv_.wait(lk, [=]() { return events_updated_ == true; });
events_updated_ = false;
if (cur_mono_time_ != route_start_ts_ + seek_to * 1e9) {
// wake up by the previous merging, skip it.
continue;
}
Event cur_event(cereal::Event::Which::INIT_DATA, cur_mono_time_);
auto eit = std::upper_bound(events_->begin(), events_->end(), &cur_event, Event::lessThan());
if (eit == events_->end()) {
qDebug() << "waiting for events...";
continue;
}
REQUIRE(std::is_sorted(events_->begin(), events_->end(), Event::lessThan()));
const int seek_to_segment = seek_to / 60;
const int event_seconds = ((*eit)->mono_time - route_start_ts_) / 1e9;
current_segment_ = event_seconds / 60;
INFO("seek to [" << seek_to << "s segment " << seek_to_segment << "], events [" << event_seconds << "s segment" << current_segment_ << "]");
REQUIRE(event_seconds >= seek_to);
if (event_seconds > seek_to) {
auto it = segments_.lower_bound(seek_to_segment);
REQUIRE(it->first == current_segment_);
}
break;
}
}
void TestReplay::test_seek() {
// create a dummy stream thread
stream_thread_ = new QThread(this);
QEventLoop loop;
std::thread thread = std::thread([&]() {
for (int i = 0; i < 50; ++i) {
testSeekTo(random_int(0, 3 * 60));
}
loop.quit();
});
loop.exec();
thread.join();
}
TEST_CASE("Replay") {
TestReplay replay(DEMO_ROUTE, (uint8_t)REPLAY_FLAG_NO_VIPC);
REQUIRE(replay.load());
replay.test_seek();
}
|
#include <chrono>
#include <thread>
#include <QDebug>
#include <QEventLoop>
#include "catch2/catch.hpp"
#include "common/util.h"
#include "tools/replay/replay.h"
#include "tools/replay/util.h"
const std::string TEST_RLOG_URL = "https://commadataci.blob.core.windows.net/openpilotci/0c94aa1e1296d7c6/2021-05-05--19-48-37/0/rlog.bz2";
const std::string TEST_RLOG_CHECKSUM = "5b966d4bb21a100a8c4e59195faeb741b975ccbe268211765efd1763d892bfb3";
bool donload_to_file(const std::string &url, const std::string &local_file, int chunk_size = 5 * 1024 * 1024, int retries = 3) {
do {
if (httpDownload(url, local_file, chunk_size)) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
} while (--retries >= 0);
return false;
}
TEST_CASE("httpMultiPartDownload") {
char filename[] = "/tmp/XXXXXX";
close(mkstemp(filename));
const size_t chunk_size = 5 * 1024 * 1024;
std::string content;
SECTION("download to file") {
REQUIRE(donload_to_file(TEST_RLOG_URL, filename, chunk_size));
content = util::read_file(filename);
}
SECTION("download to buffer") {
for (int i = 0; i < 3 && content.empty(); ++i) {
content = httpGet(TEST_RLOG_URL, chunk_size);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
REQUIRE(!content.empty());
}
REQUIRE(content.size() == 9112651);
REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM);
}
int random_int(int min, int max) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return dist(rng);
}
TEST_CASE("FileReader") {
auto enable_local_cache = GENERATE(true, false);
std::string cache_file = cacheFilePath(TEST_RLOG_URL);
system(("rm " + cache_file + " -f").c_str());
FileReader reader(enable_local_cache);
std::string content = reader.read(TEST_RLOG_URL);
REQUIRE(sha256(content) == TEST_RLOG_CHECKSUM);
if (enable_local_cache) {
REQUIRE(sha256(util::read_file(cache_file)) == TEST_RLOG_CHECKSUM);
} else {
REQUIRE(util::file_exists(cache_file) == false);
}
}
TEST_CASE("LogReader") {
SECTION("corrupt log") {
FileReader reader(true);
std::string corrupt_content = reader.read(TEST_RLOG_URL);
corrupt_content.resize(corrupt_content.length() / 2);
corrupt_content = decompressBZ2(corrupt_content);
LogReader log;
REQUIRE(log.load((std::byte *)corrupt_content.data(), corrupt_content.size()));
REQUIRE(log.events.size() > 0);
}
}
void read_segment(int n, const SegmentFile &segment_file, uint32_t flags) {
QEventLoop loop;
Segment segment(n, segment_file, flags);
QObject::connect(&segment, &Segment::loadFinished, [&]() {
REQUIRE(segment.isLoaded() == true);
REQUIRE(segment.log != nullptr);
REQUIRE(segment.frames[RoadCam] != nullptr);
if (flags & REPLAY_FLAG_DCAM) {
REQUIRE(segment.frames[DriverCam] != nullptr);
}
if (flags & REPLAY_FLAG_ECAM) {
REQUIRE(segment.frames[WideRoadCam] != nullptr);
}
// test LogReader & FrameReader
REQUIRE(segment.log->events.size() > 0);
REQUIRE(std::is_sorted(segment.log->events.begin(), segment.log->events.end(), Event::lessThan()));
for (auto cam : ALL_CAMERAS) {
auto &fr = segment.frames[cam];
if (!fr) continue;
if (cam == RoadCam || cam == WideRoadCam) {
REQUIRE(fr->getFrameCount() == 1200);
}
std::unique_ptr<uint8_t[]> yuv_buf = std::make_unique<uint8_t[]>(fr->getYUVSize());
// sequence get 100 frames
for (int i = 0; i < 100; ++i) {
REQUIRE(fr->get(i, yuv_buf.get()));
}
}
loop.quit();
});
loop.exec();
}
TEST_CASE("Route") {
// Create a local route from remote for testing
Route remote_route(DEMO_ROUTE);
REQUIRE(remote_route.load());
char tmp_path[] = "/tmp/root_XXXXXX";
const std::string data_dir = mkdtemp(tmp_path);
const std::string route_name = DEMO_ROUTE.mid(17).toStdString();
for (int i = 0; i < 2; ++i) {
std::string log_path = util::string_format("%s/%s--%d/", data_dir.c_str(), route_name.c_str(), i);
util::create_directories(log_path, 0755);
REQUIRE(donload_to_file(remote_route.at(i).rlog.toStdString(), log_path + "rlog.bz2"));
REQUIRE(donload_to_file(remote_route.at(i).road_cam.toStdString(), log_path + "fcamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).driver_cam.toStdString(), log_path + "dcamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).wide_road_cam.toStdString(), log_path + "ecamera.hevc"));
REQUIRE(donload_to_file(remote_route.at(i).qcamera.toStdString(), log_path + "qcamera.ts"));
}
SECTION("Local route") {
auto flags = GENERATE(REPLAY_FLAG_DCAM | REPLAY_FLAG_ECAM, REPLAY_FLAG_QCAMERA);
Route route(DEMO_ROUTE, QString::fromStdString(data_dir));
REQUIRE(route.load());
REQUIRE(route.segments().size() == 2);
for (int i = 0; i < route.segments().size(); ++i) {
read_segment(i, route.at(i), flags);
}
};
SECTION("Remote route") {
auto flags = GENERATE(REPLAY_FLAG_DCAM | REPLAY_FLAG_ECAM, REPLAY_FLAG_QCAMERA);
Route route(DEMO_ROUTE);
REQUIRE(route.load());
REQUIRE(route.segments().size() == 11);
for (int i = 0; i < 2; ++i) {
read_segment(i, route.at(i), flags);
}
};
}
// helper class for unit tests
class TestReplay : public Replay {
public:
TestReplay(const QString &route, uint8_t flags = REPLAY_FLAG_NO_FILE_CACHE) : Replay(route, {}, {}, nullptr, flags) {}
void test_seek();
void testSeekTo(int seek_to);
};
void TestReplay::testSeekTo(int seek_to) {
seekTo(seek_to, false);
while (true) {
std::unique_lock lk(stream_lock_);
stream_cv_.wait(lk, [=]() { return events_updated_ == true; });
events_updated_ = false;
if (cur_mono_time_ != route_start_ts_ + seek_to * 1e9) {
// wake up by the previous merging, skip it.
continue;
}
Event cur_event(cereal::Event::Which::INIT_DATA, cur_mono_time_);
auto eit = std::upper_bound(events_->begin(), events_->end(), &cur_event, Event::lessThan());
if (eit == events_->end()) {
qDebug() << "waiting for events...";
continue;
}
REQUIRE(std::is_sorted(events_->begin(), events_->end(), Event::lessThan()));
const int seek_to_segment = seek_to / 60;
const int event_seconds = ((*eit)->mono_time - route_start_ts_) / 1e9;
current_segment_ = event_seconds / 60;
INFO("seek to [" << seek_to << "s segment " << seek_to_segment << "], events [" << event_seconds << "s segment" << current_segment_ << "]");
REQUIRE(event_seconds >= seek_to);
if (event_seconds > seek_to) {
auto it = segments_.lower_bound(seek_to_segment);
REQUIRE(it->first == current_segment_);
}
break;
}
}
void TestReplay::test_seek() {
// create a dummy stream thread
stream_thread_ = new QThread(this);
QEventLoop loop;
std::thread thread = std::thread([&]() {
for (int i = 0; i < 50; ++i) {
testSeekTo(random_int(0, 3 * 60));
}
loop.quit();
});
loop.exec();
thread.join();
}
TEST_CASE("Replay") {
auto flag = GENERATE(REPLAY_FLAG_NO_FILE_CACHE, REPLAY_FLAG_NONE);
TestReplay replay(DEMO_ROUTE, flag);
REQUIRE(replay.load());
replay.test_seek();
}
|
Revert "tools/replay: reduce test running time (#26110)"
|
Revert "tools/replay: reduce test running time (#26110)"
This reverts commit 6d07268ee5b385010961eab206b0b42a0ae6b5f8.
|
C++
|
mit
|
commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot
|
f5f978d53fe60a1a2937eeafb536ebe418c1cfd0
|
tests/basic_test.cpp
|
tests/basic_test.cpp
|
/*
* basic_test.cpp
*/
#include <chrono>
#include <mutex>
#include "gtest/gtest.h"
#include "naive_spin_mutex.hpp"
#include "ttas_spin_mutex.hpp"
#include "checked_mutex.hpp"
#include "fair_mutex.hpp"
#include "alternate_mutex.hpp"
#include "yamc_testutil.hpp"
#define TEST_THREADS 8
#define TEST_ITERATION 10000u
#define TEST_NOT_TIMEOUT std::chrono::minutes(3)
#define TEST_EXPECT_TIMEOUT std::chrono::milliseconds(500)
using NormalMutexTypes = ::testing::Types<
yamc::spin::mutex,
yamc::spin_weak::mutex,
yamc::spin_ttas::mutex,
yamc::checked::mutex,
yamc::fair::mutex
>;
template <typename Mutex>
struct NormalMutexTest : ::testing::Test {};
TYPED_TEST_CASE(NormalMutexTest, NormalMutexTypes);
// mutex::lock()
TYPED_TEST(NormalMutexTest, BasicLock)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
std::lock_guard<decltype(mtx)> lk(mtx);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// mutex::try_lock()
TYPED_TEST(NormalMutexTest, TryLock)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock()) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// mutex::try_lock() failure
TYPED_TEST(NormalMutexTest, TryLockFail)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
ASSERT_EQ(false, mtx.try_lock());
step.await(); // b2
}
}
using RecursiveMutexTypes = ::testing::Types<
yamc::checked::recursive_mutex,
yamc::fair::recursive_mutex,
yamc::alternate::recursive_mutex
>;
template <typename Mutex>
struct RecursiveMutexTest : ::testing::Test {};
TYPED_TEST_CASE(RecursiveMutexTest, RecursiveMutexTypes);
// recursive_mutex::lock()
TYPED_TEST(RecursiveMutexTest, BasicLock)
{
TypeParam mtx;
std::size_t c1 = 0, c2 = 0, c3 = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
std::lock_guard<decltype(mtx)> lk1(mtx);
auto before_cnt = ++c1;
{
std::lock_guard<decltype(mtx)> lk2(mtx);
++c2;
}
auto after_cnt = ++c3;
ASSERT_TRUE(before_cnt == after_cnt);
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c1);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c2);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c3);
}
// recursive_mutex::try_lock()
TYPED_TEST(RecursiveMutexTest, TryLock)
{
TypeParam mtx;
std::size_t c1 = 0, c2 = 0, c3 = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock()) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk1(mtx, std::adopt_lock);
++c1;
{
ASSERT_EQ(true, mtx.try_lock());
std::lock_guard<decltype(mtx)> lk2(mtx, std::adopt_lock);
++c2;
}
++c3;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c1);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c2);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c3);
}
// recursive_mutex::try_lock() failure
TYPED_TEST(RecursiveMutexTest, TryLockFail)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.lock());
step.await(); // b3
step.await(); // b4
ASSERT_NO_THROW(mtx.unlock());
step.await(); // b5
step.await(); // b6
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 1
step.await(); // b2
step.await(); // b3
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 2
step.await(); // b4
step.await(); // b5
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 3
step.await(); // b6
}
}
using TimedMutexTypes = ::testing::Types<
yamc::checked::timed_mutex,
yamc::checked::recursive_timed_mutex
>;
template <typename Mutex>
struct TimedMutexTest : ::testing::Test {};
TYPED_TEST_CASE(TimedMutexTest, TimedMutexTypes);
// (recursive_)timed_mutex::try_lock_for()
TYPED_TEST(TimedMutexTest, TryLockFor)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock_for(TEST_NOT_TIMEOUT)) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// (recursive_)timed_mutex::try_lock_until()
TYPED_TEST(TimedMutexTest, TryLockUntil)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
const auto tp = std::chrono::system_clock::now() + TEST_NOT_TIMEOUT;
while (!mtx.try_lock_until(tp)) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// (recursive_)timed_mutex::try_lock_for() timeout
TYPED_TEST(TimedMutexTest, TryLockForTimeout)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
yamc::test::stopwatch<> sw;
bool result = mtx.try_lock_for(TEST_EXPECT_TIMEOUT);
auto elapsed = sw.elapsed();
ASSERT_EQ(false, result);
EXPECT_LE(TEST_EXPECT_TIMEOUT, elapsed);
step.await(); // b2
}
}
// (recursive_)timed_mutex::try_lock_until() timeout
TYPED_TEST(TimedMutexTest, TryLockUntilTimeout)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
const auto tp = std::chrono::system_clock::now() + TEST_EXPECT_TIMEOUT;
yamc::test::stopwatch<> sw;
bool result = mtx.try_lock_until(tp);
auto elapsed = sw.elapsed();
ASSERT_EQ(false, result);
EXPECT_LE(TEST_EXPECT_TIMEOUT, elapsed);
step.await(); // b2
}
}
// backoff::exponential<>
TEST(BackoffTest, Exponential100)
{
using BackoffPolicy = yamc::backoff::exponential<100>;
BackoffPolicy::state state;
ASSERT_EQ(100u, state.initcount);
ASSERT_EQ(100u, state.counter);
for (int i = 0; i < 100; ++i) {
BackoffPolicy::wait(state); // wait 100
}
ASSERT_EQ(0u, state.counter);
for (int i = 0; i < 2000; ++i) {
BackoffPolicy::wait(state);
}
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
BackoffPolicy::wait(state);
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
}
TEST(BackoffTest, Exponential1)
{
using BackoffPolicy = yamc::backoff::exponential<1>;
BackoffPolicy::state state;
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(1u, state.counter);
BackoffPolicy::wait(state);
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
}
|
/*
* basic_test.cpp
*/
#include <atomic>
#include <chrono>
#include <mutex>
#include "gtest/gtest.h"
#include "naive_spin_mutex.hpp"
#include "ttas_spin_mutex.hpp"
#include "checked_mutex.hpp"
#include "fair_mutex.hpp"
#include "alternate_mutex.hpp"
#include "yamc_testutil.hpp"
#define TEST_THREADS 8
#define TEST_ITERATION 10000u
#define TEST_NOT_TIMEOUT std::chrono::minutes(3)
#define TEST_EXPECT_TIMEOUT std::chrono::milliseconds(500)
using NormalMutexTypes = ::testing::Types<
yamc::spin::mutex,
yamc::spin_weak::mutex,
yamc::spin_ttas::mutex,
yamc::checked::mutex,
yamc::fair::mutex
>;
template <typename Mutex>
struct NormalMutexTest : ::testing::Test {};
TYPED_TEST_CASE(NormalMutexTest, NormalMutexTypes);
// mutex::lock()
TYPED_TEST(NormalMutexTest, BasicLock)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
std::lock_guard<decltype(mtx)> lk(mtx);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// mutex::try_lock()
TYPED_TEST(NormalMutexTest, TryLock)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock()) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// mutex::try_lock() failure
TYPED_TEST(NormalMutexTest, TryLockFail)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
ASSERT_EQ(false, mtx.try_lock());
step.await(); // b2
}
}
using RecursiveMutexTypes = ::testing::Types<
yamc::checked::recursive_mutex,
yamc::fair::recursive_mutex,
yamc::alternate::recursive_mutex
>;
template <typename Mutex>
struct RecursiveMutexTest : ::testing::Test {};
TYPED_TEST_CASE(RecursiveMutexTest, RecursiveMutexTypes);
// recursive_mutex::lock()
TYPED_TEST(RecursiveMutexTest, BasicLock)
{
TypeParam mtx;
std::size_t c1 = 0, c2 = 0, c3 = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
std::lock_guard<decltype(mtx)> lk1(mtx);
auto before_cnt = ++c1;
{
std::lock_guard<decltype(mtx)> lk2(mtx);
++c2;
}
auto after_cnt = ++c3;
ASSERT_TRUE(before_cnt == after_cnt);
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c1);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c2);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c3);
}
// recursive_mutex::try_lock()
TYPED_TEST(RecursiveMutexTest, TryLock)
{
TypeParam mtx;
std::size_t c1 = 0, c2 = 0, c3 = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock()) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk1(mtx, std::adopt_lock);
++c1;
{
ASSERT_EQ(true, mtx.try_lock());
std::lock_guard<decltype(mtx)> lk2(mtx, std::adopt_lock);
++c2;
}
++c3;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c1);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c2);
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, c3);
}
// recursive_mutex::try_lock() failure
TYPED_TEST(RecursiveMutexTest, TryLockFail)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.lock());
step.await(); // b3
step.await(); // b4
ASSERT_NO_THROW(mtx.unlock());
step.await(); // b5
step.await(); // b6
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 1
step.await(); // b2
step.await(); // b3
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 2
step.await(); // b4
step.await(); // b5
ASSERT_EQ(false, mtx.try_lock()); // lockcnt = 3
step.await(); // b6
}
}
using TimedMutexTypes = ::testing::Types<
yamc::checked::timed_mutex,
yamc::checked::recursive_timed_mutex
>;
template <typename Mutex>
struct TimedMutexTest : ::testing::Test {};
TYPED_TEST_CASE(TimedMutexTest, TimedMutexTypes);
// (recursive_)timed_mutex::try_lock_for()
TYPED_TEST(TimedMutexTest, TryLockFor)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
while (!mtx.try_lock_for(TEST_NOT_TIMEOUT)) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// (recursive_)timed_mutex::try_lock_until()
TYPED_TEST(TimedMutexTest, TryLockUntil)
{
TypeParam mtx;
std::size_t counter = 0;
yamc::test::task_runner(
TEST_THREADS,
[&](std::size_t /*id*/) {
for (std::size_t n = 0; n < TEST_ITERATION; ++n) {
const auto tp = std::chrono::system_clock::now() + TEST_NOT_TIMEOUT;
while (!mtx.try_lock_until(tp)) {
std::this_thread::yield();
}
std::lock_guard<decltype(mtx)> lk(mtx, std::adopt_lock);
counter = counter + 1;
}
});
ASSERT_EQ(TEST_ITERATION * TEST_THREADS, counter);
}
// (recursive_)timed_mutex::try_lock_for() timeout
TYPED_TEST(TimedMutexTest, TryLockForTimeout)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
yamc::test::stopwatch<> sw;
bool result = mtx.try_lock_for(TEST_EXPECT_TIMEOUT);
auto elapsed = sw.elapsed();
ASSERT_EQ(false, result);
EXPECT_LE(TEST_EXPECT_TIMEOUT, elapsed);
step.await(); // b2
}
}
// (recursive_)timed_mutex::try_lock_until() timeout
TYPED_TEST(TimedMutexTest, TryLockUntilTimeout)
{
yamc::test::barrier step(2);
TypeParam mtx;
yamc::test::join_thread thd([&]{
ASSERT_NO_THROW(mtx.lock());
step.await(); // b1
step.await(); // b2
ASSERT_NO_THROW(mtx.unlock());
});
{
step.await(); // b1
const auto tp = std::chrono::system_clock::now() + TEST_EXPECT_TIMEOUT;
yamc::test::stopwatch<> sw;
bool result = mtx.try_lock_until(tp);
auto elapsed = sw.elapsed();
ASSERT_EQ(false, result);
EXPECT_LE(TEST_EXPECT_TIMEOUT, elapsed);
step.await(); // b2
}
}
// lockfree property of atomic<int>
TEST(AtomicTest, Lockfree)
{
// std::atomic<int> type is always lock-free
ASSERT_EQ(2, ATOMIC_INT_LOCK_FREE);
// std::atomic<int> is lock-free
std::atomic<int> i;
ASSERT_TRUE(i.is_lock_free());
}
// backoff::exponential<100>
TEST(BackoffTest, Exponential100)
{
using BackoffPolicy = yamc::backoff::exponential<100>;
BackoffPolicy::state state;
ASSERT_EQ(100u, state.initcount);
ASSERT_EQ(100u, state.counter);
for (int i = 0; i < 100; ++i) {
BackoffPolicy::wait(state); // wait 100
}
ASSERT_EQ(0u, state.counter);
for (int i = 0; i < 2000; ++i) {
BackoffPolicy::wait(state);
}
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
BackoffPolicy::wait(state);
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
}
// backoff::exponential<1>
TEST(BackoffTest, Exponential1)
{
using BackoffPolicy = yamc::backoff::exponential<1>;
BackoffPolicy::state state;
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(1u, state.counter);
BackoffPolicy::wait(state);
ASSERT_EQ(1u, state.initcount);
ASSERT_EQ(0u, state.counter);
}
|
add Lockfree test (basic_test.cpp)
|
add Lockfree test (basic_test.cpp)
|
C++
|
mit
|
yohhoy/yamc,yohhoy/yamc
|
202ceb4d3efd2294544583a7d4dc92899aa0181f
|
src/plugins/dummy/dummyplugin.cpp
|
src/plugins/dummy/dummyplugin.cpp
|
/************************************************************************************
* Copyright (C) 2014 Aleix Pol Gonzalez <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
************************************************************************************/
#include <purpose/job.h>
#include <purpose/pluginbase.h>
#include <QDebug>
#include <QTimer>
#include <QStandardPaths>
#include <QFile>
#include <QJsonDocument>
#include <KPluginFactory>
EXPORT_SHARE_VERSION
class DummyShareJob : public Purpose::Job
{
Q_OBJECT
public:
DummyShareJob(QObject* parent) : Purpose::Job(parent) {}
virtual void start() override
{
QFile f(data().value(QStringLiteral("destinationPath")).toString());
bool b = f.open(QIODevice::WriteOnly);
Q_ASSERT(b);
f.write(QJsonDocument(data()).toJson());
QTimer::singleShot(100, this, [this](){ setPercent(10); });
QTimer::singleShot(300, this, [this](){ setPercent(30); });
QTimer::singleShot(600, this, [this](){ setPercent(80); });
QTimer::singleShot(950, this, [this](){ Q_EMIT output( {{ QStringLiteral("url"), {} }} ); });
QTimer::singleShot(1000, this, [this](){ emitResult(); });
}
virtual QUrl configSourceCode() const override
{
QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("purpose/dummyplugin_config.qml"));
Q_ASSERT(!path.isEmpty());
return QUrl::fromLocalFile(path);
}
};
class Q_DECL_EXPORT DummyPlugin : public Purpose::PluginBase
{
Q_OBJECT
public:
DummyPlugin(QObject* p, const QVariantList& ) : Purpose::PluginBase(p) {}
virtual Purpose::Job* share() const override
{
return new DummyShareJob(nullptr);
}
};
K_PLUGIN_FACTORY_WITH_JSON(DummyShare, "dummyplugin.json", registerPlugin<DummyPlugin>();)
#include "dummyplugin.moc"
|
/************************************************************************************
* Copyright (C) 2014 Aleix Pol Gonzalez <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
************************************************************************************/
#include <purpose/job.h>
#include <purpose/pluginbase.h>
#include <QDebug>
#include <QTimer>
#include <QStandardPaths>
#include <QFile>
#include <QJsonDocument>
#include <KPluginFactory>
EXPORT_SHARE_VERSION
class DummyShareJob : public Purpose::Job
{
Q_OBJECT
public:
DummyShareJob(QObject* parent) : Purpose::Job(parent) {}
virtual void start() override
{
QFile f(data().value(QStringLiteral("destinationPath")).toString());
bool b = f.open(QIODevice::WriteOnly);
Q_ASSERT(b);
f.write(QJsonDocument(data()).toJson());
QTimer::singleShot(100, this, [this](){ setPercent(10); });
QTimer::singleShot(300, this, [this](){ setPercent(30); });
QTimer::singleShot(600, this, [this](){ setPercent(80); });
QTimer::singleShot(950, this, [this](){ Q_EMIT output( {{ QStringLiteral("url"), QStringLiteral("data:fuuuuu") }} ); });
QTimer::singleShot(1000, this, [this](){ emitResult(); });
}
virtual QUrl configSourceCode() const override
{
QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("purpose/dummyplugin_config.qml"));
Q_ASSERT(!path.isEmpty());
return QUrl::fromLocalFile(path);
}
};
class Q_DECL_EXPORT DummyPlugin : public Purpose::PluginBase
{
Q_OBJECT
public:
DummyPlugin(QObject* p, const QVariantList& ) : Purpose::PluginBase(p) {}
virtual Purpose::Job* share() const override
{
return new DummyShareJob(nullptr);
}
};
K_PLUGIN_FACTORY_WITH_JSON(DummyShare, "dummyplugin.json", registerPlugin<DummyPlugin>();)
#include "dummyplugin.moc"
|
Make the Dummy plugin actually output something
|
Make the Dummy plugin actually output something
|
C++
|
lgpl-2.1
|
RJVB/kde-purpose,RJVB/kde-purpose,RJVB/kde-purpose
|
eecede18a0add6e04d5d6c0c1f3ad332d5377909
|
shared_from_this/main.cpp
|
shared_from_this/main.cpp
|
#include <memory>
#include <iostream>
struct Good: std::enable_shared_from_this<Good>
{
std::shared_ptr<Good> getptr() {
return shared_from_this();
}
~Good() { std::cout << "Good::~Good() called\n"; }
};
struct Bad
{
std::shared_ptr<Bad> getptr() {
return std::shared_ptr<Bad>(this);
}
~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
int main()
{
{ // Good: the two shared_ptr's share the same object
std::shared_ptr<Good> gp1(new Good);
std::shared_ptr<Good> gp2 = gp1->getptr();
std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
}
{ // Bad, each shared_ptr thinks it's the only owner of the object
std::shared_ptr<Bad> bp1(new Bad);
std::shared_ptr<Bad> bp2 = bp1->getptr();
std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
}
} // UB: double-delete of Bad
|
#include <memory>
#include <iostream>
struct Good : std::enable_shared_from_this<Good> {
std::shared_ptr<Good> getptr() { return shared_from_this(); }
~Good() { std::cout << "Good::~Good() called\n"; }
};
struct Bad {
std::shared_ptr<Bad> getptr() { return std::shared_ptr<Bad>(this); }
~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
struct Foo : std::enable_shared_from_this<Foo> {
virtual ~Foo() { std::cout << "Foo::~Foo() called\n"; }
virtual std::shared_ptr<Foo> getPtr() {
std::cout << "Foo::getPtr() called\n";
return shared_from_this();
}
};
struct Bar : public Foo {
virtual ~Bar() { std::cout << "Bar::~Bar() called\n"; }
virtual std::shared_ptr<Foo> getPtr() {
std::cout << "Bar::getPtr() called\n";
return shared_from_this();
}
};
int main() {
{ // Good: the two shared_ptr's share the same object
std::shared_ptr<Good> gp1(new Good);
std::shared_ptr<Good> gp2 = gp1->getptr();
std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
}
{ // Bad, each shared_ptr thinks it's the only owner of the object
std::shared_ptr<Bad> bp1(new Bad);
std::shared_ptr<Bad> bp2 = bp1->getptr();
std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
}
{
std::shared_ptr<Foo> fooPtr = std::make_shared<Bar>();
std::shared_ptr<Foo> foo2Ptr = fooPtr->getPtr();
std::cout << "foo2Ptr.use_count() = " << foo2Ptr.use_count() << '\n';
}
} // UB: double-delete of Bad
|
update shared_from_this
|
update shared_from_this
|
C++
|
apache-2.0
|
Mizux/snippets,Mizux/snippets
|
c73c8525c862fe186274028776c6b152d4f2be1c
|
soccer/Logger.hpp
|
soccer/Logger.hpp
|
/**
* @brief The Logger stores and saves the state of the game at each point in
* time.
*
* @details
* The log stores things such as robot and ball position and velocity as well as
* debug information about the current play. See the LogFrame.proto file for a
* full list of what is stored in the log.
*
* This logger implements a circular buffer for recent history and writes all
* frames to disk.
*
* _history is a circular buffer.
*
* Consider a sequence number for each frame, where the first frame passed
* to addFrame() has a sequence number of zero and the sequence number is one
* greater for each subsequent frame.
*
* _nextFrameNumber is the sequence number of the next frame to be stored by
* addFrame().
*
* lastFrame() returns the sequence number of the latest available frame.
* It returns -1 if no frames have been stored.
*
* You can get a copy of a frame by passing its sequence number to getFrame().
* If the frame is too old to be in the circular buffer (or the sequence number
* is beyond the most recent available) then getFrame() will return false.
*
* Frames are allocated as they are first needed. The size of the circular
* buffer limits total memory usage.
*/
#pragma once
#include <protobuf/LogFrame.pb.h>
#include <QString>
#include <QReadLocker>
#include <QWriteLocker>
#include <QReadWriteLock>
#include <vector>
#include <algorithm>
#include <memory>
#include "time.hpp"
#include <boost/circular_buffer.hpp>
class Logger {
public:
Logger(size_t logSize = 10000);
~Logger();
bool open(QString filename);
void close();
// Returns the size of the circular buffer
size_t capacity() const { return _history.capacity(); }
// Returns the sequence number of the most recently added frame.
// Returns -1 if no frames have been added.
size_t size() const { return _history.size(); }
std::shared_ptr<Packet::LogFrame> lastFrame() const;
void addFrame(std::shared_ptr<Packet::LogFrame> frame);
// Gets frames.size() frames starting at start and working backwards.
// Clears any frames that couldn't be populated.
// Returns the number of frames copied.
int getFrames(int start,
std::vector<std::shared_ptr<Packet::LogFrame>>& frames) const;
// Returns the amount of memory used by all LogFrames in the history.
int spaceUsed() const { return _spaceUsed; }
bool recording() const { return _fd >= 0; }
QString filename() const { return _filename; }
int firstFrameNumber() const {
return currentFrameNumber() - _history.size() + 1;
}
int currentFrameNumber() const { return _nextFrameNumber - 1; }
template<typename OutputIterator>
int getFrames(int endIndex, int num,
OutputIterator result) const {
QReadLocker locker(&_lock);
auto end = _history.rbegin();
endIndex = std::min(_nextFrameNumber, endIndex);
int numFromBack = _nextFrameNumber - endIndex;
if (numFromBack >= _history.size()) {
return 0;
} else {
advance(end, numFromBack);
int startFrame = _nextFrameNumber - _history.size();
int numToCopy = std::min(endIndex - 1 - startFrame, num);
copy_n(end, numToCopy, result);
return std::max(numToCopy, 0);
}
}
RJ::Time startTime() const { return _startTime; }
private:
RJ::Time _startTime;
mutable QReadWriteLock _lock;
QString _filename;
/**
* Frame history.
* Increasing indices correspond to earlier times.
* This must only be accessed while _mutex is locked.
*
* It is not safe to modify a single std::shared_ptr from multiple threads,
* but after it is copied the copies can be used and destroyed freely in
* different threads.
*/
boost::circular_buffer<std::shared_ptr<Packet::LogFrame>> _history;
int _spaceUsed;
// File descriptor for log file
int _fd;
// Sequence number of the next frame to be written
int _nextFrameNumber;
};
|
/**
* @brief The Logger stores and saves the state of the game at each point in
* time.
*
* @details
* The log stores things such as robot and ball position and velocity as well as
* debug information about the current play. See the LogFrame.proto file for a
* full list of what is stored in the log.
*
* This logger implements a circular buffer for recent history and writes all
* frames to disk.
*
* _history is a circular buffer.
*
* Consider a sequence number for each frame, where the first frame passed
* to addFrame() has a sequence number of zero and the sequence number is one
* greater for each subsequent frame.
*
* _nextFrameNumber is the sequence number of the next frame to be stored by
* addFrame().
*
* lastFrame() returns the sequence number of the latest available frame.
* It returns -1 if no frames have been stored.
*
* You can get a copy of a frame by passing its sequence number to getFrame().
* If the frame is too old to be in the circular buffer (or the sequence number
* is beyond the most recent available) then getFrame() will return false.
*
* Frames are allocated as they are first needed. The size of the circular
* buffer limits total memory usage.
*/
#pragma once
#include <protobuf/LogFrame.pb.h>
#include <QString>
#include <QReadLocker>
#include <QWriteLocker>
#include <QReadWriteLock>
#include <vector>
#include <algorithm>
#include <memory>
#include "time.hpp"
#include <boost/circular_buffer.hpp>
class Logger {
public:
Logger(size_t logSize = 10000);
~Logger();
bool open(QString filename);
void close();
// Returns the size of the circular buffer
size_t capacity() const { return _history.capacity(); }
// Returns the sequence number of the most recently added frame.
// Returns -1 if no frames have been added.
size_t size() const { return _history.size(); }
std::shared_ptr<Packet::LogFrame> lastFrame() const;
void addFrame(std::shared_ptr<Packet::LogFrame> frame);
// Gets frames.size() frames starting at start and working backwards.
// Clears any frames that couldn't be populated.
// Returns the number of frames copied.
int getFrames(int start,
std::vector<std::shared_ptr<Packet::LogFrame>>& frames) const;
// Returns the amount of memory used by all LogFrames in the history.
int spaceUsed() const { return _spaceUsed; }
bool recording() const { return _fd >= 0; }
QString filename() const { return _filename; }
int firstFrameNumber() const {
return currentFrameNumber() - _history.size() + 1;
}
int currentFrameNumber() const { return _nextFrameNumber - 1; }
template <typename OutputIterator>
int getFrames(int endIndex, int num, OutputIterator result) const {
QReadLocker locker(&_lock);
auto end = _history.rbegin();
endIndex = std::min(_nextFrameNumber, endIndex);
int numFromBack = _nextFrameNumber - endIndex;
if (numFromBack >= _history.size()) {
return 0;
} else {
advance(end, numFromBack);
int startFrame = _nextFrameNumber - _history.size();
int numToCopy = std::min(endIndex - 1 - startFrame, num);
copy_n(end, numToCopy, result);
return std::max(numToCopy, 0);
}
}
RJ::Time startTime() const { return _startTime; }
private:
RJ::Time _startTime;
mutable QReadWriteLock _lock;
QString _filename;
/**
* Frame history.
* Increasing indices correspond to earlier times.
* This must only be accessed while _mutex is locked.
*
* It is not safe to modify a single std::shared_ptr from multiple threads,
* but after it is copied the copies can be used and destroyed freely in
* different threads.
*/
boost::circular_buffer<std::shared_ptr<Packet::LogFrame>> _history;
int _spaceUsed;
// File descriptor for log file
int _fd;
// Sequence number of the next frame to be written
int _nextFrameNumber;
};
|
Make Pretty
|
Make Pretty
|
C++
|
apache-2.0
|
RoboJackets/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,RoboJackets/robocup-software
|
23ec3937eca97e7310841b27709e2cc677806406
|
JPetHLDReader/JPetHLDReader.cpp
|
JPetHLDReader/JPetHLDReader.cpp
|
/**
* @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 JPetHLDReader.cpp
* @brief The interface only mimics the JPetReader class
*/
#include "JPetHLDReader.h"
#include <iostream>
#include <cassert>
JPetHLDReader::JPetHLDReader():
fBranch(0),
fTree(0),
fEvent(0),
fFile(NULL),
fCurrentEventNumber(-1)
{
/* */
}
JPetHLDReader::JPetHLDReader (const char* filename):
fBranch(0),
fTree(0),
fEvent(0),
fFile(NULL),
fCurrentEventNumber(-1)
{
if (!openFileAndLoadData(filename, "T")) {
ERROR("error in opening file");
}
}
JPetHLDReader::~JPetHLDReader ()
{
closeFile();
}
EventIII& JPetHLDReader::getCurrentEvent()
{
if (loadCurrentEvent()) {
fEventW = new WrappedEvent(*fEvent);
return *fEventW;
//return *fEvent;
} else {
ERROR("Could not read the current event");
if (fEvent) {
delete fEvent;
}
fEvent = new EventIII();
}
fEventW = new WrappedEvent(*fEvent);
return *fEventW;
}
bool JPetHLDReader::nextEvent()
{
fCurrentEventNumber++;
return loadCurrentEvent();
}
bool JPetHLDReader::firstEvent()
{
fCurrentEventNumber = 0;
return loadCurrentEvent();
}
bool JPetHLDReader::lastEvent()
{
fCurrentEventNumber = getNbOfAllEvents() - 1;
return loadCurrentEvent();
}
bool JPetHLDReader::nthEvent(int n)
{
fCurrentEventNumber = n;
return loadCurrentEvent();
}
void JPetHLDReader::closeFile ()
{
if (fFile != NULL) {
if (fFile->IsOpen()) fFile->Close();
delete fFile;
fFile = NULL;
}
fBranch = 0;
fEvent = 0;
fTree = 0;
}
bool JPetHLDReader::loadData(const char* treename)
{
if (!isOpen() ) {
ERROR("File not open");
return false;
}
if (!treename) {
ERROR("empty tree name");
return false;
}
fTree = static_cast<TTree*>(fFile->Get(treename));
if (!fTree) {
ERROR("in reading tree");
return false;
}
fBranch = fTree->GetBranch("eventIII");
if (!fBranch) {
ERROR("in reading branch from tree");
return false;
}
fBranch->SetAddress(&fEvent);
firstEvent();
return true;
}
bool JPetHLDReader::openFile (const char* filename)
{
closeFile();
fFile = new TFile(filename);
if ((!fFile->IsOpen()) || fFile->IsZombie()) {
ERROR("Cannot open file.");
closeFile();
return false;
}
return true;
}
|
/**
* @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 JPetHLDReader.cpp
* @brief The interface only mimics the JPetReader class
*/
#include "JPetHLDReader.h"
#include <iostream>
#include <cassert>
JPetHLDReader::JPetHLDReader():
fBranch(0),
fTree(0),
fEvent(0),
fEventW(0),
fFile(NULL),
fCurrentEventNumber(-1)
{
/* */
}
JPetHLDReader::JPetHLDReader (const char* filename):
fBranch(0),
fTree(0),
fEvent(0),
fEventW(0),
fFile(NULL),
fCurrentEventNumber(-1)
{
if (!openFileAndLoadData(filename, "T")) {
ERROR("error in opening file");
}
}
JPetHLDReader::~JPetHLDReader ()
{
closeFile();
}
EventIII& JPetHLDReader::getCurrentEvent()
{
if (loadCurrentEvent()) {
fEventW = new WrappedEvent(*fEvent);
return *fEventW;
//return *fEvent;
} else {
ERROR("Could not read the current event");
if (fEvent) {
delete fEvent;
}
fEvent = new EventIII();
}
fEventW = new WrappedEvent(*fEvent);
return *fEventW;
}
bool JPetHLDReader::nextEvent()
{
fCurrentEventNumber++;
return loadCurrentEvent();
}
bool JPetHLDReader::firstEvent()
{
fCurrentEventNumber = 0;
return loadCurrentEvent();
}
bool JPetHLDReader::lastEvent()
{
fCurrentEventNumber = getNbOfAllEvents() - 1;
return loadCurrentEvent();
}
bool JPetHLDReader::nthEvent(int n)
{
fCurrentEventNumber = n;
return loadCurrentEvent();
}
void JPetHLDReader::closeFile ()
{
if (fFile != NULL) {
if (fFile->IsOpen()) fFile->Close();
delete fFile;
fFile = NULL;
}
fBranch = 0;
fEvent = 0;
fTree = 0;
}
bool JPetHLDReader::loadData(const char* treename)
{
if (!isOpen() ) {
ERROR("File not open");
return false;
}
if (!treename) {
ERROR("empty tree name");
return false;
}
fTree = static_cast<TTree*>(fFile->Get(treename));
if (!fTree) {
ERROR("in reading tree");
return false;
}
fBranch = fTree->GetBranch("eventIII");
if (!fBranch) {
ERROR("in reading branch from tree");
return false;
}
fBranch->SetAddress(&fEvent);
firstEvent();
return true;
}
bool JPetHLDReader::openFile (const char* filename)
{
closeFile();
fFile = new TFile(filename);
if ((!fFile->IsOpen()) || fFile->IsZombie()) {
ERROR("Cannot open file.");
closeFile();
return false;
}
return true;
}
|
Add some missing constructor initialization in JPetHLDReader
|
Add some missing constructor initialization in JPetHLDReader
|
C++
|
apache-2.0
|
alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework
|
0f2827703942c2fc588288d5c9c85a1d167865c7
|
tests/mock_memio.cpp
|
tests/mock_memio.cpp
|
#include "mock_memio.hpp"
namespace mock {
namespace {
mock::Memory g_memory;
extern "C" void raw_write32(uint32_t addr, uint32_t value) {
g_memory.write32(addr, value);
}
extern "C" uint32_t raw_read32(uint32_t addr) {
return g_memory.read32(addr);
}
} // namespace
void Memory::priv_write32(uint32_t addr, uint32_t value) {
const auto& it = addr_handler_map_.find(addr);
if (it != addr_handler_map_.end()) {
uint32_t old_value = get_value_at(addr, 0);
mem_map_[addr] = it->second->write32(addr, old_value, value);
} else {
mem_map_[addr] = value;
}
}
uint32_t Memory::priv_read32(uint32_t addr) const {
uint32_t ret = 0;
const auto it = mem_map_.find(addr);
if (it != mem_map_.end()) {
ret = it->second;
}
return ret;
}
void Memory::write32(uint32_t addr, uint32_t value) {
journal_.push_back(std::make_tuple(Memory::Op::WRITE32, addr, value));
priv_write32(addr, value);
}
void Memory::write16(uint32_t addr, uint16_t value) {
journal_.push_back(std::make_tuple(Memory::Op::WRITE16, addr, value));
const auto write_addr = addr & (~3);
uint32_t old_value = priv_read32(write_addr);
auto new_value = (old_value & (~(0xffff << (8 * (addr & 2)))))
| (value << (8 * (addr & 2)));
priv_write32(write_addr, new_value);
}
uint32_t Memory::read32(uint32_t addr) const {
uint32_t res = priv_read32(addr);
journal_.push_back(std::make_tuple(Memory::Op::READ32, addr, res));
return res;
}
// NOTE: This does not allow unaligned reads
uint16_t Memory::read16(uint32_t addr) const {
const auto lookup_addr = addr & (~3);
uint32_t res = priv_read32(lookup_addr);
res >>= ((addr & 2) ? 16 : 0);
journal_.push_back(std::make_tuple(Memory::Op::READ16, addr, res));
return res;
}
uint8_t Memory::read8(uint32_t addr) const {
const auto lookup_addr = addr & (~3);
uint32_t res = priv_read32(lookup_addr);
res >>= (8 * (addr & 3));
journal_.push_back(std::make_tuple(Memory::Op::READ8, addr, res));
return res;
}
void Memory::set_value_at(uint32_t addr, uint32_t value) {
mem_map_[addr] = value;
}
uint32_t Memory::get_value_at(uint32_t addr) {
return mem_map_[addr];
}
uint32_t Memory::get_value_at(uint32_t addr, uint32_t default_value) {
auto result = default_value;
const auto& it = mem_map_.find(addr);
if (it != mem_map_.end()) {
result = it->second;
}
return result;
}
const Memory::JournalT& Memory::get_journal() const {
return journal_;
}
void Memory::reset() {
mem_map_.clear();
journal_.clear();
}
void Memory::set_addr_io_handler(uint32_t addr, IOHandlerStub* io_handler) {
addr_handler_map_.insert(std::make_pair(addr, io_handler));
io_handler->set_memory(this);
}
void Memory::set_addr_io_handler(uint32_t range_start, uint32_t range_end, IOHandlerStub* io_handler) {
for (auto addr = range_start; addr < range_end; addr += sizeof(addr)) {
addr_handler_map_.insert(std::make_pair(addr, io_handler));
}
io_handler->set_memory(this);
}
Memory& get_global_memory() {
return g_memory;
}
void IOHandlerStub::set_mem_value(uint32_t addr, uint32_t value) {
mem_->set_value_at(addr, value);
}
uint32_t IOHandlerStub::get_mem_value(uint32_t addr) const {
return mem_->get_value_at(addr, 0);
}
} // namespace mock
|
#include "mock_memio.hpp"
namespace mock {
namespace {
mock::Memory g_memory;
extern "C" void raw_write32(uint32_t addr, uint32_t value) {
g_memory.write32(addr, value);
}
extern "C" uint32_t raw_read32(uint32_t addr) {
return g_memory.read32(addr);
}
} // namespace
void Memory::priv_write32(uint32_t addr, uint32_t value) {
const auto& it = addr_handler_map_.find(addr);
if (it != addr_handler_map_.end()) {
uint32_t old_value = get_value_at(addr, 0);
mem_map_[addr] = it->second->write32(addr, old_value, value);
} else {
mem_map_[addr] = value;
}
}
uint32_t Memory::priv_read32(uint32_t addr) const {
uint32_t ret = 0;
const auto it = mem_map_.find(addr);
if (it != mem_map_.end()) {
ret = it->second;
}
return ret;
}
void Memory::write32(uint32_t addr, uint32_t value) {
journal_.push_back(std::make_tuple(Memory::Op::WRITE32, addr, value));
priv_write32(addr, value);
}
void Memory::write16(uint32_t addr, uint16_t value) {
journal_.push_back(std::make_tuple(Memory::Op::WRITE16, addr, value));
const auto write_addr = addr & (~3);
uint32_t old_value = priv_read32(write_addr);
auto new_value = (old_value & (~(0xffff << (8 * (addr & 2)))))
| (value << (8 * (addr & 2)));
priv_write32(write_addr, new_value);
}
uint32_t Memory::read32(uint32_t addr) const {
uint32_t res = priv_read32(addr);
journal_.push_back(std::make_tuple(Memory::Op::READ32, addr, res));
return res;
}
// NOTE: This does not allow unaligned reads
uint16_t Memory::read16(uint32_t addr) const {
const auto lookup_addr = addr & (~3);
uint32_t res = priv_read32(lookup_addr);
res >>= ((addr & 2) ? 16 : 0);
journal_.push_back(std::make_tuple(Memory::Op::READ16, addr, res));
return res;
}
uint8_t Memory::read8(uint32_t addr) const {
const auto lookup_addr = addr & (~3);
uint32_t res = priv_read32(lookup_addr);
res >>= (8 * (addr & 3));
journal_.push_back(std::make_tuple(Memory::Op::READ8, addr, res));
return res;
}
void Memory::set_value_at(uint32_t addr, uint32_t value) {
mem_map_[addr] = value;
}
uint32_t Memory::get_value_at(uint32_t addr) {
return mem_map_[addr];
}
uint32_t Memory::get_value_at(uint32_t addr, uint32_t default_value) {
auto result = default_value;
const auto& it = mem_map_.find(addr);
if (it != mem_map_.end()) {
result = it->second;
}
return result;
}
const Memory::JournalT& Memory::get_journal() const {
return journal_;
}
void Memory::reset() {
mem_map_.clear();
journal_.clear();
addr_handler_map_.clear();
}
void Memory::set_addr_io_handler(uint32_t addr, IOHandlerStub* io_handler) {
addr_handler_map_.insert(std::make_pair(addr, io_handler));
io_handler->set_memory(this);
}
void Memory::set_addr_io_handler(uint32_t range_start, uint32_t range_end, IOHandlerStub* io_handler) {
for (auto addr = range_start; addr < range_end; addr += sizeof(addr)) {
addr_handler_map_.insert(std::make_pair(addr, io_handler));
}
io_handler->set_memory(this);
}
Memory& get_global_memory() {
return g_memory;
}
void IOHandlerStub::set_mem_value(uint32_t addr, uint32_t value) {
mem_->set_value_at(addr, value);
}
uint32_t IOHandlerStub::get_mem_value(uint32_t addr) const {
return mem_->get_value_at(addr, 0);
}
} // namespace mock
|
Fix bug in fake_memio, that was not clearing the address handlers properly
|
Fix bug in fake_memio, that was not clearing the address handlers properly
|
C++
|
apache-2.0
|
google/cortex-demos,google/cortex-demos,google/cortex-demos,google/cortex-demos
|
8512c22ba47d4ad9a7f0056fcfbd0c7688ef0ac7
|
soccer/planning/TargetVelPathPlannerTest.cpp
|
soccer/planning/TargetVelPathPlannerTest.cpp
|
#include <gtest/gtest.h>
#include "TargetVelPathPlanner.hpp"
#include "planning/MotionCommand.hpp"
#include <Geometry2d/Point.hpp>
using namespace Geometry2d;
namespace Planning {
TEST(TargetVelPathPlannerTest, run) {
MotionInstant startInstant({0, 0}, {0, 0});
WorldVelTargetCommand command(Point(0, 1));
MotionConstraints motionConstraints;
ShapeSet obstacles;
obstacles.add(std::make_shared<Rect>(Point(-1, 5), Point(1, 4)));
TargetVelPathPlanner planner;
auto path = planner.run(startInstant, cmd, motionConstraints, &obstacles);
ASSERT_NE(nullptr, path) << "Planner returned null path";
// Ensure that the path is obstacle-free
float hitTime;
EXPECT_FALSE(path->hit(obstacles, hitTime, 0))
<< "Returned path hits obstacles";
// Ensure that the path moves in the direction of the target world velocity
// (positive y-axis)
boost::optional<MotionInstant> instant = path->evaluate(0.1);
ASSERT_NE(boost::none, instant);
EXPECT_FLOAT_EQ(0, instant->pos.x);
EXPECT_GT(instant->pos.y, 0);
}
} // namespace Planning
|
#include <gtest/gtest.h>
#include "TargetVelPathPlanner.hpp"
#include "planning/MotionCommand.hpp"
#include <Geometry2d/Point.hpp>
using namespace Geometry2d;
namespace Planning {
TEST(TargetVelPathPlannerTest, run) {
MotionInstant startInstant({0, 0}, {0, 0});
WorldVelTargetCommand cmd(Point(0, 1));
MotionConstraints motionConstraints;
ShapeSet obstacles;
obstacles.add(std::make_shared<Rect>(Point(-1, 5), Point(1, 4)));
TargetVelPathPlanner planner;
auto path = planner.run(startInstant, &cmd, motionConstraints, &obstacles);
ASSERT_NE(nullptr, path) << "Planner returned null path";
// Ensure that the path is obstacle-free
float hitTime;
EXPECT_FALSE(path->hit(obstacles, hitTime, 0))
<< "Returned path hits obstacles";
// Ensure that the path moves in the direction of the target world velocity
// (positive y-axis)
boost::optional<MotionInstant> instant = path->evaluate(0.1);
ASSERT_NE(boost::none, instant);
EXPECT_FLOAT_EQ(0, instant->pos.x);
EXPECT_GT(instant->pos.y, 0);
}
} // namespace Planning
|
Fix TargetVelPathPlannerTest
|
Fix TargetVelPathPlannerTest
|
C++
|
apache-2.0
|
RoboJackets/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software,RoboJackets/robocup-software
|
946d6377d3dc54cd27058d352d15314f3b1ed167
|
examples/priv.cpp
|
examples/priv.cpp
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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/>.
*/
/*
Demonstration of private keys.
*/
#include <iostream>
#include <sstream>
#include <bitcoin/bitcoin.hpp>
using namespace bc;
void display_help()
{
puts("Usage: priv [COMMAND] [ARGS]...");
puts("");
puts("The priv commands are:");
puts(" new\t\tGenerate a new private key and output to STDOUT");
puts(" sign\t\tSign the next argument using the private key in STDIN");
puts(" verify\tVerify the next argument using the private key in STDIN");
puts(" address\tshow the associated bitcoin address");
}
void error_exit(const char* message, int status=1)
{
std::cerr << "priv: " << message << std::endl;
exit(status);
}
int new_keypair()
{
elliptic_curve_key ec;
ec.new_key_pair();
private_data raw_private_key = ec.private_key();
std::cout << std::string(raw_private_key.begin(), raw_private_key.end());
return 0;
}
int sign(const std::string input_data, const std::string raw_private_key)
{
hash_digest digest = decode_hex_digest<hash_digest>(input_data);
elliptic_curve_key ec;
if (!ec.set_private_key(
private_data(raw_private_key.begin(), raw_private_key.end())))
error_exit("bad private key");
log_info() << encode_hex(ec.sign(digest));
return 0;
}
int verify(const std::string input_data, const std::string& signature_data,
const std::string raw_private_key)
{
hash_digest digest = decode_hex_digest<hash_digest>(input_data);
data_chunk signature = decode_hex(signature_data);
elliptic_curve_key ec;
if (!ec.set_private_key(
private_data(raw_private_key.begin(), raw_private_key.end())))
error_exit("bad private key");
log_info() << (ec.verify(digest, signature) ? '1' : '0');
return 0;
}
int address(const std::string raw_private_key)
{
elliptic_curve_key ec;
if (!ec.set_private_key(
private_data(raw_private_key.begin(), raw_private_key.end())))
error_exit("bad private key");
payment_address address;
set_public_key(address, ec.public_key());
log_info() << address.encoded();
return 0;
}
std::string read_private_key()
{
std::istreambuf_iterator<char> it(std::cin);
std::istreambuf_iterator<char> end;
return std::string(it, end);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
display_help();
return 0;
}
std::string command = argv[1];
size_t number_args = argc - 2, arg_index = 2;
if (command == "new")
return new_keypair();
else if (command == "sign")
{
if (number_args != 1)
error_exit("sign requires argument data");
std::string input_data = argv[arg_index];
return sign(input_data, read_private_key());
}
else if (command == "verify")
{
if (number_args != 2)
error_exit("verify requires argument data and signature");
std::string input_data = argv[arg_index],
signature = argv[arg_index + 1];
return verify(input_data, signature, read_private_key());
}
else if (command == "address")
return address(read_private_key());
else
error_exit("not a valid command. See priv help text.");
// Should never happen!
return 1;
}
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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/>.
*/
/*
Demonstration of private keys.
*/
#include <iostream>
#include <sstream>
#include <bitcoin/bitcoin.hpp>
using namespace bc;
void display_help()
{
puts("Usage: priv [COMMAND] [ARGS]...");
puts("");
puts("The priv commands are:");
puts(" new\t\tGenerate a new private key and output to STDOUT");
puts(" sign\t\tSign the next argument using the private key in STDIN");
puts(" verify\tVerify the next argument using the private key in STDIN");
puts(" address\tshow the associated bitcoin address");
}
void error_exit(const char* message, int status=1)
{
std::cerr << "priv: " << message << std::endl;
exit(status);
}
int new_keypair()
{
elliptic_curve_key ec;
if (!ec.new_keypair())
error_exit("could not create new key pair");
secret_parameter raw_private_key = ec.secret();
std::cout << std::string(raw_private_key.begin(), raw_private_key.end());
return 0;
}
int sign(const std::string input_data, const std::string raw_private_key)
{
hash_digest digest = decode_hex_digest<hash_digest>(input_data);
hash_digest privkey = decode_hex_digest<hash_digest>(raw_private_key);
elliptic_curve_key ec;
if (!ec.set_secret(privkey))
error_exit("bad private key");
log_info() << encode_hex(ec.sign(digest));
return 0;
}
int verify(const std::string input_data, const std::string& signature_data,
const std::string raw_private_key)
{
hash_digest digest = decode_hex_digest<hash_digest>(input_data);
data_chunk signature = decode_hex(signature_data);
hash_digest privkey = decode_hex_digest<hash_digest>(raw_private_key);
elliptic_curve_key ec;
if (!ec.set_secret(privkey))
error_exit("bad private key");
log_info() << (ec.verify(digest, signature) ? '1' : '0');
return 0;
}
int address(const std::string raw_private_key)
{
hash_digest privkey = decode_hex_digest<hash_digest>(raw_private_key);
elliptic_curve_key ec;
if (!ec.set_secret(privkey))
error_exit("bad private key");
payment_address address;
set_public_key(address, ec.public_key());
log_info() << address.encoded();
return 0;
}
std::string read_private_key()
{
std::istreambuf_iterator<char> it(std::cin);
std::istreambuf_iterator<char> end;
return std::string(it, end);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
display_help();
return 0;
}
std::string command = argv[1];
size_t number_args = argc - 2, arg_index = 2;
if (command == "new")
return new_keypair();
else if (command == "sign")
{
if (number_args != 1)
error_exit("sign requires argument data");
std::string input_data = argv[arg_index];
return sign(input_data, read_private_key());
}
else if (command == "verify")
{
if (number_args != 2)
error_exit("verify requires argument data and signature");
std::string input_data = argv[arg_index],
signature = argv[arg_index + 1];
return verify(input_data, signature, read_private_key());
}
else if (command == "address")
return address(read_private_key());
else
error_exit("not a valid command. See priv help text.");
// Should never happen!
return 1;
}
|
Use new elliptic_curve_key.
|
examples/priv: Use new elliptic_curve_key.
The way ECK is used has changed a bit, so accomodate the example.
Announcement: http://lists.dyne.org/lurker/message/20140116.144459.92a367f2.en.html
Issue: https://github.com/spesmilo/libbitcoin/issues/33
|
C++
|
agpl-3.0
|
libtetcoin/libtetcoin-consensus,kaostao/libbitcoin,libtetcoin/libtetcoin-consensus,kaostao/libbitcoin,swansontec/libbitcoin,BWallet/libbitcoin,GroestlCoin/libgroestlcoin,swansontec/libbitcoin,libmetrocoin/libmetrocoin-consensus,Airbitz/libbitcoin,BWallet/libbitcoin,BWallet/libbitcoin,GroestlCoin/libgroestlcoin,libtetcoin/libtetcoin-consensus,Airbitz/libbitcoin,libtetcoin/libtetcoin-consensus,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,libtetcoin/libtetcoin-consensus,kaostao/libbitcoin,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,libmetrocoin/libmetrocoin-consensus,Airbitz/libbitcoin,libmetrocoin/libmetrocoin-consensus,kaostao/libbitcoin,Airbitz/libbitcoin,BWallet/libbitcoin,libmetrocoin/libmetrocoin-consensus,libmetrocoin/libmetrocoin-consensus
|
43d60d7b360a1e164772acb29988f433105d28db
|
vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp
|
vespalib/src/tests/net/tls/policy_checking_certificate_verifier/policy_checking_certificate_verifier_test.cpp
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <vespa/vespalib/net/tls/transport_security_options_reading.h>
#include <vespa/vespalib/net/tls/policy_checking_certificate_verifier.h>
#include <vespa/vespalib/test/peer_policy_utils.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/exceptions.h>
using namespace vespalib;
using namespace vespalib::net::tls;
bool glob_matches(vespalib::stringref pattern, vespalib::stringref string_to_check) {
auto glob = HostGlobPattern::create_from_glob(pattern);
return glob->matches(string_to_check);
}
TEST("glob without wildcards matches entire string") {
EXPECT_TRUE(glob_matches("foo", "foo"));
EXPECT_FALSE(glob_matches("foo", "fooo"));
EXPECT_FALSE(glob_matches("foo", "ffoo"));
}
TEST("wildcard glob can match prefix") {
EXPECT_TRUE(glob_matches("foo*", "foo"));
EXPECT_TRUE(glob_matches("foo*", "foobar"));
EXPECT_FALSE(glob_matches("foo*", "ffoo"));
}
TEST("wildcard glob can match suffix") {
EXPECT_TRUE(glob_matches("*foo", "foo"));
EXPECT_TRUE(glob_matches("*foo", "ffoo"));
EXPECT_FALSE(glob_matches("*foo", "fooo"));
}
TEST("wildcard glob can match substring") {
EXPECT_TRUE(glob_matches("f*o", "fo"));
EXPECT_TRUE(glob_matches("f*o", "foo"));
EXPECT_TRUE(glob_matches("f*o", "ffoo"));
EXPECT_FALSE(glob_matches("f*o", "boo"));
}
TEST("wildcard glob does not cross multiple dot delimiter boundaries") {
EXPECT_TRUE(glob_matches("*.bar.baz", "foo.bar.baz"));
EXPECT_TRUE(glob_matches("*.bar.baz", ".bar.baz"));
EXPECT_FALSE(glob_matches("*.bar.baz", "zoid.foo.bar.baz"));
EXPECT_TRUE(glob_matches("foo.*.baz", "foo.bar.baz"));
EXPECT_FALSE(glob_matches("foo.*.baz", "foo.bar.zoid.baz"));
}
TEST("single char glob matches non dot characters") {
EXPECT_TRUE(glob_matches("f?o", "foo"));
EXPECT_FALSE(glob_matches("f?o", "fooo"));
EXPECT_FALSE(glob_matches("f?o", "ffoo"));
EXPECT_FALSE(glob_matches("f?o", "f.o"));
}
TEST("special basic regex characters are escaped") {
EXPECT_TRUE(glob_matches("$[.\\^", "$[.\\^"));
}
TEST("special extended regex characters are ignored") {
EXPECT_TRUE(glob_matches("{)(+|]}", "{)(+|]}"));
}
// TODO CN + SANs
PeerCredentials creds_with_dns_sans(std::vector<vespalib::string> dns_sans) {
PeerCredentials creds;
creds.dns_sans = std::move(dns_sans);
return creds;
}
PeerCredentials creds_with_cn(vespalib::stringref cn) {
PeerCredentials creds;
creds.common_name = cn;
return creds;
}
bool verify(AllowedPeers allowed_peers, const PeerCredentials& peer_creds) {
auto verifier = create_verify_callback_from(std::move(allowed_peers));
return verifier->verify(peer_creds);
}
TEST("Default-constructed AllowedPeers does not allow all authenticated peers") {
EXPECT_FALSE(AllowedPeers().allows_all_authenticated());
}
TEST("Specially constructed set of policies allows all authenticated peers") {
auto allow_all = AllowedPeers::allow_all_authenticated();
EXPECT_TRUE(allow_all.allows_all_authenticated());
EXPECT_TRUE(verify(allow_all, creds_with_dns_sans({{"anything.goes"}})));
}
TEST("Non-empty policies do not allow all unauthenticated peers") {
auto allow_not_all = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_FALSE(allow_not_all.allows_all_authenticated());
}
TEST("SAN requirement without glob pattern is matched as exact string") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.bar"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.worlds"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hhello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.world.bar"}})));
}
TEST("SAN requirement can include glob wildcards") {
auto allowed = allowed_peers({policy_with({required_san_dns("*.w?rld")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"greetings.w0rld"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.wrld"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"world"}})));
}
TEST("multi-SAN policy requires all SANs to be present in certificate") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world"),
required_san_dns("foo.bar")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}})));
// Need both
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.bar"}})));
// OK with more SANs that strictly required
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"baz.blorg"}})));
}
TEST("wildcard SAN in certificate is not treated as a wildcard match by policy") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"*.world"}})));
}
TEST("wildcard SAN in certificate is still matched by wildcard policy SAN") {
auto allowed = allowed_peers({policy_with({required_san_dns("*.world")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"*.world"}})));
}
struct MultiPolicyMatchFixture {
AllowedPeers allowed;
MultiPolicyMatchFixture();
~MultiPolicyMatchFixture();
};
MultiPolicyMatchFixture::MultiPolicyMatchFixture()
: allowed(allowed_peers({policy_with({required_san_dns("hello.world")}),
policy_with({required_san_dns("foo.bar")}),
policy_with({required_san_dns("zoid.berg")})}))
{}
MultiPolicyMatchFixture::~MultiPolicyMatchFixture() = default;
TEST_F("peer verifies if it matches at least 1 policy of multiple", MultiPolicyMatchFixture) {
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"foo.bar"}})));
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"zoid.berg"}})));
}
TEST_F("peer verifies if it matches multiple policies", MultiPolicyMatchFixture) {
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"hello.world"}, {"zoid.berg"}})));
}
TEST_F("peer must match at least 1 of multiple policies", MultiPolicyMatchFixture) {
EXPECT_FALSE(verify(f.allowed, creds_with_dns_sans({{"does.not.exist"}})));
}
TEST("CN requirement without glob pattern is matched as exact string") {
auto allowed = allowed_peers({policy_with({required_cn("hello.world")})});
EXPECT_TRUE(verify(allowed, creds_with_cn("hello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("foo.bar")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.worlds")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hhello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("foo.hello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.world.bar")));
}
TEST("CN requirement can include glob wildcards") {
auto allowed = allowed_peers({policy_with({required_cn("*.w?rld")})});
EXPECT_TRUE(verify(allowed, creds_with_cn("hello.world")));
EXPECT_TRUE(verify(allowed, creds_with_cn("greetings.w0rld")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.wrld")));
EXPECT_FALSE(verify(allowed, creds_with_cn("world")));
}
// TODO test CN _and_ SAN
TEST_MAIN() { TEST_RUN_ALL(); }
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <vespa/vespalib/net/tls/transport_security_options_reading.h>
#include <vespa/vespalib/net/tls/policy_checking_certificate_verifier.h>
#include <vespa/vespalib/test/peer_policy_utils.h>
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/exceptions.h>
using namespace vespalib;
using namespace vespalib::net::tls;
bool glob_matches(vespalib::stringref pattern, vespalib::stringref string_to_check) {
auto glob = HostGlobPattern::create_from_glob(pattern);
return glob->matches(string_to_check);
}
TEST("glob without wildcards matches entire string") {
EXPECT_TRUE(glob_matches("foo", "foo"));
EXPECT_FALSE(glob_matches("foo", "fooo"));
EXPECT_FALSE(glob_matches("foo", "ffoo"));
}
TEST("wildcard glob can match prefix") {
EXPECT_TRUE(glob_matches("foo*", "foo"));
EXPECT_TRUE(glob_matches("foo*", "foobar"));
EXPECT_FALSE(glob_matches("foo*", "ffoo"));
}
TEST("wildcard glob can match suffix") {
EXPECT_TRUE(glob_matches("*foo", "foo"));
EXPECT_TRUE(glob_matches("*foo", "ffoo"));
EXPECT_FALSE(glob_matches("*foo", "fooo"));
}
TEST("wildcard glob can match substring") {
EXPECT_TRUE(glob_matches("f*o", "fo"));
EXPECT_TRUE(glob_matches("f*o", "foo"));
EXPECT_TRUE(glob_matches("f*o", "ffoo"));
EXPECT_FALSE(glob_matches("f*o", "boo"));
}
TEST("wildcard glob does not cross multiple dot delimiter boundaries") {
EXPECT_TRUE(glob_matches("*.bar.baz", "foo.bar.baz"));
EXPECT_TRUE(glob_matches("*.bar.baz", ".bar.baz"));
EXPECT_FALSE(glob_matches("*.bar.baz", "zoid.foo.bar.baz"));
EXPECT_TRUE(glob_matches("foo.*.baz", "foo.bar.baz"));
EXPECT_FALSE(glob_matches("foo.*.baz", "foo.bar.zoid.baz"));
}
TEST("single char glob matches non dot characters") {
EXPECT_TRUE(glob_matches("f?o", "foo"));
EXPECT_FALSE(glob_matches("f?o", "fooo"));
EXPECT_FALSE(glob_matches("f?o", "ffoo"));
EXPECT_FALSE(glob_matches("f?o", "f.o"));
}
TEST("special basic regex characters are escaped") {
EXPECT_TRUE(glob_matches("$[.\\^", "$[.\\^"));
}
TEST("special extended regex characters are ignored") {
EXPECT_TRUE(glob_matches("{)(+|]}", "{)(+|]}"));
}
// TODO CN + SANs
PeerCredentials creds_with_dns_sans(std::vector<vespalib::string> dns_sans) {
PeerCredentials creds;
creds.dns_sans = std::move(dns_sans);
return creds;
}
PeerCredentials creds_with_cn(vespalib::stringref cn) {
PeerCredentials creds;
creds.common_name = cn;
return creds;
}
bool verify(AllowedPeers allowed_peers, const PeerCredentials& peer_creds) {
auto verifier = create_verify_callback_from(std::move(allowed_peers));
return verifier->verify(peer_creds);
}
TEST("Default-constructed AllowedPeers does not allow all authenticated peers") {
EXPECT_FALSE(AllowedPeers().allows_all_authenticated());
}
TEST("Specially constructed set of policies allows all authenticated peers") {
auto allow_all = AllowedPeers::allow_all_authenticated();
EXPECT_TRUE(allow_all.allows_all_authenticated());
EXPECT_TRUE(verify(allow_all, creds_with_dns_sans({{"anything.goes"}})));
}
TEST("Non-empty policies do not allow all authenticated peers") {
auto allow_not_all = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_FALSE(allow_not_all.allows_all_authenticated());
}
TEST("SAN requirement without glob pattern is matched as exact string") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.bar"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.worlds"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hhello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.world.bar"}})));
}
TEST("SAN requirement can include glob wildcards") {
auto allowed = allowed_peers({policy_with({required_san_dns("*.w?rld")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"greetings.w0rld"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.wrld"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"world"}})));
}
TEST("multi-SAN policy requires all SANs to be present in certificate") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world"),
required_san_dns("foo.bar")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}})));
// Need both
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"foo.bar"}})));
// OK with more SANs that strictly required
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"hello.world"}, {"foo.bar"}, {"baz.blorg"}})));
}
TEST("wildcard SAN in certificate is not treated as a wildcard match by policy") {
auto allowed = allowed_peers({policy_with({required_san_dns("hello.world")})});
EXPECT_FALSE(verify(allowed, creds_with_dns_sans({{"*.world"}})));
}
TEST("wildcard SAN in certificate is still matched by wildcard policy SAN") {
auto allowed = allowed_peers({policy_with({required_san_dns("*.world")})});
EXPECT_TRUE(verify(allowed, creds_with_dns_sans({{"*.world"}})));
}
struct MultiPolicyMatchFixture {
AllowedPeers allowed;
MultiPolicyMatchFixture();
~MultiPolicyMatchFixture();
};
MultiPolicyMatchFixture::MultiPolicyMatchFixture()
: allowed(allowed_peers({policy_with({required_san_dns("hello.world")}),
policy_with({required_san_dns("foo.bar")}),
policy_with({required_san_dns("zoid.berg")})}))
{}
MultiPolicyMatchFixture::~MultiPolicyMatchFixture() = default;
TEST_F("peer verifies if it matches at least 1 policy of multiple", MultiPolicyMatchFixture) {
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"hello.world"}})));
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"foo.bar"}})));
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"zoid.berg"}})));
}
TEST_F("peer verifies if it matches multiple policies", MultiPolicyMatchFixture) {
EXPECT_TRUE(verify(f.allowed, creds_with_dns_sans({{"hello.world"}, {"zoid.berg"}})));
}
TEST_F("peer must match at least 1 of multiple policies", MultiPolicyMatchFixture) {
EXPECT_FALSE(verify(f.allowed, creds_with_dns_sans({{"does.not.exist"}})));
}
TEST("CN requirement without glob pattern is matched as exact string") {
auto allowed = allowed_peers({policy_with({required_cn("hello.world")})});
EXPECT_TRUE(verify(allowed, creds_with_cn("hello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("foo.bar")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.worlds")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hhello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("foo.hello.world")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.world.bar")));
}
TEST("CN requirement can include glob wildcards") {
auto allowed = allowed_peers({policy_with({required_cn("*.w?rld")})});
EXPECT_TRUE(verify(allowed, creds_with_cn("hello.world")));
EXPECT_TRUE(verify(allowed, creds_with_cn("greetings.w0rld")));
EXPECT_FALSE(verify(allowed, creds_with_cn("hello.wrld")));
EXPECT_FALSE(verify(allowed, creds_with_cn("world")));
}
// TODO test CN _and_ SAN
TEST_MAIN() { TEST_RUN_ALL(); }
|
Correct test name
|
Correct test name
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
758198c03d03584325d18c9da22de8f57033edd2
|
source/system.cpp
|
source/system.cpp
|
/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2009 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#include <crisscross/universal_include.h>
#include <crisscross/system.h>
namespace CrissCross
{
namespace System
{
static long holdrand = 1L;
static double pausedAt = 0.0;
static double timeShift = 0.0;
static bool timerPaused = false;
#if defined (TARGET_OS_WINDOWS)
/* ! The result of QueryPerformanceFrequency(). (Windows only) */
static double __m_tickInterval;
#elif defined (TARGET_OS_MACOSX)
/* ! The time index at which the timer started. ( Mac OS X only) */
uint64_t __m_start;
/* ! The time base information. (Mac OS X only) */
mach_timebase_info_data_t __m_timebase;
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
/* ! The time index at which the timer started. (Linux only) */
timeval __m_start;
#endif
void InitTimer()
{
#if defined (TARGET_OS_WINDOWS)
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
__m_tickInterval = 1.0 / ( double )freq.QuadPart;
#elif defined (TARGET_OS_MACOSX)
mach_timebase_info(&__m_timebase);
__m_start = mach_absolute_time();
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
gettimeofday(&__m_start, NULL);
#endif
timerPaused = false;
}
void SetTimerState(bool _paused)
{
if (_paused && !timerPaused) {
pausedAt = GetHighResTime();
timerPaused = true;
} else if (!_paused && timerPaused) {
timeShift = GetHighResTime() - pausedAt;
timerPaused = false;
}
}
void AdvancePausedTimer(double _seconds)
{
pausedAt += _seconds;
}
double GetHighResTime()
{
double retval;
#if defined (TARGET_OS_WINDOWS)
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
retval = ( double )count.QuadPart * __m_tickInterval;
#elif defined (TARGET_OS_MACOSX)
uint64_t elapsed = mach_absolute_time() - __m_start;
retval = double (elapsed) * (__m_timebase.numer / __m_timebase.denom) /
1000000000.0;
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
timeval now;
double t1, t2;
gettimeofday(&now, NULL);
t1 = ( double )__m_start.tv_sec +
( double )__m_start.tv_usec / (1000 * 1000);
t2 = ( double )now.tv_sec + ( double )now.tv_usec / (1000 * 1000);
retval = t2 - t1;
#endif
return retval - timeShift;
}
void ThreadSleep(int _msec)
{
if (_msec < 0) return;
#if defined (TARGET_OS_WINDOWS)
Sleep(_msec);
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_MACOSX)
unsigned int sleep_time = _msec * 1000;
while (sleep_time > 1000000) {
usleep(1000000);
sleep_time -= 1000000;
}
usleep(sleep_time);
#endif
}
#if defined (TARGET_OS_WINDOWS)
int WaitForThread(HANDLE _thread, DWORD _timeout)
{
WaitForSingleObject(_thread, INFINITE);
return 0;
}
#elif defined (TARGET_OS_LINUX)
int WaitForThread(pthread_t _thread, int _timeout)
{
pthread_join(_thread, NULL);
return 0;
}
#endif
long RandomNumber()
{
#ifdef TARGET_OS_WINDOWS
return (((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
#else
return lrand48();
#endif
}
void SeedRandom()
{
#if defined (TARGET_OS_WINDOWS)
holdrand = GetTickCount();
#else
struct timeval t;
gettimeofday(&t, NULL);
holdrand = t.tv_usec;
srand48(holdrand);
#endif
}
}
}
|
/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2009 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#include <crisscross/universal_include.h>
#include <crisscross/system.h>
namespace CrissCross
{
namespace System
{
static long holdrand = 1L;
static double pausedAt = 0.0;
static double timeShift = 0.0;
static bool timerPaused = false;
#if defined (TARGET_OS_WINDOWS)
/* ! The result of QueryPerformanceFrequency(). (Windows only) */
static double __m_tickInterval;
#elif defined (TARGET_OS_MACOSX)
/* ! The time index at which the timer started. ( Mac OS X only) */
static uint64_t __m_start;
/* ! The time base information. (Mac OS X only) */
static mach_timebase_info_data_t __m_timebase;
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
/* ! The time index at which the timer started. (Linux only) */
static timeval __m_start;
#endif
void InitTimer()
{
#if defined (TARGET_OS_WINDOWS)
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
__m_tickInterval = 1.0 / ( double )freq.QuadPart;
#elif defined (TARGET_OS_MACOSX)
mach_timebase_info(&__m_timebase);
__m_start = mach_absolute_time();
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
gettimeofday(&__m_start, NULL);
#endif
timerPaused = false;
}
void SetTimerState(bool _paused)
{
if (_paused && !timerPaused) {
pausedAt = GetHighResTime();
timerPaused = true;
} else if (!_paused && timerPaused) {
timeShift = GetHighResTime() - pausedAt;
timerPaused = false;
}
}
void AdvancePausedTimer(double _seconds)
{
pausedAt += _seconds;
}
double GetHighResTime()
{
double retval;
#if defined (TARGET_OS_WINDOWS)
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
retval = ( double )count.QuadPart * __m_tickInterval;
#elif defined (TARGET_OS_MACOSX)
uint64_t elapsed = mach_absolute_time() - __m_start;
retval = double (elapsed) * (__m_timebase.numer / __m_timebase.denom) /
1000000000.0;
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \
defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) || \
defined (TARGET_OS_NDSFIRMWARE)
timeval now;
double t1, t2;
gettimeofday(&now, NULL);
t1 = ( double )__m_start.tv_sec +
( double )__m_start.tv_usec / (1000 * 1000);
t2 = ( double )now.tv_sec + ( double )now.tv_usec / (1000 * 1000);
retval = t2 - t1;
#endif
return retval - timeShift;
}
void ThreadSleep(int _msec)
{
if (_msec < 0) return;
#if defined (TARGET_OS_WINDOWS)
Sleep(_msec);
#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_MACOSX)
unsigned int sleep_time = _msec * 1000;
while (sleep_time > 1000000) {
usleep(1000000);
sleep_time -= 1000000;
}
usleep(sleep_time);
#endif
}
#if defined (TARGET_OS_WINDOWS)
int WaitForThread(HANDLE _thread, DWORD _timeout)
{
WaitForSingleObject(_thread, INFINITE);
return 0;
}
#elif defined (TARGET_OS_LINUX)
int WaitForThread(pthread_t _thread, int _timeout)
{
pthread_join(_thread, NULL);
return 0;
}
#endif
long RandomNumber()
{
#ifdef TARGET_OS_WINDOWS
return (((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
#else
return lrand48();
#endif
}
void SeedRandom()
{
#if defined (TARGET_OS_WINDOWS)
holdrand = GetTickCount();
#else
struct timeval t;
gettimeofday(&t, NULL);
holdrand = t.tv_usec;
srand48(holdrand);
#endif
}
}
}
|
make timer related variables static
|
system: make timer related variables static
Signed-off-by: Steven Noonan <[email protected]>
|
C++
|
bsd-3-clause
|
tycho/crisscross,tycho/crisscross,prophile/crisscross,prophile/crisscross,tycho/crisscross,prophile/crisscross
|
3d71b5aaf6d2852793e66bfdc35ec9e695f60df5
|
sound/fmgen/fmgen_file.cpp
|
sound/fmgen/fmgen_file.cpp
|
// $Id: file.cpp,v 1.6 1999/12/28 11:14:05 cisc Exp $
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#ifdef __cplusplus
}
#endif
#include "fmgen_types.h"
#include "fmgen_headers.h"
#include "fmgen_file.h"
// ---------------------------------------------------------------------------
// 構築/消滅
// ---------------------------------------------------------------------------
FileIO::FileIO()
{
flags = 0;
}
FileIO::FileIO(const char* filename, uint flg)
{
flags = 0;
Open(filename, flg);
}
FileIO::~FileIO()
{
Close();
}
// ---------------------------------------------------------------------------
// ファイルを開く
// ---------------------------------------------------------------------------
bool FileIO::Open(const char* filename, uint flg)
{
char mode[5] = "rwb";
Close();
strncpy(path, filename, MAX_PATH);
if(flg & readonly)
strcpy(mode, "rb");
else {
if(flg & create)
strcpy(mode, "rwb+");
else
strcpy(mode, "rwb");
}
pfile = fopen(filename, mode);
flags = (flg & readonly) | (pfile == NULL ? 0 : open);
if (pfile == NULL)
error = file_not_found;
SetLogicalOrigin(0);
return !(pfile == NULL);
}
// ---------------------------------------------------------------------------
// ファイルがない場合は作成
// ---------------------------------------------------------------------------
bool FileIO::CreateNew(const char* filename)
{
uint flg = create;
return Open(filename, flg);
}
// ---------------------------------------------------------------------------
// ファイルを作り直す
// ---------------------------------------------------------------------------
bool FileIO::Reopen(uint flg)
{
if (!(flags & open)) return false;
if ((flags & readonly) && (flg & create)) return false;
if (flags & readonly) flg |= readonly;
return Open(path, flg);
}
// ---------------------------------------------------------------------------
// ファイルを閉じる
// ---------------------------------------------------------------------------
void FileIO::Close()
{
if (GetFlags() & open)
{
fclose(pfile);
flags = 0;
}
}
// ---------------------------------------------------------------------------
// ファイル殻の読み出し
// ---------------------------------------------------------------------------
int32 FileIO::Read(void* dest, int32 size)
{
if (!(GetFlags() & open))
return -1;
DWORD readsize;
if (!(readsize = fread(dest, 1, size, pfile)))
return -1;
return size;
}
// ---------------------------------------------------------------------------
// ファイルへの書き出し
// ---------------------------------------------------------------------------
int32 FileIO::Write(const void* dest, int32 size)
{
if (!(GetFlags() & open) || (GetFlags() & readonly))
return -1;
DWORD writtensize;
if (!(writtensize = fwrite(dest, 1, size, pfile)))
return -1;
return writtensize;
}
// ---------------------------------------------------------------------------
// ファイルをシーク
// ---------------------------------------------------------------------------
bool FileIO::Seek(int32 pos, SeekMethod method)
{
if (!(GetFlags() & open))
return false;
int origin;
switch (method)
{
case begin:
origin = SEEK_SET;
break;
case current:
origin = SEEK_CUR;
break;
case end:
origin = SEEK_END;
break;
default:
return false;
}
return fseek(pfile, pos, origin);
}
// ---------------------------------------------------------------------------
// ファイルの位置を得る
// ---------------------------------------------------------------------------
int32 FileIO::Tellp()
{
if (!(GetFlags() & open))
return 0;
return ftell(pfile);
}
// ---------------------------------------------------------------------------
// 現在の位置をファイルの終端とする
// ---------------------------------------------------------------------------
bool FileIO::SetEndOfFile()
{
if (!(GetFlags() & open))
return false;
return Seek(0, end);
}
|
// $Id: file.cpp,v 1.6 1999/12/28 11:14:05 cisc Exp $
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#ifdef __cplusplus
}
#endif
#include "fmgen_types.h"
#include "fmgen_headers.h"
#include "fmgen_file.h"
// ---------------------------------------------------------------------------
// 構築/消滅
// ---------------------------------------------------------------------------
FileIO::FileIO()
{
pfile = NULL;
flags = 0;
}
FileIO::FileIO(const char* filename, uint flg)
{
pfile = NULL;
flags = 0;
Open(filename, flg);
}
FileIO::~FileIO()
{
Close();
}
// ---------------------------------------------------------------------------
// ファイルを開く
// ---------------------------------------------------------------------------
bool FileIO::Open(const char* filename, uint flg)
{
char mode[5] = "rwb";
Close();
strncpy(path, filename, MAX_PATH);
if(flg & readonly)
strcpy(mode, "rb");
else {
if(flg & create)
strcpy(mode, "rwb+");
else
strcpy(mode, "rwb");
}
pfile = fopen(filename, mode);
flags = (flg & readonly) | (pfile == NULL ? 0 : open);
if (pfile == NULL)
error = file_not_found;
SetLogicalOrigin(0);
return !(pfile == NULL);
}
// ---------------------------------------------------------------------------
// ファイルがない場合は作成
// ---------------------------------------------------------------------------
bool FileIO::CreateNew(const char* filename)
{
uint flg = create;
return Open(filename, flg);
}
// ---------------------------------------------------------------------------
// ファイルを作り直す
// ---------------------------------------------------------------------------
bool FileIO::Reopen(uint flg)
{
if (!(flags & open)) return false;
if ((flags & readonly) && (flg & create)) return false;
if (flags & readonly) flg |= readonly;
return Open(path, flg);
}
// ---------------------------------------------------------------------------
// ファイルを閉じる
// ---------------------------------------------------------------------------
void FileIO::Close()
{
if (GetFlags() & open)
{
if(pfile) {
fclose(pfile);
pfile = NULL;
}
flags = 0;
}
}
// ---------------------------------------------------------------------------
// ファイル殻の読み出し
// ---------------------------------------------------------------------------
int32 FileIO::Read(void* dest, int32 size)
{
if (!(GetFlags() & open))
return -1;
DWORD readsize;
if (!(readsize = fread(dest, 1, size, pfile)))
return -1;
return size;
}
// ---------------------------------------------------------------------------
// ファイルへの書き出し
// ---------------------------------------------------------------------------
int32 FileIO::Write(const void* dest, int32 size)
{
if (!(GetFlags() & open) || (GetFlags() & readonly))
return -1;
DWORD writtensize;
if (!(writtensize = fwrite(dest, 1, size, pfile)))
return -1;
return writtensize;
}
// ---------------------------------------------------------------------------
// ファイルをシーク
// ---------------------------------------------------------------------------
bool FileIO::Seek(int32 pos, SeekMethod method)
{
if (!(GetFlags() & open))
return false;
int origin;
switch (method)
{
case begin:
origin = SEEK_SET;
break;
case current:
origin = SEEK_CUR;
break;
case end:
origin = SEEK_END;
break;
default:
return false;
}
return fseek(pfile, pos, origin);
}
// ---------------------------------------------------------------------------
// ファイルの位置を得る
// ---------------------------------------------------------------------------
int32 FileIO::Tellp()
{
if (!(GetFlags() & open))
return 0;
return ftell(pfile);
}
// ---------------------------------------------------------------------------
// 現在の位置をファイルの終端とする
// ---------------------------------------------------------------------------
bool FileIO::SetEndOfFile()
{
if (!(GetFlags() & open))
return false;
return Seek(0, end);
}
|
fix rhythm file close
|
fix rhythm file close
|
C++
|
mit
|
AZO234/NP2kai,AZO234/NP2kai,AZO234/NP2kai,AZO234/NP2kai
|
bab5e80f5a20cd9ade0c6126d06df3e857a5b415
|
tests/test_shell.cpp
|
tests/test_shell.cpp
|
#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test_find)
{
cu::scheduler sch;
LOGI("---------- begin find test --------");
cu::channel<std::string> c1(sch, 20);
c1.pipeline( find()
, grep("*.h")
, cat()
, replace("class", "object")
, log() );
c1("../..");
LOGI("---------- end find test --------");
}
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch, 100);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(0)
, assert_count(1)
, assert_string("hello")
);
c1("hello big world");
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(1)
, assert_count(1)
, assert_string("big")
);
c2("hello big world");
cu::channel<std::string> c3(sch, 100);
c3.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(2)
, assert_count(1)
, assert_string("world")
);
c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
// TEST(CoroTest, TestCount)
// {
// cu::scheduler sch;
//
// cu::channel<std::string> c1(sch, 100);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
// }
TEST(CoroTest, TestUpper)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 5);
c1.pipeline( replace("mundo", "gente"), toupper(), log() );
sch.spawn([&](auto& yield) {
c1(yield, "hola mundo");
c1(yield, "hola mundo");
c1(yield, "hola mundo");
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("begin");
c1.for_each(yield, [](auto& r) {
LOGI("--> %s", r.c_str());
ASSERT_STREQ("HOLA GENTE", r.c_str());
});
LOGI("end");
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler2)
{
cu::scheduler sch;
cu::channel<int> c1(sch, 5);
cu::channel<int> c2(sch, 5);
cu::channel<int> c3(sch, 5);
sch.spawn([&](auto& yield) {
LOGI("start productor 1 / 2");
for(int x=0; x<100; ++x)
{
LOGI("tick productor 1 / 2: sending: %d", x);
c1(yield, x);
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("start productor 2 / 2");
for(int z=0; z<100; ++z)
{
LOGI("tick productor 2 / 2: sending: %d", z);
c2(yield, z);
}
c2.close(yield);
});
sch.spawn([&](auto& yield)
{
LOGI("start consume a - b");
bool any_closed = false;
while(!any_closed)
{
cu::optional<int> a, b;
switch(cu::select(yield, c1))
{
case 0:
{
a = c1.get(yield);
if(!a)
any_closed = true;
}
break;
}
switch(cu::select(yield, c2))
{
case 0:
{
b = c2.get(yield);
if(!b)
any_closed = true;
}
break;
}
c3(yield, *a + *b);
}
c3.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("start consume final");
c3.for_each(yield, [](auto& r) {
LOGI("result = %d", r);
});
});
sch.run_until_complete();
}
|
#include <atomic>
#include <string>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../shell.h"
#include "../coroutine.h"
#include "../scheduler.h"
#include "../semaphore.h"
#include "../channel.h"
class CoroTest : testing::Test { };
using namespace cu;
TEST(CoroTest, Test_find)
{
cu::scheduler sch;
LOGI("---------- begin find test --------");
cu::channel<std::string> c1(sch, 20);
c1.pipeline( find()
, grep("*.h")
, cat()
, replace("class", "object")
, log() );
c1("../..");
LOGI("---------- end find test --------");
}
TEST(CoroTest, Test_run_ls_strip_quote_grep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
run()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c1("ls .");
/////////////////////////////////
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
ls()
, strip()
, quote()
, grep("shell_*")
, assert_count(1)
, assert_string("\"shell_exe\"")
, log()
);
c2(".");
}
TEST(CoroTest, Test_run_ls_sort_grep_uniq_join)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
std::string out_subproces;
c1.pipeline(run(), strip(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_subproces));
c1("ls .");
//
cu::channel<std::string> c2(sch, 100);
std::string out_ls;
c2.pipeline(ls(), sort(), grep("*fes*"), uniq(), join(), log(), out(out_ls));
c2(".");
//
ASSERT_STREQ(out_subproces.c_str(), out_ls.c_str());
}
TEST(CoroTest, TestCut)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(0)
, assert_count(1)
, assert_string("hello")
);
c1("hello big world");
cu::channel<std::string> c2(sch, 100);
c2.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(1)
, assert_count(1)
, assert_string("big")
);
c2("hello big world");
cu::channel<std::string> c3(sch, 100);
c3.pipeline(
assert_count(1)
, split()
, assert_count(3)
, join()
, assert_count(1)
, cut(2)
, assert_count(1)
, assert_string("world")
);
c3("hello big world");
}
TEST(CoroTest, TestGrep)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(3)
, grep("line2")
, assert_count(1)
, assert_string("line2")
);
c1("line1\nline2\nline3");
}
TEST(CoroTest, TestGrep2)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 100);
c1.pipeline(
split("\n")
, assert_count(4)
);
c1("line1\nline2\nline3\n");
}
// TEST(CoroTest, TestCount)
// {
// cu::scheduler sch;
//
// cu::channel<std::string> c1(sch, 100);
// int result;
// c1.pipeline(
// split("\n")
// , count()
// , out(result)
// );
// c1("line1\nline2\nline3");
// ASSERT_EQ(result, 3) << "maybe count() is not working well";
// }
TEST(CoroTest, TestUpper)
{
cu::scheduler sch;
cu::channel<std::string> c1(sch, 5);
c1.pipeline( replace("mundo", "gente"), toupper(), log() );
sch.spawn([&](auto& yield) {
c1(yield, "hola mundo");
c1(yield, "hola mundo");
c1(yield, "hola mundo");
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("begin");
c1.for_each(yield, [](auto& r) {
LOGI("--> %s", r.c_str());
ASSERT_STREQ("HOLA GENTE", r.c_str());
});
LOGI("end");
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler2)
{
cu::scheduler sch;
cu::channel<int> c1(sch, 5);
cu::channel<int> c2(sch, 5);
cu::channel<int> c3(sch, 5);
sch.spawn([&](auto& yield) {
LOGI("start productor 1 / 2");
for(int x=0; x<100; ++x)
{
LOGI("tick productor 1 / 2: sending: %d", x);
c1(yield, x);
}
c1.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("start productor 2 / 2");
for(int z=0; z<100; ++z)
{
LOGI("tick productor 2 / 2: sending: %d", z);
c2(yield, z);
}
c2.close(yield);
});
sch.spawn([&](auto& yield)
{
LOGI("start consume");
for(;;)
{
cu::optional<int> a;
switch(cu::select(yield, c1))
{
case 0:
{
a = c1.get(yield);
if(!a)
break;
}
break;
default:
}
cu::optional<int> b;
switch(cu::select(yield, c2))
{
case 0:
{
b = c2.get(yield);
if(!b)
break;
}
break;
default:
}
c3(yield, *a + *b);
}
c3.close(yield);
});
sch.spawn([&](auto& yield) {
LOGI("start consume final");
c3.for_each(yield, [](auto& r) {
LOGI("result = %d", r);
});
});
sch.run_until_complete();
}
|
Update test_shell.cpp
|
Update test_shell.cpp
|
C++
|
mit
|
makiolo/cppunix,makiolo/cppunix
|
4b70027fa02ecde2faa939a386f5e82a7f12222f
|
tests/v4l2decode.cpp
|
tests/v4l2decode.cpp
|
/*
* Copyright (C) 2011-2014 Intel Corporation. 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <linux/videodev2.h>
#include <errno.h>
#include <sys/mman.h>
#include <vector>
#include <stdint.h>
#include "common/log.h"
#include "common/utils.h"
#include "decodeinput.h"
#include "decodehelp.h"
#include "V4L2Device.h"
#include "V4L2Renderer.h"
#include <Yami.h>
#ifndef V4L2_EVENT_RESOLUTION_CHANGE
#define V4L2_EVENT_RESOLUTION_CHANGE 5
#endif
uint32_t videoWidth = 0;
uint32_t videoHeight = 0;
static enum v4l2_memory inputMemoryType = V4L2_MEMORY_MMAP;
static VideoDataMemoryType memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME;
static enum v4l2_memory outputMemoryType = V4L2_MEMORY_MMAP;
struct RawFrameData {
uint32_t width;
uint32_t height;
uint32_t pitch[3];
uint32_t offset[3];
uint32_t fourcc; //NV12
uint8_t *data;
};
const uint32_t k_maxInputBufferSize = 1024*1024;
const int k_inputPlaneCount = 1;
const int k_maxOutputPlaneCount = 3;
int outputPlaneCount = 2;
uint32_t inputQueueCapacity = 0;
uint32_t outputQueueCapacity = 0;
uint32_t k_extraOutputFrameCount = 2;
static std::vector<uint8_t*> inputFrames;
static std::vector<struct RawFrameData> rawOutputFrames;
static bool isReadEOS=false;
static int32_t stagingBufferInDevice = 0;
static uint32_t renderFrameCount = 0;
static DecodeParameter params;
bool feedOneInputFrame(DecodeInput* input, const SharedPtr<V4L2Device>& device, int index = -1 /* if index is not -1, simple enque it*/)
{
VideoDecodeBuffer inputBuffer;
struct v4l2_buffer buf;
struct v4l2_plane planes[k_inputPlaneCount];
int ioctlRet = -1;
memset(&buf, 0, sizeof(buf));
memset(&planes, 0, sizeof(planes));
buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; // it indicates input buffer(raw frame) type
buf.memory = inputMemoryType;
buf.m.planes = planes;
buf.length = k_inputPlaneCount;
if (index == -1) {
ioctlRet = device->ioctl(VIDIOC_DQBUF, &buf);
if (ioctlRet == -1)
return true;
stagingBufferInDevice --;
} else {
buf.index = index;
}
if (isReadEOS)
return false;
if (!input->getNextDecodeUnit(inputBuffer)) {
// send empty buffer for EOS
buf.m.planes[0].bytesused = 0;
isReadEOS = true;
} else {
ASSERT(inputBuffer.size <= k_maxInputBufferSize);
memcpy(inputFrames[buf.index], inputBuffer.data, inputBuffer.size);
buf.m.planes[0].bytesused = inputBuffer.size;
buf.m.planes[0].m.mem_offset = 0;
buf.flags = inputBuffer.flag;
}
ioctlRet = device->ioctl(VIDIOC_QBUF, &buf);
ASSERT(ioctlRet != -1);
stagingBufferInDevice ++;
return true;
}
bool handleResolutionChange(const SharedPtr<V4L2Device>& device)
{
bool resolutionChanged = false;
// check resolution change
struct v4l2_event ev;
memset(&ev, 0, sizeof(ev));
while (device->ioctl(VIDIOC_DQEVENT, &ev) == 0) {
if (ev.type == V4L2_EVENT_RESOLUTION_CHANGE) {
resolutionChanged = true;
break;
}
}
if (!resolutionChanged)
return false;
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
if (device->ioctl(VIDIOC_G_FMT, &format) == -1) {
return false;
}
// resolution and pixelformat got here
outputPlaneCount = format.fmt.pix_mp.num_planes;
ASSERT(outputPlaneCount == 2);
videoWidth = format.fmt.pix_mp.width;
videoHeight = format.fmt.pix_mp.height;
return true;
}
extern uint32_t v4l2PixelFormatFromMime(const char* mime);
int main(int argc, char** argv)
{
DecodeInput *input;
uint32_t i = 0;
int32_t ioctlRet = -1;
YamiMediaCodec::CalcFps calcFps;
if (!processCmdLine(argc, argv, ¶ms))
return -1;
switch (params.renderMode) {
case 0:
memoryType = VIDEO_DATA_MEMORY_TYPE_RAW_COPY;
break;
case 3:
memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME;
break;
case 4:
memoryType = VIDEO_DATA_MEMORY_TYPE_DMA_BUF;
break;
case 6:
memoryType = VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF;
break;
default:
ASSERT(0 && "unsupported render mode, -m [0,3,4, 6] are supported");
break;
}
input = DecodeInput::create(params.inputFile);
if (input==NULL) {
ERROR("fail to init input stream\n");
return -1;
}
SharedPtr<V4L2Device> device = V4L2Device::Create();
if (!device) {
ERROR("failed to create v4l2 device");
return -1;
}
SharedPtr<V4L2Renderer> renderer = V4L2Renderer::create(device, memoryType);
if (!renderer) {
ERROR("unsupported render mode %d, please check your build configuration", memoryType);
return -1;
}
renderFrameCount = 0;
calcFps.setAnchor();
// open device
if (!device->open("decoder", 0)) {
ERROR("open decode failed");
return -1;
}
ioctlRet = device->setFrameMemoryType(memoryType);
if (!renderer->setDisplay()) {
ERROR("set display failed");
return -1;
}
// query hw capability
struct v4l2_capability caps;
memset(&caps, 0, sizeof(caps));
caps.capabilities = V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
ioctlRet = device->ioctl(VIDIOC_QUERYCAP, &caps);
ASSERT(ioctlRet != -1);
// set input/output data format
uint32_t codecFormat = v4l2PixelFormatFromMime(input->getMimeType());
if (!codecFormat) {
ERROR("unsupported mimetype, %s", input->getMimeType());
return -1;
}
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
format.fmt.pix_mp.pixelformat = codecFormat;
format.fmt.pix_mp.width = input->getWidth();
format.fmt.pix_mp.height = input->getHeight();
format.fmt.pix_mp.num_planes = 1;
format.fmt.pix_mp.plane_fmt[0].sizeimage = k_maxInputBufferSize;
ioctlRet = device->ioctl(VIDIOC_S_FMT, &format);
ASSERT(ioctlRet != -1);
// set preferred output format
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
uint8_t* data = (uint8_t*)input->getCodecData().data();
uint32_t size = input->getCodecData().size();
//save codecdata, size+data, the type of format.fmt.raw_data is __u8[200]
//we must make sure enough space (>=sizeof(uint32_t) + size) to store codecdata
memcpy(format.fmt.raw_data, &size, sizeof(uint32_t));
if(sizeof(format.fmt.raw_data) >= size + sizeof(uint32_t))
memcpy(format.fmt.raw_data + sizeof(uint32_t), data, size);
else {
ERROR("No enough space to store codec data");
return -1;
}
ioctlRet = device->ioctl(VIDIOC_S_FMT, &format);
ASSERT(ioctlRet != -1);
// input port starts as early as possible to decide output frame format
__u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
ASSERT(ioctlRet != -1);
// setup input buffers
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = inputMemoryType;
reqbufs.count = 8;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
ASSERT(reqbufs.count>0);
inputQueueCapacity = reqbufs.count;
inputFrames.resize(inputQueueCapacity);
for (i=0; i<inputQueueCapacity; i++) {
struct v4l2_plane planes[k_inputPlaneCount];
struct v4l2_buffer buffer;
memset(&buffer, 0, sizeof(buffer));
memset(planes, 0, sizeof(planes));
buffer.index = i;
buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
buffer.memory = inputMemoryType;
buffer.m.planes = planes;
buffer.length = k_inputPlaneCount;
ioctlRet = device->ioctl(VIDIOC_QUERYBUF, &buffer);
ASSERT(ioctlRet != -1);
// length and mem_offset should be filled by VIDIOC_QUERYBUF above
void* address = device->mmap(NULL,
buffer.m.planes[0].length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
buffer.m.planes[0].m.mem_offset);
ASSERT(address);
inputFrames[i] = static_cast<uint8_t*>(address);
DEBUG("inputFrames[%d] = %p", i, inputFrames[i]);
}
// feed input frames first
for (i=0; i<inputQueueCapacity; i++) {
if (!feedOneInputFrame(input, device, i)) {
break;
}
}
// query video resolution
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
while (1) {
if (device->ioctl(VIDIOC_G_FMT, &format) != 0) {
if (errno != EINVAL) {
// EINVAL means we haven't seen sufficient stream to decode the format.
INFO("ioctl() failed: VIDIOC_G_FMT, haven't get video resolution during start yet, waiting");
}
} else {
break;
}
usleep(50);
}
outputPlaneCount = format.fmt.pix_mp.num_planes;
ASSERT(outputPlaneCount == 2);
videoWidth = format.fmt.pix_mp.width;
videoHeight = format.fmt.pix_mp.height;
ASSERT(videoWidth && videoHeight);
bool ret = renderer->setupOutputBuffers(videoWidth, videoHeight);
ASSERT(ret && "setupOutputBuffers failed");
// output port starts as late as possible to adopt user provide output buffer
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
ASSERT(ioctlRet != -1);
bool event_pending=true; // try to get video resolution.
uint32_t dqCountAfterEOS = 0;
do {
if (event_pending) {
handleResolutionChange(device);
}
renderer->renderOneFrame();
if (!feedOneInputFrame(input, device)) {
if (stagingBufferInDevice == 0)
break;
dqCountAfterEOS++;
}
if (dqCountAfterEOS == inputQueueCapacity) // input drain
break;
} while (device->poll(true, &event_pending) == 0);
// drain output buffer
int retry = 3;
while (renderer->renderOneFrame() || (--retry) > 0) { // output drain
usleep(10000);
}
calcFps.fps(renderFrameCount);
// SIMULATE_V4L2_OP(Munmap)(void* addr, size_t length)
possibleWait(input->getMimeType(), ¶ms);
// release queued input/output buffer
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = inputMemoryType;
reqbufs.count = 0;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
reqbufs.memory = outputMemoryType;
reqbufs.count = 0;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
// stop input port
type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
// stop output port
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
// close device
ioctlRet = device->close();
ASSERT(ioctlRet != -1);
if(input)
delete input;
fprintf(stdout, "decode done\n");
return 0;
}
|
/*
* Copyright (C) 2011-2014 Intel Corporation. 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <linux/videodev2.h>
#include <errno.h>
#include <sys/mman.h>
#include <vector>
#include <stdint.h>
#include "common/log.h"
#include "common/utils.h"
#include "decodeinput.h"
#include "decodehelp.h"
#include "V4L2Device.h"
#include "V4L2Renderer.h"
#include <Yami.h>
#ifndef V4L2_EVENT_RESOLUTION_CHANGE
#define V4L2_EVENT_RESOLUTION_CHANGE 5
#endif
uint32_t videoWidth = 0;
uint32_t videoHeight = 0;
static enum v4l2_memory inputMemoryType = V4L2_MEMORY_MMAP;
static VideoDataMemoryType memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME;
static enum v4l2_memory outputMemoryType = V4L2_MEMORY_MMAP;
struct RawFrameData {
uint32_t width;
uint32_t height;
uint32_t pitch[3];
uint32_t offset[3];
uint32_t fourcc; //NV12
uint8_t *data;
};
const uint32_t k_maxInputBufferSize = 1024*1024;
const int k_inputPlaneCount = 1;
const int k_maxOutputPlaneCount = 3;
int outputPlaneCount = 2;
uint32_t inputQueueCapacity = 0;
uint32_t outputQueueCapacity = 0;
uint32_t k_extraOutputFrameCount = 2;
static std::vector<uint8_t*> inputFrames;
static std::vector<struct RawFrameData> rawOutputFrames;
static bool isReadEOS=false;
static int32_t stagingBufferInDevice = 0;
static uint32_t renderFrameCount = 0;
static DecodeParameter params;
bool feedOneInputFrame(DecodeInput* input, const SharedPtr<V4L2Device>& device, int index = -1 /* if index is not -1, simple enque it*/)
{
VideoDecodeBuffer inputBuffer;
struct v4l2_buffer buf;
struct v4l2_plane planes[k_inputPlaneCount];
int ioctlRet = -1;
memset(&buf, 0, sizeof(buf));
memset(&planes, 0, sizeof(planes));
buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; // it indicates input buffer(raw frame) type
buf.memory = inputMemoryType;
buf.m.planes = planes;
buf.length = k_inputPlaneCount;
if (index == -1) {
ioctlRet = device->ioctl(VIDIOC_DQBUF, &buf);
if (ioctlRet == -1)
return true;
stagingBufferInDevice --;
} else {
buf.index = index;
}
if (isReadEOS)
return false;
if (!input->getNextDecodeUnit(inputBuffer)) {
// send empty buffer for EOS
buf.m.planes[0].bytesused = 0;
isReadEOS = true;
} else {
ASSERT(inputBuffer.size <= k_maxInputBufferSize);
memcpy(inputFrames[buf.index], inputBuffer.data, inputBuffer.size);
buf.m.planes[0].bytesused = inputBuffer.size;
buf.m.planes[0].m.mem_offset = 0;
buf.flags = inputBuffer.flag;
}
ioctlRet = device->ioctl(VIDIOC_QBUF, &buf);
ASSERT(ioctlRet != -1);
stagingBufferInDevice ++;
return true;
}
bool handleResolutionChange(const SharedPtr<V4L2Device>& device)
{
bool resolutionChanged = false;
// check resolution change
struct v4l2_event ev;
memset(&ev, 0, sizeof(ev));
while (device->ioctl(VIDIOC_DQEVENT, &ev) == 0) {
if (ev.type == V4L2_EVENT_RESOLUTION_CHANGE) {
resolutionChanged = true;
break;
}
}
if (!resolutionChanged)
return false;
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
if (device->ioctl(VIDIOC_G_FMT, &format) == -1) {
return false;
}
// resolution and pixelformat got here
outputPlaneCount = format.fmt.pix_mp.num_planes;
ASSERT(outputPlaneCount == 2);
videoWidth = format.fmt.pix_mp.width;
videoHeight = format.fmt.pix_mp.height;
return true;
}
extern uint32_t v4l2PixelFormatFromMime(const char* mime);
int main(int argc, char** argv)
{
DecodeInput *input;
uint32_t i = 0;
int32_t ioctlRet = -1;
YamiMediaCodec::CalcFps calcFps;
if (!processCmdLine(argc, argv, ¶ms))
return -1;
switch (params.renderMode) {
case 0:
memoryType = VIDEO_DATA_MEMORY_TYPE_RAW_COPY;
break;
case 3:
memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME;
break;
case 4:
memoryType = VIDEO_DATA_MEMORY_TYPE_DMA_BUF;
break;
case 6:
memoryType = VIDEO_DATA_MEMORY_TYPE_EXTERNAL_DMA_BUF;
break;
default:
ASSERT(0 && "unsupported render mode, -m [0,3,4, 6] are supported");
break;
}
input = DecodeInput::create(params.inputFile);
if (input==NULL) {
ERROR("fail to init input stream\n");
return -1;
}
SharedPtr<V4L2Device> device = V4L2Device::Create();
if (!device) {
ERROR("failed to create v4l2 device");
return -1;
}
SharedPtr<V4L2Renderer> renderer = V4L2Renderer::create(device, memoryType);
if (!renderer) {
ERROR("unsupported render mode %d, please check your build configuration", memoryType);
return -1;
}
renderFrameCount = 0;
calcFps.setAnchor();
// open device
if (!device->open("decoder", 0)) {
ERROR("open decode failed");
return -1;
}
ioctlRet = device->setFrameMemoryType(memoryType);
if (!renderer->setDisplay()) {
ERROR("set display failed");
return -1;
}
// query hw capability
struct v4l2_capability caps;
memset(&caps, 0, sizeof(caps));
caps.capabilities = V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
ioctlRet = device->ioctl(VIDIOC_QUERYCAP, &caps);
ASSERT(ioctlRet != -1);
// set input/output data format
uint32_t codecFormat = v4l2PixelFormatFromMime(input->getMimeType());
if (!codecFormat) {
ERROR("unsupported mimetype, %s", input->getMimeType());
return -1;
}
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
format.fmt.pix_mp.pixelformat = codecFormat;
format.fmt.pix_mp.width = input->getWidth();
format.fmt.pix_mp.height = input->getHeight();
format.fmt.pix_mp.num_planes = 1;
format.fmt.pix_mp.plane_fmt[0].sizeimage = k_maxInputBufferSize;
ioctlRet = device->ioctl(VIDIOC_S_FMT, &format);
ASSERT(ioctlRet != -1);
// set preferred output format
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
uint8_t* data = (uint8_t*)input->getCodecData().data();
uint32_t size = input->getCodecData().size();
//save codecdata, size+data, the type of format.fmt.raw_data is __u8[200]
//we must make sure enough space (>=sizeof(uint32_t) + size) to store codecdata
memcpy(format.fmt.raw_data, &size, sizeof(uint32_t));
if(sizeof(format.fmt.raw_data) >= size + sizeof(uint32_t))
memcpy(format.fmt.raw_data + sizeof(uint32_t), data, size);
else {
ERROR("No enough space to store codec data");
return -1;
}
ioctlRet = device->ioctl(VIDIOC_S_FMT, &format);
ASSERT(ioctlRet != -1);
// input port starts as early as possible to decide output frame format
__u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
ASSERT(ioctlRet != -1);
// setup input buffers
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = inputMemoryType;
reqbufs.count = 8;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
ASSERT(reqbufs.count>0);
inputQueueCapacity = reqbufs.count;
inputFrames.resize(inputQueueCapacity);
for (i=0; i<inputQueueCapacity; i++) {
struct v4l2_plane planes[k_inputPlaneCount];
struct v4l2_buffer buffer;
memset(&buffer, 0, sizeof(buffer));
memset(planes, 0, sizeof(planes));
buffer.index = i;
buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
buffer.memory = inputMemoryType;
buffer.m.planes = planes;
buffer.length = k_inputPlaneCount;
ioctlRet = device->ioctl(VIDIOC_QUERYBUF, &buffer);
ASSERT(ioctlRet != -1);
// length and mem_offset should be filled by VIDIOC_QUERYBUF above
void* address = device->mmap(NULL,
buffer.m.planes[0].length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
buffer.m.planes[0].m.mem_offset);
ASSERT(address);
inputFrames[i] = static_cast<uint8_t*>(address);
DEBUG("inputFrames[%d] = %p", i, inputFrames[i]);
}
// feed input frames first
for (i=0; i<inputQueueCapacity; i++) {
if (!feedOneInputFrame(input, device, i)) {
break;
}
}
// query video resolution
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
while (1) {
if (device->ioctl(VIDIOC_G_FMT, &format) != 0) {
if (errno != EINVAL) {
// EINVAL means we haven't seen sufficient stream to decode the format.
INFO("ioctl() failed: VIDIOC_G_FMT, haven't get video resolution during start yet, waiting");
}
} else {
break;
}
usleep(50);
}
outputPlaneCount = format.fmt.pix_mp.num_planes;
ASSERT(outputPlaneCount == 2);
videoWidth = format.fmt.pix_mp.width;
videoHeight = format.fmt.pix_mp.height;
ASSERT(videoWidth && videoHeight);
bool ret = renderer->setupOutputBuffers(videoWidth, videoHeight);
ASSERT(ret && "setupOutputBuffers failed");
// output port starts as late as possible to adopt user provide output buffer
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
ASSERT(ioctlRet != -1);
//#define SEEK_POS 500
#ifdef SEEK_POS
uint32_t frames = 0;
#endif
bool event_pending=true; // try to get video resolution.
uint32_t dqCountAfterEOS = 0;
do {
if (event_pending) {
handleResolutionChange(device);
}
renderer->renderOneFrame();
if (!feedOneInputFrame(input, device)) {
if (stagingBufferInDevice == 0)
break;
dqCountAfterEOS++;
}
if (dqCountAfterEOS == inputQueueCapacity) // input drain
break;
#ifdef SEEK_POS
frames++;
if (frames == SEEK_POS) {
delete input;
input = DecodeInput::create(params.inputFile);
if (input == NULL) {
ERROR("fail to init input stream\n");
return -1;
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
stagingBufferInDevice = 0;
type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
ASSERT(ioctlRet != -1);
for (i = 0; i < inputQueueCapacity; i++) {
if (!feedOneInputFrame(input, device, i)) {
break;
}
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMON, &type);
renderer->queueOutputBuffers();
}
#endif
} while (device->poll(true, &event_pending) == 0);
// drain output buffer
int retry = 3;
while (renderer->renderOneFrame() || (--retry) > 0) { // output drain
usleep(10000);
}
calcFps.fps(renderFrameCount);
// SIMULATE_V4L2_OP(Munmap)(void* addr, size_t length)
possibleWait(input->getMimeType(), ¶ms);
// release queued input/output buffer
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = inputMemoryType;
reqbufs.count = 0;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
reqbufs.memory = outputMemoryType;
reqbufs.count = 0;
ioctlRet = device->ioctl(VIDIOC_REQBUFS, &reqbufs);
ASSERT(ioctlRet != -1);
// stop input port
type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
// stop output port
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
ioctlRet = device->ioctl(VIDIOC_STREAMOFF, &type);
ASSERT(ioctlRet != -1);
// close device
ioctlRet = device->close();
ASSERT(ioctlRet != -1);
if(input)
delete input;
fprintf(stdout, "decode done\n");
return 0;
}
|
add seek simulation code
|
v4l2decode: add seek simulation code
we have no seek unit test yet, we use this to simulate the seek operation
|
C++
|
apache-2.0
|
01org/libyami-utils,01org/libyami-utils,01org/libyami-utils,01org/libyami-utils
|
5a5c4a83c1e873dcd82c01e8d40c0840f436d627
|
source/Interpreter/OptionGroupWatchpoint.cpp
|
source/Interpreter/OptionGroupWatchpoint.cpp
|
//===-- OptionGroupWatchpoint.cpp -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Interpreter/OptionGroupWatchpoint.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/lldb-enumerations.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Utility/Utils.h"
using namespace lldb;
using namespace lldb_private;
static OptionEnumValueElement g_watch_type[] =
{
{ OptionGroupWatchpoint::eWatchRead, "read", "Watch for read"},
{ OptionGroupWatchpoint::eWatchWrite, "write", "Watch for write"},
{ OptionGroupWatchpoint::eWatchReadWrite, "read_write", "Watch for read/write"},
{ 0, NULL, NULL }
};
static OptionEnumValueElement g_watch_size[] =
{
{ 1, "1", "Watch for byte size of 1"},
{ 2, "2", "Watch for byte size of 2"},
{ 4, "4", "Watch for byte size of 4"},
{ 8, "8", "Watch for byte size of 8"},
{ 0, NULL, NULL }
};
// if you add any options here, remember to update the counters in OptionGroupWatchpoint::GetNumDefinitions()
static OptionDefinition
g_option_table[] =
{
{ LLDB_OPT_SET_1, false, "watch", 'w', required_argument, g_watch_type, 0, eArgTypeWatchType, "Determine how to watch a variable (read, write, or read/write)."},
{ LLDB_OPT_SET_1, false, "xsize", 'x', required_argument, g_watch_size, 0, eArgTypeByteSize, "Number of bytes to use to watch a location (1, 2, 4, or 8)."}
};
OptionGroupWatchpoint::OptionGroupWatchpoint () :
OptionGroup()
{
}
OptionGroupWatchpoint::~OptionGroupWatchpoint ()
{
}
Error
OptionGroupWatchpoint::SetOptionValue (CommandInterpreter &interpreter,
uint32_t option_idx,
const char *option_arg)
{
Error error;
char short_option = (char) g_option_table[option_idx].short_option;
switch (short_option)
{
case 'w':
watch_type = (WatchType) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
if (error.Success())
watch_variable = true;
break;
case 'x':
watch_size = (WatchType) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
break;
default:
error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
break;
}
return error;
}
void
OptionGroupWatchpoint::OptionParsingStarting (CommandInterpreter &interpreter)
{
watch_variable = false;
watch_type = eWatchInvalid;
watch_size = 0;
}
const OptionDefinition*
OptionGroupWatchpoint::GetDefinitions ()
{
return g_option_table;
}
uint32_t
OptionGroupWatchpoint::GetNumDefinitions ()
{
return arraysize(g_option_table);
}
|
//===-- OptionGroupWatchpoint.cpp -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Interpreter/OptionGroupWatchpoint.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/lldb-enumerations.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Utility/Utils.h"
using namespace lldb;
using namespace lldb_private;
static OptionEnumValueElement g_watch_type[] =
{
{ OptionGroupWatchpoint::eWatchRead, "read", "Watch for read"},
{ OptionGroupWatchpoint::eWatchWrite, "write", "Watch for write"},
{ OptionGroupWatchpoint::eWatchReadWrite, "read_write", "Watch for read/write"},
{ 0, NULL, NULL }
};
static OptionEnumValueElement g_watch_size[] =
{
{ 1, "1", "Watch for byte size of 1"},
{ 2, "2", "Watch for byte size of 2"},
{ 4, "4", "Watch for byte size of 4"},
{ 8, "8", "Watch for byte size of 8"},
{ 0, NULL, NULL }
};
// if you add any options here, remember to update the counters in OptionGroupWatchpoint::GetNumDefinitions()
static OptionDefinition
g_option_table[] =
{
{ LLDB_OPT_SET_1, false, "watch", 'w', required_argument, g_watch_type, 0, eArgTypeWatchType, "Determine how to watch a variable; or, with -x option, its pointee."},
{ LLDB_OPT_SET_1, false, "xsize", 'x', required_argument, g_watch_size, 0, eArgTypeByteSize, "Number of bytes to use to watch the pointee."}
};
OptionGroupWatchpoint::OptionGroupWatchpoint () :
OptionGroup()
{
}
OptionGroupWatchpoint::~OptionGroupWatchpoint ()
{
}
Error
OptionGroupWatchpoint::SetOptionValue (CommandInterpreter &interpreter,
uint32_t option_idx,
const char *option_arg)
{
Error error;
char short_option = (char) g_option_table[option_idx].short_option;
switch (short_option)
{
case 'w':
watch_type = (WatchType) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
if (error.Success())
watch_variable = true;
break;
case 'x':
watch_size = (WatchType) Args::StringToOptionEnum(option_arg, g_option_table[option_idx].enum_values, 0, error);
break;
default:
error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
break;
}
return error;
}
void
OptionGroupWatchpoint::OptionParsingStarting (CommandInterpreter &interpreter)
{
watch_variable = false;
watch_type = eWatchInvalid;
watch_size = 0;
}
const OptionDefinition*
OptionGroupWatchpoint::GetDefinitions ()
{
return g_option_table;
}
uint32_t
OptionGroupWatchpoint::GetNumDefinitions ()
{
return arraysize(g_option_table);
}
|
Modify the help text for watching a variable or its pointee.
|
Modify the help text for watching a variable or its pointee.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@142391 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb
|
ae495d0d3910633f6ebc884c1e67e3814a3af76b
|
source/utilities/utils.cpp
|
source/utilities/utils.cpp
|
#include <csignal>
#include <locale>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "utils.hpp"
void debugger() {
#ifdef _MSC_VER
# ifdef _WIN64
throw std::runtime_error("inline asm in unsupported on this platform");
# else
__asm int 3
# endif
#else
raise(SIGTRAP);
#endif
}
std::string enquote(std::string s) {
std::ostringstream result;
result << "\"";
for (auto c : s) {
switch (c) {
case '\'':
result << "\\'";
break;
case '"':
result << "\\\"";
break;
case '?':
result << "\\?";
break;
case '\\':
result << "\\\\";
break;
case '\a':
result << "\\a";
break;
case '\b':
result << "\\b";
break;
case '\f':
result << "\\f";
break;
case '\n':
result << "\\n";
break;
case '\r':
result << "\\r";
break;
case '\t':
result << "\\t";
break;
case '\v':
result << "\\v";
break;
default:
result << c;
}
}
result << "\"";
return result.str();
}
std::string string_replace(std::string const & original, std::string const & find, std::string const & replace) {
std::string newString;
newString.reserve(original.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while (std::string::npos != (findPos = original.find(find, lastPos))) {
newString.append(original, lastPos, findPos - lastPos);
newString += replace;
lastPos = findPos + find.length();
}
// Care for the rest after last occurrence
newString += original.substr(lastPos);
return newString;
}
std::string realpath(std::string fileName) {
struct free_delete {
void operator()(char * x) const {
free(static_cast<void *>(x));
}
};
#ifdef _MSC_VER
std::unique_ptr<char, free_delete> buffer(_fullpath(nullptr, fileName.c_str(), _MAX_PATH));
#else
std::unique_ptr<char, free_delete> buffer(realpath(fileName.c_str(), nullptr));
#endif
return buffer.get();
}
std::string toupper(std::string const & in) {
auto result = in;
for (auto & c : result) c = toupper(c);
return result;
}
std::string tolower(std::string const & in) {
auto result = in;
for (auto & c : result) c = tolower(c);
return result;
}
#ifndef CMAKE_INTDIR
#define CMAKE_INTDIR "None"
#endif
#ifndef CMAKE_BUILD_TYPE
#define CMAKE_BUILD_TYPE "None"
#endif
#ifndef _MSC_VER
// compares two strings in compile time constant fashion
constexpr int c_strcmp(char const * lhs, char const * rhs) {
return '\0' == lhs[0] && '\0' == rhs[0] ? 0
: lhs[0] != rhs[0] ? lhs[0] - rhs[0]
: c_strcmp(lhs + 1, rhs + 1);
}
#endif
|
#include <csignal>
#include <locale>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#ifdef _MSC_VER
# include <Windows.h>
#endif
#include "utils.hpp"
void debugger() {
#ifdef _MSC_VER
DebugBreak();
#else
raise(SIGTRAP);
#endif
}
std::string enquote(std::string s) {
std::ostringstream result;
result << "\"";
for (auto c : s) {
switch (c) {
case '\'':
result << "\\'";
break;
case '"':
result << "\\\"";
break;
case '?':
result << "\\?";
break;
case '\\':
result << "\\\\";
break;
case '\a':
result << "\\a";
break;
case '\b':
result << "\\b";
break;
case '\f':
result << "\\f";
break;
case '\n':
result << "\\n";
break;
case '\r':
result << "\\r";
break;
case '\t':
result << "\\t";
break;
case '\v':
result << "\\v";
break;
default:
result << c;
}
}
result << "\"";
return result.str();
}
std::string string_replace(std::string const & original, std::string const & find, std::string const & replace) {
std::string newString;
newString.reserve(original.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while (std::string::npos != (findPos = original.find(find, lastPos))) {
newString.append(original, lastPos, findPos - lastPos);
newString += replace;
lastPos = findPos + find.length();
}
// Care for the rest after last occurrence
newString += original.substr(lastPos);
return newString;
}
std::string realpath(std::string fileName) {
struct free_delete {
void operator()(char * x) const {
free(static_cast<void *>(x));
}
};
#ifdef _MSC_VER
std::unique_ptr<char, free_delete> buffer(_fullpath(nullptr, fileName.c_str(), _MAX_PATH));
#else
std::unique_ptr<char, free_delete> buffer(realpath(fileName.c_str(), nullptr));
#endif
return buffer.get();
}
std::string toupper(std::string const & in) {
auto result = in;
for (auto & c : result) c = toupper(c);
return result;
}
std::string tolower(std::string const & in) {
auto result = in;
for (auto & c : result) c = tolower(c);
return result;
}
#ifndef CMAKE_INTDIR
#define CMAKE_INTDIR "None"
#endif
#ifndef CMAKE_BUILD_TYPE
#define CMAKE_BUILD_TYPE "None"
#endif
#ifndef _MSC_VER
// compares two strings in compile time constant fashion
constexpr int c_strcmp(char const * lhs, char const * rhs) {
return '\0' == lhs[0] && '\0' == rhs[0] ? 0
: lhs[0] != rhs[0] ? lhs[0] - rhs[0]
: c_strcmp(lhs + 1, rhs + 1);
}
#endif
|
Make debugger() work in MSVC++ 64-bit builds.
|
Make debugger() work in MSVC++ 64-bit builds.
|
C++
|
bsd-3-clause
|
coder0xff/Plange,coder0xff/Plange,coder0xff/Plange,coder0xff/Plange
|
b45c4c5413d6b58173d21823148c5c8cfec57b38
|
source/src/emailinputter/qremailinputter.cpp
|
source/src/emailinputter/qremailinputter.cpp
|
#include "emailinputter/qremailinputter.h"
#include <QtCore/qdebug.h>
#include <QtWidgets/qtextedit.h>
#include <QtGui/qevent.h>
#include <QtWidgets/qlistview.h>
#include <QtGui/qstandarditemmodel.h>
#include <QtWidgets/qboxlayout.h>
#include "emailinputter/qrmailboxfilterproxymodel.h"
#include "emailinputter/qremailinputtextedit.h"
NS_QRWIDGETS_BEGIN
class QrEmailInputterPrivate{
QR_DECLARE_PUBLIC(QrEmailInputter)
public:
QrEMailInputTextEdit *textedit = nullptr;
QString filteredValue;
QListView *listview = nullptr;
QStandardItemModel *listdata = nullptr;
QrMailboxFilterProxyModel *listdataProxy = nullptr;
public:
QrEmailInputterPrivate(QrEmailInputter *q) : q_ptr(q) {}
public:
void initLayout();
void connectListView();
bool upDownListView(bool up);
void showListView();
};
void QrEmailInputterPrivate::initLayout() {
Q_Q(QrEmailInputter);
textedit = new QrEMailInputTextEdit(q);
textedit->installEventFilter(q);
listview = new QListView(q);
listview->installEventFilter(q);
listview->setWindowFlags(Qt::FramelessWindowHint);
listdataProxy = new QrMailboxFilterProxyModel(listview);
listdataProxy->setFilterKeyColumn(0);
listdataProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
listview->setModel(listdataProxy);
listview->setFocusPolicy(Qt::NoFocus);
listview->setEditTriggers(QAbstractItemView::NoEditTriggers);
listview->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listview->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listview->hide();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(textedit);
layout->addWidget(listview);
q->setLayout(layout);
}
void QrEmailInputterPrivate::connectListView() {
QObject::connect(textedit, &QrEMailInputTextEdit::startTyping,
[this](int beginPositionOfBlock){
QTextCursor filterValueCursor = textedit->textCursor();
int filterValueWidth = filterValueCursor.position() - beginPositionOfBlock;
filterValueCursor.movePosition(
QTextCursor::Left,
QTextCursor::MoveAnchor,
filterValueWidth);
filterValueCursor.movePosition(
QTextCursor::Right,
QTextCursor::KeepAnchor,
filterValueWidth);
filteredValue = filterValueCursor.selectedText();
if (filteredValue.isEmpty()) {
listview->hide();
return;
}
listdataProxy->setFilterRegExp(filteredValue);
showListView();
});
QObject::connect(textedit, &QrEMailInputTextEdit::finishTyping, [this](){
filteredValue.clear(); // one mailbox finish, clear filterValue
listview->hide();
});
}
bool QrEmailInputterPrivate::upDownListView(bool up)
{
if (nullptr == listdata
|| 0 == listdataProxy->rowCount()
|| filteredValue.isEmpty()) {
return false;
}
int curRowIdx = listview->selectionModel()->currentIndex().row();
if (-1 == curRowIdx) {
curRowIdx = 0;
}
int nextRowIdx = (up ? --curRowIdx : ++ curRowIdx) % listdataProxy->rowCount();
if (up && -1 == nextRowIdx) {
nextRowIdx = listdataProxy->rowCount() - 1;
}
listview->selectionModel()->setCurrentIndex(
listdataProxy->index(nextRowIdx, 0), QItemSelectionModel::SelectCurrent);
return true;
}
void QrEmailInputterPrivate::showListView() {
auto qPos = textedit->mapToGlobal(textedit->pos());
qPos.setY(qPos.y() + textedit->height());
listview->move(qPos);
listview->show();
}
NS_QRWIDGETS_END
USING_NS_QRWIDGETS;
QrEmailInputter::QrEmailInputter(QWidget *parent)
: QWidget(parent),
d_ptr(new QrEmailInputterPrivate(this))
{
setAttribute(Qt::WA_DeleteOnClose);
Q_D(QrEmailInputter);
d->initLayout();
d->connectListView();
}
void QrEmailInputter::setDDListData(QStandardItemModel *listData)
{
Q_ASSERT(nullptr != listData);
Q_D(QrEmailInputter);
d->listdata = listData;
d->listdataProxy->setSourceModel(d->listdata);
d->listview->resize(width(), height());
}
void QrEmailInputter::setHeightOfDDList(int height)
{
Q_D(QrEmailInputter);
d->listview->resize(d->listview->width(), height);
}
bool QrEmailInputter::keyPress(QKeyEvent *event)
{
Q_D(QrEmailInputter);
switch(event->key()){
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Semicolon:
case Qt::Key_Backspace:
return d->textedit->keyPress(event);
case Qt::Key_Return:
case Qt::Key_Enter:
if (! d->listview->selectionModel()->currentIndex().isValid()) {
return d->textedit->keyPress(event);
}
d->textedit->enterClickFromDDList(
d->listdataProxy->data(
d->listview->selectionModel()->currentIndex())
.toString());
return true;
case Qt::Key_Up: // select the above selection of email-list
return d->upDownListView(true);
case Qt::Key_Down: // select the below selection of email-list
return d->upDownListView(false);
}
if (event->matches(QKeySequence::Paste)
|| event->matches(QKeySequence::Delete)
|| event->matches(QKeySequence::Undo)
|| event->matches(QKeySequence::Redo)) {
return d->textedit->keyPress(event);
}
return false;
}
bool QrEmailInputter::eventFilter(QObject *target, QEvent *event)
{
Q_D(QrEmailInputter);
if (d->textedit == target
&& event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyPress(keyEvent)) {
return true;
}
}
return QWidget::eventFilter(target, event);
}
void QrEmailInputter::hideEvent(QHideEvent *)
{
Q_D(QrEmailInputter);
d->textedit->hide();
d->listview->hide();
}
|
#include "emailinputter/qremailinputter.h"
#include <QtCore/qdebug.h>
#include <QtWidgets/qtextedit.h>
#include <QtGui/qevent.h>
#include <QtWidgets/qlistview.h>
#include <QtGui/qstandarditemmodel.h>
#include <QtWidgets/qboxlayout.h>
#include "emailinputter/qrmailboxfilterproxymodel.h"
#include "emailinputter/qremailinputtextedit.h"
NS_QRWIDGETS_BEGIN
class QrEmailInputterPrivate{
QR_DECLARE_PUBLIC(QrEmailInputter)
public:
QrEMailInputTextEdit *textedit = nullptr;
QString filteredValue;
QListView *listview = nullptr;
QStandardItemModel *listdata = nullptr;
QrMailboxFilterProxyModel *listdataProxy = nullptr;
public:
QrEmailInputterPrivate(QrEmailInputter *q) : q_ptr(q) {}
public:
void initLayout();
void connectListView();
bool upDownListView(bool up);
void showListView();
};
void QrEmailInputterPrivate::initLayout() {
Q_Q(QrEmailInputter);
textedit = new QrEMailInputTextEdit(q);
textedit->installEventFilter(q);
listview = new QListView(q);
listview->installEventFilter(q);
listview->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup | Qt::Tool );
listdataProxy = new QrMailboxFilterProxyModel(listview);
listdataProxy->setFilterKeyColumn(0);
listdataProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
listview->setModel(listdataProxy);
listview->setFocusPolicy(Qt::NoFocus);
listview->setEditTriggers(QAbstractItemView::NoEditTriggers);
listview->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listview->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listview->hide();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(textedit);
layout->addWidget(listview);
q->setLayout(layout);
}
void QrEmailInputterPrivate::connectListView() {
QObject::connect(textedit, &QrEMailInputTextEdit::startTyping,
[this](int beginPositionOfBlock){
QTextCursor filterValueCursor = textedit->textCursor();
int filterValueWidth = filterValueCursor.position() - beginPositionOfBlock;
filterValueCursor.movePosition(
QTextCursor::Left,
QTextCursor::MoveAnchor,
filterValueWidth);
filterValueCursor.movePosition(
QTextCursor::Right,
QTextCursor::KeepAnchor,
filterValueWidth);
filteredValue = filterValueCursor.selectedText();
if (filteredValue.isEmpty()) {
listview->hide();
return;
}
listdataProxy->setFilterRegExp(filteredValue);
showListView();
});
QObject::connect(textedit, &QrEMailInputTextEdit::finishTyping, [this](){
filteredValue.clear(); // one mailbox finish, clear filterValue
listview->hide();
});
}
bool QrEmailInputterPrivate::upDownListView(bool up)
{
if (nullptr == listdata
|| 0 == listdataProxy->rowCount()
|| filteredValue.isEmpty()) {
return false;
}
int curRowIdx = listview->selectionModel()->currentIndex().row();
if (-1 == curRowIdx) {
curRowIdx = 0;
}
int nextRowIdx = (up ? --curRowIdx : ++ curRowIdx) % listdataProxy->rowCount();
if (up && -1 == nextRowIdx) {
nextRowIdx = listdataProxy->rowCount() - 1;
}
listview->selectionModel()->setCurrentIndex(
listdataProxy->index(nextRowIdx, 0), QItemSelectionModel::SelectCurrent);
return true;
}
void QrEmailInputterPrivate::showListView()
{
listview->resize(textedit->size());
auto qPos = textedit->mapToGlobal(textedit->pos());
qPos.setY(qPos.y() + textedit->height());
listview->move(qPos - QPoint(10,10));
listview->show();
}
NS_QRWIDGETS_END
USING_NS_QRWIDGETS;
QrEmailInputter::QrEmailInputter(QWidget *parent)
: QWidget(parent),
d_ptr(new QrEmailInputterPrivate(this))
{
Q_D(QrEmailInputter);
d->initLayout();
d->connectListView();
}
void QrEmailInputter::setDDListData(QStandardItemModel *listData)
{
Q_ASSERT(nullptr != listData);
Q_D(QrEmailInputter);
d->listdata = listData;
d->listdataProxy->setSourceModel(d->listdata);
}
void QrEmailInputter::setHeightOfDDList(int height)
{
Q_D(QrEmailInputter);
d->listview->resize(d->listview->width(), height);
}
bool QrEmailInputter::keyPress(QKeyEvent *event)
{
Q_D(QrEmailInputter);
switch(event->key()){
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Semicolon:
case Qt::Key_Backspace:
return d->textedit->keyPress(event);
case Qt::Key_Return:
case Qt::Key_Enter:
if (! d->listview->selectionModel()->currentIndex().isValid()) {
return d->textedit->keyPress(event);
}
d->textedit->enterClickFromDDList(
d->listdataProxy->data(
d->listview->selectionModel()->currentIndex())
.toString());
return true;
case Qt::Key_Up: // select the above selection of email-list
return d->upDownListView(true);
case Qt::Key_Down: // select the below selection of email-list
return d->upDownListView(false);
}
if (event->matches(QKeySequence::Paste)
|| event->matches(QKeySequence::Delete)
|| event->matches(QKeySequence::Undo)
|| event->matches(QKeySequence::Redo)) {
return d->textedit->keyPress(event);
}
return false;
}
bool QrEmailInputter::eventFilter(QObject *target, QEvent *event)
{
Q_D(QrEmailInputter);
if (d->textedit == target
&& event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyPress(keyEvent)) {
return true;
}
}
return QWidget::eventFilter(target, event);
}
void QrEmailInputter::hideEvent(QHideEvent *)
{
Q_D(QrEmailInputter);
d->textedit->hide();
d->listview->hide();
}
|
set email inputter 's list as a pop up widget
|
set email inputter 's list as a pop up widget
|
C++
|
apache-2.0
|
Qters/QrWidgets
|
2ba7834604c605cce904380037712a79d159bee9
|
test/eigensolver_generalized_real.cpp
|
test/eigensolver_generalized_real.cpp
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>
template<typename MatrixType> void generalized_eigensolver_real(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
/* this test covers the following files:
GeneralizedEigenSolver.h
*/
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
MatrixType a = MatrixType::Random(rows,cols);
MatrixType b = MatrixType::Random(rows,cols);
MatrixType a1 = MatrixType::Random(rows,cols);
MatrixType b1 = MatrixType::Random(rows,cols);
MatrixType spdA = a.adjoint() * a + a1.adjoint() * a1;
MatrixType spdB = b.adjoint() * b + b1.adjoint() * b1;
// lets compare to GeneralizedSelfAdjointEigenSolver
GeneralizedSelfAdjointEigenSolver<MatrixType> symmEig(spdA, spdB);
GeneralizedEigenSolver<MatrixType> eig(spdA, spdB);
VERIFY_IS_EQUAL(eig.eigenvalues().imag().cwiseAbs().maxCoeff(), 0);
VectorType realEigenvalues = eig.eigenvalues().real();
std::sort(realEigenvalues.data(), realEigenvalues.data()+realEigenvalues.size());
VERIFY_IS_APPROX(realEigenvalues, symmEig.eigenvalues());
// regression test for bug 1098
{
GeneralizedSelfAdjointEigenSolver<MatrixType> eig1(a.adjoint() * a,b.adjoint() * b);
eig1.compute(a.adjoint() * a,b.adjoint() * b);
GeneralizedEigenSolver<MatrixType> eig2(a.adjoint() * a,b.adjoint() * b);
eig2.compute(a.adjoint() * a,b.adjoint() * b);
}
}
void test_eigensolver_generalized_real()
{
for(int i = 0; i < g_repeat; i++) {
int s = 0;
CALL_SUBTEST_1( generalized_eigensolver_real(Matrix4f()) );
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(s,s)) );
// some trivial but implementation-wise tricky cases
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(1,1)) );
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(2,2)) );
CALL_SUBTEST_3( generalized_eigensolver_real(Matrix<double,1,1>()) );
CALL_SUBTEST_4( generalized_eigensolver_real(Matrix2d()) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
}
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012-2016 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>
#include <Eigen/LU>
template<typename MatrixType> void generalized_eigensolver_real(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
/* this test covers the following files:
GeneralizedEigenSolver.h
*/
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef std::complex<Scalar> ComplexScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
MatrixType a = MatrixType::Random(rows,cols);
MatrixType b = MatrixType::Random(rows,cols);
MatrixType a1 = MatrixType::Random(rows,cols);
MatrixType b1 = MatrixType::Random(rows,cols);
MatrixType spdA = a.adjoint() * a + a1.adjoint() * a1;
MatrixType spdB = b.adjoint() * b + b1.adjoint() * b1;
// lets compare to GeneralizedSelfAdjointEigenSolver
{
GeneralizedSelfAdjointEigenSolver<MatrixType> symmEig(spdA, spdB);
GeneralizedEigenSolver<MatrixType> eig(spdA, spdB);
VERIFY_IS_EQUAL(eig.eigenvalues().imag().cwiseAbs().maxCoeff(), 0);
VectorType realEigenvalues = eig.eigenvalues().real();
std::sort(realEigenvalues.data(), realEigenvalues.data()+realEigenvalues.size());
VERIFY_IS_APPROX(realEigenvalues, symmEig.eigenvalues());
}
// non symmetric case:
{
GeneralizedEigenSolver<MatrixType> eig(a,b);
for(Index k=0; k<cols; ++k)
{
Matrix<ComplexScalar,Dynamic,Dynamic> tmp = (eig.betas()(k)*a).template cast<ComplexScalar>() - eig.alphas()(k)*b;
if(tmp.norm()>(std::numeric_limits<Scalar>::min)())
tmp /= tmp.norm();
VERIFY_IS_MUCH_SMALLER_THAN( std::abs(tmp.determinant()), Scalar(1) );
}
}
// regression test for bug 1098
{
GeneralizedSelfAdjointEigenSolver<MatrixType> eig1(a.adjoint() * a,b.adjoint() * b);
eig1.compute(a.adjoint() * a,b.adjoint() * b);
GeneralizedEigenSolver<MatrixType> eig2(a.adjoint() * a,b.adjoint() * b);
eig2.compute(a.adjoint() * a,b.adjoint() * b);
}
}
void test_eigensolver_generalized_real()
{
for(int i = 0; i < g_repeat; i++) {
int s = 0;
CALL_SUBTEST_1( generalized_eigensolver_real(Matrix4f()) );
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(s,s)) );
// some trivial but implementation-wise special cases
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(1,1)) );
CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(2,2)) );
CALL_SUBTEST_3( generalized_eigensolver_real(Matrix<double,1,1>()) );
CALL_SUBTEST_4( generalized_eigensolver_real(Matrix2d()) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
}
}
|
Add unit test for non symmetric generalized eigenvalues
|
Add unit test for non symmetric generalized eigenvalues
|
C++
|
bsd-3-clause
|
pasuka/eigen,ritsu1228/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen,pasuka/eigen,ritsu1228/eigen,ritsu1228/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,ritsu1228/eigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,ritsu1228/eigen
|
b2ea3849ad4ca19858f45f650925fee088ccefa0
|
MFT/AliMuonForwardTrackPair.cxx
|
MFT/AliMuonForwardTrackPair.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//====================================================================================================================================================
//
// Description of an ALICE muon forward track pair, i.e. a pair of AliMuonForwardTrack objects
//
// Contact author: [email protected]
//
//====================================================================================================================================================
#include "AliLog.h"
#include "AliMUONTrackParam.h"
#include "TParticle.h"
#include "AliMuonForwardTrack.h"
#include "AliMUONTrackExtrap.h"
#include "TClonesArray.h"
#include "TDatabasePDG.h"
#include "TLorentzVector.h"
#include "TRandom.h"
#include "AliMuonForwardTrackPair.h"
ClassImp(AliMuonForwardTrackPair)
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair():
TObject(),
fMuonForwardTracks(0),
fKinemMC(0,0,0,0),
fKinem(0,0,0,0),
fIsKinemSet(kFALSE)
{
// default constructor
fMuonForwardTracks = new TClonesArray("AliMuonForwardTrack", 2);
}
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair(AliMuonForwardTrack *track0, AliMuonForwardTrack *track1):
TObject(),
fMuonForwardTracks(0),
fKinemMC(0,0,0,0),
fKinem(0,0,0,0),
fIsKinemSet(kFALSE)
{
fMuonForwardTracks = new TClonesArray("AliMuonForwardTrack", 2);
new ((*fMuonForwardTracks)[0]) AliMuonForwardTrack(*track0);
new ((*fMuonForwardTracks)[1]) AliMuonForwardTrack(*track1);
SetKinemMC();
}
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair(const AliMuonForwardTrackPair& trackPair):
TObject(trackPair),
fMuonForwardTracks(trackPair.fMuonForwardTracks),
fKinemMC(trackPair.fKinemMC),
fKinem(trackPair.fKinem),
fIsKinemSet(trackPair.fIsKinemSet)
{
// copy constructor
}
//====================================================================================================================================================
AliMuonForwardTrackPair& AliMuonForwardTrackPair::operator=(const AliMuonForwardTrackPair& trackPair) {
// Asignment operator
// check assignement to self
if (this == &trackPair) return *this;
// base class assignement
AliMuonForwardTrackPair::operator=(trackPair);
// clear memory
Clear();
fMuonForwardTracks = trackPair.fMuonForwardTracks;
fKinemMC = trackPair.fKinemMC;
fKinem = trackPair.fKinem;
fIsKinemSet = trackPair.fIsKinemSet;
return *this;
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetTrack(Int_t iTrack, AliMuonForwardTrack *track) {
if (iTrack==0 || iTrack==1) {
new ((*fMuonForwardTracks)[iTrack]) AliMuonForwardTrack(*track);
}
}
//====================================================================================================================================================
Double_t AliMuonForwardTrackPair::GetWeightedOffset(Double_t x, Double_t y, Double_t z) {
Double_t weightedOffset[2]={0};
weightedOffset[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetWeightedOffset(x, y, z);
weightedOffset[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetWeightedOffset(x, y, z);
Double_t weightedOffsetDimuon = TMath::Sqrt(0.5 * (weightedOffset[0]*weightedOffset[0] + weightedOffset[1]*weightedOffset[1]));
return weightedOffsetDimuon;
}
//====================================================================================================================================================
Double_t AliMuonForwardTrackPair::GetMassWithoutMFT(Double_t x, Double_t y, Double_t z, Int_t nClusters) {
Int_t idCluster[2] = {0};
if (nClusters>0) {
idCluster[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetNMUONClusters() - nClusters;
idCluster[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetNMUONClusters() - nClusters;
}
if (idCluster[0]<0) idCluster[0] = 0;
if (idCluster[1]<0) idCluster[1] = 0;
AliMUONTrackParam *param0 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetTrackParamAtMUONCluster(idCluster[0]);
AliMUONTrackParam *param1 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetTrackParamAtMUONCluster(idCluster[1]);
AliDebug(2, Form("MUON before extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
AliDebug(2, Form("Extrapolating 1st muon from z = %f to z = %f", param0->GetZ(), z));
AliMUONTrackExtrap::ExtrapToVertex(param0, x, y, z, 0., 0.); // this should reproduce what is done in AliMUONESDInterface::MUONToESD(...)
AliDebug(2, Form("Extrapolating 2nd muon from z = %f to z = %f", param1->GetZ(), z));
AliMUONTrackExtrap::ExtrapToVertex(param1, x, y, z, 0., 0.); // this should reproduce what is done in AliMUONESDInterface::MUONToESD(...)
AliDebug(2, Form("MUON after extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
Double_t momentum[2] = {0};
momentum[0] = param0->P();
momentum[1] = param1->P();
Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass();
TLorentzVector dimu;
dimu.SetE(TMath::Sqrt(mMu*mMu + momentum[0]*momentum[0]) + TMath::Sqrt(mMu*mMu + momentum[1]*momentum[1]));
dimu.SetPx(param0->Px() + param1->Px());
dimu.SetPy(param0->Py() + param1->Py());
dimu.SetPz(param0->Pz() + param1->Pz());
return dimu.M();
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetKinemMC() {
if ( !(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()) ||
!(((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()) ) return;
AliDebug(2, Form("MC: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Px(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Py(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Pz(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Px(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Py(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Pz()));
fKinemMC.SetE(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Energy() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Energy());
fKinemMC.SetPx(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Px() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Px());
fKinemMC.SetPy(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Py() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Py());
fKinemMC.SetPz(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Pz() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Pz());
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetKinem(Double_t z, Int_t nClusters) {
// if (!fMuonForwardTracks) return kFALSE;
// if (!fMuonForwardTracks->At(0) || !fMuonForwardTracks->At(1)) return kFALSE;
Int_t idCluster[2] = {0};
if (nClusters>0) {
idCluster[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetNMFTClusters() - nClusters;
idCluster[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetNMFTClusters() - nClusters;
}
if (idCluster[0]<0) idCluster[0] = 0;
if (idCluster[1]<0) idCluster[1] = 0;
Double_t momentum[2] = {0};
AliMUONTrackParam *param0 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetTrackParamAtMFTCluster(idCluster[0]);
AliMUONTrackParam *param1 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetTrackParamAtMFTCluster(idCluster[1]);
AliDebug(2, Form("MFT before extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
if (TMath::Abs(z)<1e6) {
AliDebug(2, Form("Extrapolating 1st muon from z = %f to z = %f", param0->GetZ(), z));
AliMUONTrackExtrap::ExtrapToZCov(param0, z);
AliDebug(2, Form("Extrapolating 2nd muon from z = %f to z = %f", param1->GetZ(), z));
AliMUONTrackExtrap::ExtrapToZCov(param1, z);
}
AliDebug(2, Form("MFT after extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
momentum[0] = (param0->P());
momentum[1] = (param1->P());
Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass();
fKinem.SetE(TMath::Sqrt(mMu*mMu + momentum[0]*momentum[0]) + TMath::Sqrt(mMu*mMu + momentum[1]*momentum[1]));
fKinem.SetPx(param0->Px() + param1->Px());
fKinem.SetPy(param0->Py() + param1->Py());
fKinem.SetPz(param0->Pz() + param1->Pz());
fIsKinemSet = kTRUE;
// return fKinem.M();
}
//====================================================================================================================================================
Bool_t AliMuonForwardTrackPair::IsResonance() {
Bool_t result = kFALSE;
Int_t labelMC[2] = {0};
Int_t codePDG[2] = {0};
for (Int_t iTrack=0; iTrack<2; iTrack++) {
labelMC[iTrack] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(iTrack))->GetParentMCLabel(0);
codePDG[iTrack] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(iTrack))->GetParentPDGCode(0);
}
AliDebug(1, Form("Muons' mothers: (%d, %d)", labelMC[0], labelMC[1]));
if (labelMC[0]==labelMC[1] && codePDG[0]==codePDG[1] && (codePDG[0]== 113 ||
codePDG[0]== 223 ||
codePDG[0]== 333 ||
codePDG[0]== 443 ||
codePDG[0]==100443 ||
codePDG[0]== 553 ||
codePDG[0]==100553 ) ) result = kTRUE;
if (result) AliDebug(1, Form("Pair is a resonance %d", codePDG[0]));
return result;
}
//====================================================================================================================================================
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//====================================================================================================================================================
//
// Description of an ALICE muon forward track pair, i.e. a pair of AliMuonForwardTrack objects
//
// Contact author: [email protected]
//
//====================================================================================================================================================
#include "AliLog.h"
#include "AliMUONTrackParam.h"
#include "TParticle.h"
#include "AliMuonForwardTrack.h"
#include "AliMUONTrackExtrap.h"
#include "TClonesArray.h"
#include "TDatabasePDG.h"
#include "TLorentzVector.h"
#include "TRandom.h"
#include "AliMuonForwardTrackPair.h"
ClassImp(AliMuonForwardTrackPair)
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair():
TObject(),
fMuonForwardTracks(0),
fKinemMC(0,0,0,0),
fKinem(0,0,0,0),
fIsKinemSet(kFALSE)
{
// default constructor
fMuonForwardTracks = new TClonesArray("AliMuonForwardTrack", 2);
}
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair(AliMuonForwardTrack *track0, AliMuonForwardTrack *track1):
TObject(),
fMuonForwardTracks(0),
fKinemMC(0,0,0,0),
fKinem(0,0,0,0),
fIsKinemSet(kFALSE)
{
fMuonForwardTracks = new TClonesArray("AliMuonForwardTrack", 2);
new ((*fMuonForwardTracks)[0]) AliMuonForwardTrack(*track0);
new ((*fMuonForwardTracks)[1]) AliMuonForwardTrack(*track1);
SetKinemMC();
}
//====================================================================================================================================================
AliMuonForwardTrackPair::AliMuonForwardTrackPair(const AliMuonForwardTrackPair& trackPair):
TObject(trackPair),
fMuonForwardTracks(trackPair.fMuonForwardTracks),
fKinemMC(trackPair.fKinemMC),
fKinem(trackPair.fKinem),
fIsKinemSet(trackPair.fIsKinemSet)
{
// copy constructor
}
//====================================================================================================================================================
AliMuonForwardTrackPair& AliMuonForwardTrackPair::operator=(const AliMuonForwardTrackPair& trackPair) {
// Asignment operator
// check assignement to self
if (this == &trackPair) return *this;
// base class assignement
AliMuonForwardTrackPair::operator=(trackPair);
// clear memory
Clear();
fMuonForwardTracks = trackPair.fMuonForwardTracks;
fKinemMC = trackPair.fKinemMC;
fKinem = trackPair.fKinem;
fIsKinemSet = trackPair.fIsKinemSet;
return *this;
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetTrack(Int_t iTrack, AliMuonForwardTrack *track) {
if (iTrack==0 || iTrack==1) {
new ((*fMuonForwardTracks)[iTrack]) AliMuonForwardTrack(*track);
}
}
//====================================================================================================================================================
Double_t AliMuonForwardTrackPair::GetWeightedOffset(Double_t x, Double_t y, Double_t z) {
Double_t weightedOffset[2]={0};
weightedOffset[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetWeightedOffset(x, y, z);
weightedOffset[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetWeightedOffset(x, y, z);
Double_t weightedOffsetDimuon = TMath::Sqrt(0.5 * (weightedOffset[0]*weightedOffset[0] + weightedOffset[1]*weightedOffset[1]));
return weightedOffsetDimuon;
}
//====================================================================================================================================================
Double_t AliMuonForwardTrackPair::GetMassWithoutMFT(Double_t x, Double_t y, Double_t z, Int_t nClusters) {
Int_t idCluster[2] = {0};
if (nClusters>0) {
idCluster[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetNMUONClusters() - nClusters;
idCluster[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetNMUONClusters() - nClusters;
}
if (idCluster[0]<0) idCluster[0] = 0;
if (idCluster[1]<0) idCluster[1] = 0;
AliMUONTrackParam *param0 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetTrackParamAtMUONCluster(idCluster[0]);
AliMUONTrackParam *param1 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetTrackParamAtMUONCluster(idCluster[1]);
AliDebug(2, Form("MUON before extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
AliDebug(2, Form("Extrapolating 1st muon from z = %f to z = %f", param0->GetZ(), z));
AliMUONTrackExtrap::ExtrapToVertex(param0, x, y, z, 0., 0.); // this should reproduce what is done in AliMUONESDInterface::MUONToESD(...)
AliDebug(2, Form("Extrapolating 2nd muon from z = %f to z = %f", param1->GetZ(), z));
AliMUONTrackExtrap::ExtrapToVertex(param1, x, y, z, 0., 0.); // this should reproduce what is done in AliMUONESDInterface::MUONToESD(...)
AliDebug(2, Form("MUON after extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
Double_t momentum[2] = {0};
momentum[0] = param0->P();
momentum[1] = param1->P();
Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass();
TLorentzVector dimu;
dimu.SetE(TMath::Sqrt(mMu*mMu + momentum[0]*momentum[0]) + TMath::Sqrt(mMu*mMu + momentum[1]*momentum[1]));
dimu.SetPx(param0->Px() + param1->Px());
dimu.SetPy(param0->Py() + param1->Py());
dimu.SetPz(param0->Pz() + param1->Pz());
return dimu.M();
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetKinemMC() {
if ( !(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()) ||
!(((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()) ) return;
AliDebug(2, Form("MC: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Px(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Py(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Pz(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Px(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Py(),
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Pz()));
fKinemMC.SetE(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Energy() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Energy());
fKinemMC.SetPx(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Px() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Px());
fKinemMC.SetPy(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Py() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Py());
fKinemMC.SetPz(((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetMCTrackRef()->Pz() +
((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetMCTrackRef()->Pz());
}
//====================================================================================================================================================
void AliMuonForwardTrackPair::SetKinem(Double_t z, Int_t nClusters) {
// if (!fMuonForwardTracks) return kFALSE;
// if (!fMuonForwardTracks->At(0) || !fMuonForwardTracks->At(1)) return kFALSE;
Int_t idCluster[2] = {0};
if (nClusters>0) {
idCluster[0] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetNMFTClusters() - nClusters;
idCluster[1] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetNMFTClusters() - nClusters;
}
if (idCluster[0]<0) idCluster[0] = 0;
if (idCluster[1]<0) idCluster[1] = 0;
Double_t momentum[2] = {0};
AliMUONTrackParam *param0 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(0))->GetTrackParamAtMFTCluster(idCluster[0]);
AliMUONTrackParam *param1 = ((AliMuonForwardTrack*) fMuonForwardTracks->At(1))->GetTrackParamAtMFTCluster(idCluster[1]);
AliDebug(2, Form("MFT before extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
if (TMath::Abs(z)<1e6) {
AliDebug(2, Form("Extrapolating 1st muon from z = %f to z = %f", param0->GetZ(), z));
AliMUONTrackExtrap::ExtrapToZCov(param0, z);
AliDebug(2, Form("Extrapolating 2nd muon from z = %f to z = %f", param1->GetZ(), z));
AliMUONTrackExtrap::ExtrapToZCov(param1, z);
}
AliDebug(2, Form("MFT after extrap: 1st muon = (%f, %f, %f) 2nd muon = (%f, %f, %f)",
param0->Px(), param0->Py(), param0->Pz(),
param1->Px(), param1->Py(), param1->Pz()));
momentum[0] = (param0->P());
momentum[1] = (param1->P());
Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass();
fKinem.SetE(TMath::Sqrt(mMu*mMu + momentum[0]*momentum[0]) + TMath::Sqrt(mMu*mMu + momentum[1]*momentum[1]));
fKinem.SetPx(param0->Px() + param1->Px());
fKinem.SetPy(param0->Py() + param1->Py());
fKinem.SetPz(param0->Pz() + param1->Pz());
fIsKinemSet = kTRUE;
// return fKinem.M();
}
//====================================================================================================================================================
Bool_t AliMuonForwardTrackPair::IsResonance() {
Bool_t result = kFALSE;
Int_t labelMC[2] = {0};
Int_t codePDG[2] = {0};
for (Int_t iTrack=0; iTrack<2; iTrack++) {
labelMC[iTrack] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(iTrack))->GetParentMCLabel(0);
codePDG[iTrack] = ((AliMuonForwardTrack*) fMuonForwardTracks->At(iTrack))->GetParentPDGCode(0);
}
AliDebug(1, Form("Muons' mothers: (%d, %d)", labelMC[0], labelMC[1]));
if (labelMC[0]==labelMC[1] && codePDG[0]==codePDG[1] && (codePDG[0]== 113 ||
codePDG[0]== 221 ||
codePDG[0]== 223 ||
codePDG[0]== 331 ||
codePDG[0]== 333 ||
codePDG[0]== 443 ||
codePDG[0]==100443 ||
codePDG[0]== 553 ||
codePDG[0]==100553 ) ) result = kTRUE;
if (result) AliDebug(1, Form("Pair is a resonance %d", codePDG[0]));
return result;
}
//====================================================================================================================================================
|
Update in AliMuonForwardTrackPair class
|
Update in AliMuonForwardTrackPair class
|
C++
|
bsd-3-clause
|
ALICEHLT/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,alisw/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,alisw/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,shahor02/AliRoot,miranov25/AliRoot,miranov25/AliRoot,shahor02/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot
|
b49218251e1df83a93e46e5111aaccbef95abafc
|
libspaghetti/source/nodes/values/characteristic_curve/editor_window.cc
|
libspaghetti/source/nodes/values/characteristic_curve/editor_window.cc
|
// MIT License
//
// Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl
//
// 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 "nodes/values/characteristic_curve/editor_window.h"
#include "elements/values/characteristic_curve.h"
#include "nodes/values/characteristic_curve.h"
#include "nodes/values/characteristic_curve/ui_editor_window.h"
#include <algorithm>
#include <QCheckBox>
#include <QComboBox>
#include <QDebug>
#include <QDoubleValidator>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QIntValidator>
#include <QItemDelegate>
#include <QKeyEvent>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTabWidget>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QtCharts/QLineSeries>
#include "ui/package_view.h"
//#include "nodes/values/characteristic_curve/axis_widget.h"
#include "nodes/values/characteristic_curve/axis.h"
//#include "nodes/values/characteristic_curve/series_widget.h"
#include "nodes/values/characteristic_curve/series.h"
template<class T>
class VPtr {
public:
static T *asPtr(QVariant v) { return reinterpret_cast<T *>(v.value<void *>()); }
static QVariant asQVariant(T *ptr) { return qVariantFromValue(static_cast<void *>(ptr)); }
};
namespace spaghetti::nodes::values::characteristic_curve {
class Delegate : public QItemDelegate {
public:
Delegate(EditorWindow *const a_window)
: QItemDelegate{ a_window }
, m_window{ a_window }
{
}
QWidget *createEditor(QWidget *a_parent, QStyleOptionViewItem const &a_option,
QModelIndex const &a_index) const override
{
(void)a_option;
auto const lineEdit = new QLineEdit{ a_parent };
EditorWindow::ValueType const TYPE{ (a_index.column() == 0 ? m_window->xValueType() : m_window->yValueType()) };
QValidator *validator{};
if (TYPE == EditorWindow::ValueType::eInt)
validator = new QIntValidator;
else
validator = new QDoubleValidator;
QLocale const LOCALE(QLocale::Language::English);
validator->setLocale(LOCALE);
lineEdit->setValidator(validator);
return lineEdit;
}
private:
EditorWindow *const m_window{};
};
EditorWindow::EditorWindow(CharacteristicCurve *const a_characteristicCurve)
: QDialog{ a_characteristicCurve->packageView() }
, m_ui{ new Ui::EditorWindow }
, m_characteristicCurve{ a_characteristicCurve }
{
m_ui->setupUi(this);
m_ui->editor->setEditorWindow(this);
QLocale const LOCALE{ QLocale::Language::English };
m_ui->editor->setLocale(LOCALE);
m_ui->seriesTable->setLocale(LOCALE);
m_ui->xAxisName->setText(m_ui->editor->xName());
m_ui->xAxisMajorTicks->setValue(m_ui->editor->xMajorTicks());
m_ui->xAxisMinorTicks->setValue(m_ui->editor->xMinorTicks());
m_ui->xAxisMinimum->setValue(m_ui->editor->xMinimum());
m_ui->xAxisMaximum->setValue(m_ui->editor->xMaximum());
connect(m_ui->xAxisName, &QLineEdit::textChanged, [this](QString const &a_name) {
m_characteristicCurve->changeInputName(0, a_name);
m_ui->editor->setXName(a_name);
});
connect(m_ui->xAxisMajorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setXMajorTicks(a_value); });
connect(m_ui->xAxisMinorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setXMinorTicks(a_value); });
connect(m_ui->xAxisMinimum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setXMinimum(a_value); });
connect(m_ui->xAxisMaximum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setXMaximum(a_value); });
connect(m_ui->yAxisName, &QLineEdit::textChanged, [this](QString const &a_name) {
m_characteristicCurve->changeOutputName(0, a_name);
m_ui->editor->setYName(a_name);
});
connect(m_ui->yAxisMajorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setYMajorTicks(a_value); });
connect(m_ui->yAxisMinorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setYMinorTicks(a_value); });
connect(m_ui->yAxisMinimum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setYMinimum(a_value); });
connect(m_ui->yAxisMaximum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setYMaximum(a_value); });
connect(m_ui->seriesTable, &QTableWidget::cellChanged, [this](int a_row, int a_column) {
auto const xItem = m_ui->seriesTable->item(a_row, 0);
auto const yItem = m_ui->seriesTable->item(a_row, 1);
if (!xItem || !yItem) return;
auto const X = xItem->data(Qt::DisplayRole).toDouble();
auto const Y = yItem->data(Qt::DisplayRole).toDouble();
m_ui->editor->changePoint(a_row, QPointF{ X, Y });
});
connect(m_ui->live, &QCheckBox::stateChanged, [this](int const a_state) { setLive(a_state == 2); });
setLive(false);
}
EditorWindow::~EditorWindow()
{
delete m_ui;
}
void EditorWindow::showEvent(QShowEvent *a_event)
{
// qDebug() << Q_FUNC_INFO;
static bool first{ true };
if (!first) QWidget::showEvent(a_event);
first = true;
m_ui->editor->updatePoints();
}
void EditorWindow::resizeEvent(QResizeEvent *a_event)
{
// qDebug() << Q_FUNC_INFO << a_event;
QWidget::resizeEvent(a_event);
}
void EditorWindow::synchronizeFromNode()
{
auto const editor = m_ui->editor;
auto const node = m_characteristicCurve;
auto const element = static_cast<elements::values::CharacteristicCurve *>(m_characteristicCurve->element());
editor->setXName(node->inputs()[0]->name());
editor->setXMajorTicks(element->xMajorTicks());
editor->setXMinorTicks(element->xMinorTicks());
editor->setXMinimum(static_cast<qreal>(element->xMinimum()));
editor->setXMaximum(static_cast<qreal>(element->xMaximum()));
m_ui->xAxisName->setText(node->inputs()[0]->name());
m_ui->xAxisMajorTicks->setValue(element->xMajorTicks());
m_ui->xAxisMinorTicks->setValue(element->xMinorTicks());
m_ui->xAxisMinimum->setValue(static_cast<qreal>(element->xMinimum()));
m_ui->xAxisMaximum->setValue(static_cast<qreal>(element->xMaximum()));
editor->setYName(node->outputs()[0]->name());
editor->setYMajorTicks(element->yMajorTicks());
editor->setYMinorTicks(element->yMinorTicks());
editor->setYMinimum(static_cast<qreal>(element->yMinimum()));
editor->setYMaximum(static_cast<qreal>(element->yMaximum()));
m_ui->yAxisName->setText(node->outputs()[0]->name());
m_ui->yAxisMajorTicks->setValue(element->yMajorTicks());
m_ui->yAxisMinorTicks->setValue(element->yMinorTicks());
m_ui->yAxisMinimum->setValue(static_cast<qreal>(element->yMinimum()));
m_ui->yAxisMaximum->setValue(static_cast<qreal>(element->yMaximum()));
recreateSeries();
}
void EditorWindow::setValue(qreal const a_value)
{
m_ui->editor->setX(a_value);
}
void EditorWindow::setLive(bool const a_live)
{
m_live = a_live;
m_ui->load->setDisabled(a_live);
m_ui->save->setDisabled(a_live);
}
void EditorWindow::addPoint(int const a_index, QPointF const a_point)
{
auto const seriesTable = m_ui->seriesTable;
seriesTable->insertRow(a_index);
auto const xItem = new QTableWidgetItem;
xItem->setData(Qt::DisplayRole, a_point.x());
seriesTable->setItem(a_index, 0, xItem);
auto const yItem = new QTableWidgetItem;
yItem->setData(Qt::DisplayRole, a_point.y());
seriesTable->setItem(a_index, 1, yItem);
}
void EditorWindow::changePoint(int const a_index, QPointF const a_point)
{
auto const xItem = m_ui->seriesTable->item(a_index, 0);
xItem->setData(Qt::DisplayRole, a_point.x());
auto const yItem = m_ui->seriesTable->item(a_index, 1);
yItem->setData(Qt::DisplayRole, a_point.y());
}
void EditorWindow::removePoint(int const a_index)
{
m_ui->seriesTable->removeRow(a_index);
}
void EditorWindow::recreateSeries()
{
auto const editor = m_ui->editor;
auto const editorSeries = editor->series();
auto const element = static_cast<elements::values::CharacteristicCurve *>(m_characteristicCurve->element());
auto const seriesTable = m_ui->seriesTable;
auto &series = element->series();
editorSeries->clear();
seriesTable->setRowCount(0);
seriesTable->setItemDelegate(new Delegate{ this });
for (auto &point : series) {
editorSeries->append(static_cast<qreal>(point.x), static_cast<qreal>(point.y));
auto const ROW = seriesTable->rowCount();
addPoint(ROW, QPointF{ static_cast<qreal>(point.x), static_cast<qreal>(point.y) });
}
editor->updatePoints();
}
void EditorWindow::setXValueType(ValueType const a_type)
{
m_xValueType = a_type;
}
void EditorWindow::setYValueType(ValueType const a_type)
{
m_yValueType = a_type;
}
} // namespace spaghetti::nodes::values::characteristic_curve
|
// MIT License
//
// Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl
//
// 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 "nodes/values/characteristic_curve/editor_window.h"
#include "elements/values/characteristic_curve.h"
#include "nodes/values/characteristic_curve.h"
#include "nodes/values/characteristic_curve/ui_editor_window.h"
#include <algorithm>
#include <QCheckBox>
#include <QComboBox>
#include <QDebug>
#include <QDoubleValidator>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QIntValidator>
#include <QItemDelegate>
#include <QKeyEvent>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTabWidget>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QtCharts/QLineSeries>
#include "ui/package_view.h"
//#include "nodes/values/characteristic_curve/axis_widget.h"
#include "nodes/values/characteristic_curve/axis.h"
//#include "nodes/values/characteristic_curve/series_widget.h"
#include "nodes/values/characteristic_curve/series.h"
template<class T>
class VPtr {
public:
static T *asPtr(QVariant v) { return reinterpret_cast<T *>(v.value<void *>()); }
static QVariant asQVariant(T *ptr) { return qVariantFromValue(static_cast<void *>(ptr)); }
};
namespace spaghetti::nodes::values::characteristic_curve {
class Delegate : public QItemDelegate {
public:
Delegate(EditorWindow *const a_window)
: QItemDelegate{ a_window }
, m_window{ a_window }
{
}
QWidget *createEditor(QWidget *a_parent, QStyleOptionViewItem const &a_option,
QModelIndex const &a_index) const override
{
(void)a_option;
auto const lineEdit = new QLineEdit{ a_parent };
EditorWindow::ValueType const TYPE{ (a_index.column() == 0 ? m_window->xValueType() : m_window->yValueType()) };
QValidator *validator{};
if (TYPE == EditorWindow::ValueType::eInt)
validator = new QIntValidator;
else
validator = new QDoubleValidator;
QLocale const LOCALE(QLocale::Language::English);
validator->setLocale(LOCALE);
lineEdit->setValidator(validator);
return lineEdit;
}
private:
EditorWindow *const m_window{};
};
EditorWindow::EditorWindow(CharacteristicCurve *const a_characteristicCurve)
: QDialog{ a_characteristicCurve->packageView() }
, m_ui{ new Ui::EditorWindow }
, m_characteristicCurve{ a_characteristicCurve }
{
m_ui->setupUi(this);
m_ui->editor->setEditorWindow(this);
QLocale const LOCALE{ QLocale::Language::English };
m_ui->editor->setLocale(LOCALE);
m_ui->seriesTable->setLocale(LOCALE);
m_ui->xAxisName->setText(m_ui->editor->xName());
m_ui->xAxisMajorTicks->setValue(m_ui->editor->xMajorTicks());
m_ui->xAxisMinorTicks->setValue(m_ui->editor->xMinorTicks());
m_ui->xAxisMinimum->setValue(m_ui->editor->xMinimum());
m_ui->xAxisMaximum->setValue(m_ui->editor->xMaximum());
connect(m_ui->xAxisName, &QLineEdit::textChanged, [this](QString const &a_name) {
m_characteristicCurve->changeInputName(0, a_name);
m_ui->editor->setXName(a_name);
});
connect(m_ui->xAxisMajorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setXMajorTicks(a_value); });
connect(m_ui->xAxisMinorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setXMinorTicks(a_value); });
connect(m_ui->xAxisMinimum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setXMinimum(a_value); });
connect(m_ui->xAxisMaximum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setXMaximum(a_value); });
connect(m_ui->yAxisName, &QLineEdit::textChanged, [this](QString const &a_name) {
m_characteristicCurve->changeOutputName(0, a_name);
m_ui->editor->setYName(a_name);
});
connect(m_ui->yAxisMajorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setYMajorTicks(a_value); });
connect(m_ui->yAxisMinorTicks, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
[this](int a_value) { m_ui->editor->setYMinorTicks(a_value); });
connect(m_ui->yAxisMinimum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setYMinimum(a_value); });
connect(m_ui->yAxisMaximum, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
[this](qreal a_value) { m_ui->editor->setYMaximum(a_value); });
connect(m_ui->seriesTable, &QTableWidget::cellChanged, [this](int a_row, int a_column) {
auto const xItem = m_ui->seriesTable->item(a_row, 0);
auto const yItem = m_ui->seriesTable->item(a_row, 1);
if (!xItem || !yItem) return;
auto const X = xItem->data(Qt::DisplayRole).toDouble();
auto const Y = yItem->data(Qt::DisplayRole).toDouble();
m_ui->editor->changePoint(a_row, QPointF{ X, Y });
});
connect(m_ui->live, &QCheckBox::stateChanged, [this](int const a_state) { setLive(a_state == 2); });
setLive(false);
}
EditorWindow::~EditorWindow()
{
delete m_ui;
}
void EditorWindow::showEvent(QShowEvent *a_event)
{
// qDebug() << Q_FUNC_INFO;
static bool first{ true };
if (!first) QWidget::showEvent(a_event);
first = true;
m_ui->editor->updatePoints();
}
void EditorWindow::resizeEvent(QResizeEvent *a_event)
{
// qDebug() << Q_FUNC_INFO << a_event;
QWidget::resizeEvent(a_event);
}
void EditorWindow::synchronizeFromNode()
{
auto const editor = m_ui->editor;
auto const node = m_characteristicCurve;
auto const element = static_cast<elements::values::CharacteristicCurve *>(m_characteristicCurve->element());
editor->setXName(node->inputs()[0]->name());
editor->setXMajorTicks(element->xMajorTicks());
editor->setXMinorTicks(element->xMinorTicks());
editor->setXMinimum(static_cast<qreal>(element->xMinimum()));
editor->setXMaximum(static_cast<qreal>(element->xMaximum()));
m_ui->xAxisName->setText(node->inputs()[0]->name());
m_ui->xAxisMajorTicks->setValue(element->xMajorTicks());
m_ui->xAxisMinorTicks->setValue(element->xMinorTicks());
m_ui->xAxisMinimum->setValue(static_cast<qreal>(element->xMinimum()));
m_ui->xAxisMaximum->setValue(static_cast<qreal>(element->xMaximum()));
editor->setYName(node->outputs()[0]->name());
editor->setYMajorTicks(element->yMajorTicks());
editor->setYMinorTicks(element->yMinorTicks());
editor->setYMinimum(static_cast<qreal>(element->yMinimum()));
editor->setYMaximum(static_cast<qreal>(element->yMaximum()));
m_ui->yAxisName->setText(node->outputs()[0]->name());
m_ui->yAxisMajorTicks->setValue(element->yMajorTicks());
m_ui->yAxisMinorTicks->setValue(element->yMinorTicks());
m_ui->yAxisMinimum->setValue(static_cast<qreal>(element->yMinimum()));
m_ui->yAxisMaximum->setValue(static_cast<qreal>(element->yMaximum()));
m_xValueType = element->inputs()[0].type == Element::ValueType::eInt ? ValueType::eInt : ValueType::eDouble;
m_yValueType = element->outputs()[0].type == Element::ValueType::eInt ? ValueType::eInt : ValueType::eDouble;
recreateSeries();
}
void EditorWindow::setValue(qreal const a_value)
{
m_ui->editor->setX(a_value);
}
void EditorWindow::setLive(bool const a_live)
{
m_live = a_live;
m_ui->load->setDisabled(a_live);
m_ui->save->setDisabled(a_live);
}
void EditorWindow::addPoint(int const a_index, QPointF const a_point)
{
auto const seriesTable = m_ui->seriesTable;
seriesTable->insertRow(a_index);
auto const xItem = new QTableWidgetItem;
xItem->setData(Qt::DisplayRole, a_point.x());
seriesTable->setItem(a_index, 0, xItem);
auto const yItem = new QTableWidgetItem;
yItem->setData(Qt::DisplayRole, a_point.y());
seriesTable->setItem(a_index, 1, yItem);
}
void EditorWindow::changePoint(int const a_index, QPointF const a_point)
{
auto const xItem = m_ui->seriesTable->item(a_index, 0);
xItem->setData(Qt::DisplayRole, a_point.x());
auto const yItem = m_ui->seriesTable->item(a_index, 1);
yItem->setData(Qt::DisplayRole, a_point.y());
}
void EditorWindow::removePoint(int const a_index)
{
m_ui->seriesTable->removeRow(a_index);
}
void EditorWindow::recreateSeries()
{
auto const editor = m_ui->editor;
auto const editorSeries = editor->series();
auto const element = static_cast<elements::values::CharacteristicCurve *>(m_characteristicCurve->element());
auto const seriesTable = m_ui->seriesTable;
auto &series = element->series();
editorSeries->clear();
seriesTable->setRowCount(0);
seriesTable->setItemDelegate(new Delegate{ this });
for (auto &point : series) {
editorSeries->append(static_cast<qreal>(point.x), static_cast<qreal>(point.y));
auto const ROW = seriesTable->rowCount();
addPoint(ROW, QPointF{ static_cast<qreal>(point.x), static_cast<qreal>(point.y) });
}
editor->updatePoints();
}
void EditorWindow::setXValueType(ValueType const a_type)
{
m_xValueType = a_type;
}
void EditorWindow::setYValueType(ValueType const a_type)
{
m_yValueType = a_type;
}
} // namespace spaghetti::nodes::values::characteristic_curve
|
Set x/y axis value type
|
Set x/y axis value type
|
C++
|
mit
|
aljen/spaghetti,aljen/spaghetti
|
8d3157ea9204021c5e5cfebaf06cd2fa2882a974
|
test/unit/filters/IndexFilterTest.cpp
|
test/unit/filters/IndexFilterTest.cpp
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <boost/test/unit_test.hpp>
#include <pdal/drivers/pipeline/Reader.hpp>
#include <pdal/filters/Index.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Schema.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/Options.hpp>
#include "Support.hpp"
using namespace pdal;
BOOST_AUTO_TEST_SUITE(IndexFilterTest)
BOOST_AUTO_TEST_CASE(test_3d)
{
pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
pdal::Options options(option);
pdal::drivers::pipeline::Reader reader(options);
reader.initialize();
pdal::filters::Index const* filter = static_cast<pdal::filters::Index const*>(reader.getManager().getStage());
pdal::Options opt = filter->getOptions();
// std::cout << "filter ops: " << opt << std::endl;
const pdal::Schema& schema = filter->getSchema();
pdal::PointBuffer data(schema, 20);
pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
boost::uint32_t numRead = it->read(data);
BOOST_CHECK(numRead == 20);
#ifdef PDAL_HAVE_FLANN
pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
unsigned k = 8;
// If the query distance is 0, just return the k nearest neighbors
std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
BOOST_CHECK_EQUAL(ids.size(), k);
BOOST_CHECK_EQUAL(ids[0], 8u);
BOOST_CHECK_EQUAL(ids[4], 10u);
std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
BOOST_CHECK_EQUAL(dist_ids[0], 8u);
#endif
delete it;
return;
}
BOOST_AUTO_TEST_CASE(test_2d)
{
pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
pdal::Options options(option);
pdal::drivers::pipeline::Reader reader(options);
reader.initialize();
pdal::filters::Index* filter = static_cast<pdal::filters::Index*>(reader.getManager().getStage());
filter->setDimensions(2);
// std::cout << "filter ops: " << opt << std::endl;
const pdal::Schema& schema = filter->getSchema();
pdal::PointBuffer data(schema, 20);
pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
boost::uint32_t numRead = it->read(data);
BOOST_CHECK(numRead == 20);
#ifdef PDAL_HAVE_FLANN
pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
unsigned k = 8;
// If the query distance is 0, just return the k nearest neighbors
std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 0.0, 0.0, k);
BOOST_CHECK_EQUAL(ids.size(), k);
BOOST_CHECK_EQUAL(ids[0], 8u);
BOOST_CHECK_EQUAL(ids[4], 10u);
std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 0.0, 100.0, k);
BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
BOOST_CHECK_EQUAL(dist_ids[0], 8u);
#endif
delete it;
return;
}
BOOST_AUTO_TEST_SUITE_END()
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <boost/test/unit_test.hpp>
#include <pdal/drivers/pipeline/Reader.hpp>
#include <pdal/filters/Index.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Schema.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/Options.hpp>
#include "Support.hpp"
using namespace pdal;
BOOST_AUTO_TEST_SUITE(IndexFilterTest)
BOOST_AUTO_TEST_CASE(test_3d)
{
pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
pdal::Options options(option);
pdal::drivers::pipeline::Reader reader(options);
reader.initialize();
pdal::filters::Index const* filter = static_cast<pdal::filters::Index const*>(reader.getManager().getStage());
pdal::Options opt = filter->getOptions();
// std::cout << "filter ops: " << opt << std::endl;
const pdal::Schema& schema = filter->getSchema();
pdal::PointBuffer data(schema, 20);
pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
boost::uint32_t numRead = it->read(data);
BOOST_CHECK(numRead == 20);
#ifdef PDAL_HAVE_FLANN
pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
unsigned k = 8;
// If the query distance is 0, just return the k nearest neighbors
std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
BOOST_CHECK_EQUAL(ids.size(), k);
BOOST_CHECK_EQUAL(ids[0], 8u);
BOOST_CHECK_EQUAL(ids[4], 10u);
std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
BOOST_CHECK_EQUAL(dist_ids[0], 8u);
#endif
delete it;
return;
}
BOOST_AUTO_TEST_CASE(test_2d)
{
pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
pdal::Options options(option);
pdal::drivers::pipeline::Reader reader(options);
reader.initialize();
pdal::filters::Index* filter = static_cast<pdal::filters::Index*>(reader.getManager().getStage());
filter->setNumDimensions(2);
// std::cout << "filter ops: " << opt << std::endl;
const pdal::Schema& schema = filter->getSchema();
pdal::PointBuffer data(schema, 20);
pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
boost::uint32_t numRead = it->read(data);
BOOST_CHECK(numRead == 20);
#ifdef PDAL_HAVE_FLANN
pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
unsigned k = 8;
// If the query distance is 0, just return the k nearest neighbors
std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 0.0, 0.0, k);
BOOST_CHECK_EQUAL(ids.size(), k);
BOOST_CHECK_EQUAL(ids[0], 8u);
BOOST_CHECK_EQUAL(ids[4], 10u);
std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 0.0, 100.0, k);
BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
BOOST_CHECK_EQUAL(dist_ids[0], 8u);
#endif
delete it;
return;
}
BOOST_AUTO_TEST_SUITE_END()
|
fix up test
|
fix up test
|
C++
|
bsd-3-clause
|
verma/PDAL,boundlessgeo/PDAL,jwomeara/PDAL,radiantbluetechnologies/PDAL,mtCarto/PDAL,mpgerlek/PDAL-old,lucadelu/PDAL,Sciumo/PDAL,lucadelu/PDAL,mtCarto/PDAL,Sciumo/PDAL,Sciumo/PDAL,mtCarto/PDAL,mtCarto/PDAL,lucadelu/PDAL,Sciumo/PDAL,boundlessgeo/PDAL,jwomeara/PDAL,DougFirErickson/PDAL,boundlessgeo/PDAL,radiantbluetechnologies/PDAL,radiantbluetechnologies/PDAL,lucadelu/PDAL,verma/PDAL,mpgerlek/PDAL-old,DougFirErickson/PDAL,jwomeara/PDAL,verma/PDAL,verma/PDAL,verma/PDAL,verma/PDAL,DougFirErickson/PDAL,DougFirErickson/PDAL,verma/PDAL,jwomeara/PDAL,radiantbluetechnologies/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,mpgerlek/PDAL-old
|
2590e7d8ca52d8e229df9f51751aebb64566c869
|
PWG2/PROOF-INF.PWG2kink/SETUP.C
|
PWG2/PROOF-INF.PWG2kink/SETUP.C
|
void SETUP() {
CheckLoadLibrary("libPWG2evchar");
// Set the include paths
gROOT->ProcessLine(".include PWG2evchar/EVCHAR");
// Set our location, so that other packages can find us
gSystem->Setenv("PWG2evchar_INCLUDE", "PWG2evchar");
}
Int_t CheckLoadLibrary(const char* library) {
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
|
void SETUP() {
CheckLoadLibrary("libPWG2evchar");
// Set the include paths
gROOT->ProcessLine(".include PWG2evchar/EVCHAR");
// Set our location, so that other packages can find us
gSystem->Setenv("PWG2evchar_INCLUDE", "PWG2evchar/EVCHAR");
}
Int_t CheckLoadLibrary(const char* library) {
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
|
Fix include path
|
Fix include path
|
C++
|
bsd-3-clause
|
fbellini/AliPhysics,jmargutt/AliPhysics,victor-gonzalez/AliPhysics,btrzecia/AliPhysics,kreisl/AliPhysics,hcab14/AliPhysics,rderradi/AliPhysics,mkrzewic/AliPhysics,mpuccio/AliPhysics,AMechler/AliPhysics,mbjadhav/AliPhysics,fcolamar/AliPhysics,jgronefe/AliPhysics,jgronefe/AliPhysics,dlodato/AliPhysics,jgronefe/AliPhysics,jmargutt/AliPhysics,nschmidtALICE/AliPhysics,hcab14/AliPhysics,kreisl/AliPhysics,victor-gonzalez/AliPhysics,hzanoli/AliPhysics,pchrista/AliPhysics,pbatzing/AliPhysics,dmuhlhei/AliPhysics,pbatzing/AliPhysics,kreisl/AliPhysics,lcunquei/AliPhysics,jgronefe/AliPhysics,mbjadhav/AliPhysics,dstocco/AliPhysics,mazimm/AliPhysics,kreisl/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,aaniin/AliPhysics,fbellini/AliPhysics,carstooon/AliPhysics,aaniin/AliPhysics,ALICEHLT/AliPhysics,btrzecia/AliPhysics,jmargutt/AliPhysics,mbjadhav/AliPhysics,pbatzing/AliPhysics,AudreyFrancisco/AliPhysics,ppribeli/AliPhysics,mazimm/AliPhysics,fbellini/AliPhysics,amatyja/AliPhysics,fbellini/AliPhysics,fbellini/AliPhysics,sebaleh/AliPhysics,ALICEHLT/AliPhysics,preghenella/AliPhysics,pbuehler/AliPhysics,rbailhac/AliPhysics,btrzecia/AliPhysics,alisw/AliPhysics,rderradi/AliPhysics,ALICEHLT/AliPhysics,lcunquei/AliPhysics,yowatana/AliPhysics,ALICEHLT/AliPhysics,pchrista/AliPhysics,rbailhac/AliPhysics,btrzecia/AliPhysics,aaniin/AliPhysics,dlodato/AliPhysics,rderradi/AliPhysics,preghenella/AliPhysics,amatyja/AliPhysics,yowatana/AliPhysics,dlodato/AliPhysics,btrzecia/AliPhysics,pbatzing/AliPhysics,victor-gonzalez/AliPhysics,rbailhac/AliPhysics,SHornung1/AliPhysics,mkrzewic/AliPhysics,lfeldkam/AliPhysics,SHornung1/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,carstooon/AliPhysics,hzanoli/AliPhysics,amatyja/AliPhysics,mazimm/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,AudreyFrancisco/AliPhysics,AudreyFrancisco/AliPhysics,rderradi/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,lcunquei/AliPhysics,adriansev/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,dlodato/AliPhysics,victor-gonzalez/AliPhysics,hzanoli/AliPhysics,kreisl/AliPhysics,yowatana/AliPhysics,hcab14/AliPhysics,mkrzewic/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,alisw/AliPhysics,dmuhlhei/AliPhysics,jmargutt/AliPhysics,akubera/AliPhysics,akubera/AliPhysics,adriansev/AliPhysics,sebaleh/AliPhysics,rderradi/AliPhysics,nschmidtALICE/AliPhysics,mkrzewic/AliPhysics,lcunquei/AliPhysics,aaniin/AliPhysics,ppribeli/AliPhysics,dmuhlhei/AliPhysics,jmargutt/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,pbatzing/AliPhysics,AudreyFrancisco/AliPhysics,mvala/AliPhysics,preghenella/AliPhysics,hzanoli/AliPhysics,jgronefe/AliPhysics,akubera/AliPhysics,mpuccio/AliPhysics,mkrzewic/AliPhysics,ppribeli/AliPhysics,mvala/AliPhysics,mpuccio/AliPhysics,amatyja/AliPhysics,pbuehler/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,lfeldkam/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,mazimm/AliPhysics,amaringarcia/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,pbuehler/AliPhysics,pchrista/AliPhysics,aaniin/AliPhysics,SHornung1/AliPhysics,lcunquei/AliPhysics,dmuhlhei/AliPhysics,fcolamar/AliPhysics,hzanoli/AliPhysics,lcunquei/AliPhysics,lfeldkam/AliPhysics,akubera/AliPhysics,dstocco/AliPhysics,preghenella/AliPhysics,pchrista/AliPhysics,carstooon/AliPhysics,hcab14/AliPhysics,adriansev/AliPhysics,ALICEHLT/AliPhysics,hzanoli/AliPhysics,ppribeli/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,mvala/AliPhysics,mvala/AliPhysics,btrzecia/AliPhysics,mpuccio/AliPhysics,dlodato/AliPhysics,amatyja/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,yowatana/AliPhysics,rbailhac/AliPhysics,mvala/AliPhysics,dstocco/AliPhysics,sebaleh/AliPhysics,mvala/AliPhysics,yowatana/AliPhysics,alisw/AliPhysics,yowatana/AliPhysics,pbatzing/AliPhysics,yowatana/AliPhysics,rihanphys/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,SHornung1/AliPhysics,mvala/AliPhysics,aaniin/AliPhysics,nschmidtALICE/AliPhysics,carstooon/AliPhysics,sebaleh/AliPhysics,AudreyFrancisco/AliPhysics,ppribeli/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,lfeldkam/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,dstocco/AliPhysics,fcolamar/AliPhysics,jmargutt/AliPhysics,mazimm/AliPhysics,victor-gonzalez/AliPhysics,hcab14/AliPhysics,ALICEHLT/AliPhysics,adriansev/AliPhysics,hcab14/AliPhysics,akubera/AliPhysics,fcolamar/AliPhysics,AudreyFrancisco/AliPhysics,fbellini/AliPhysics,rderradi/AliPhysics,dmuhlhei/AliPhysics,jgronefe/AliPhysics,AMechler/AliPhysics,mbjadhav/AliPhysics,pchrista/AliPhysics,amatyja/AliPhysics,dstocco/AliPhysics,mazimm/AliPhysics,alisw/AliPhysics,hzanoli/AliPhysics,ppribeli/AliPhysics,dlodato/AliPhysics,amatyja/AliPhysics,carstooon/AliPhysics,fcolamar/AliPhysics,rbailhac/AliPhysics,dlodato/AliPhysics,hcab14/AliPhysics,mkrzewic/AliPhysics,AMechler/AliPhysics,sebaleh/AliPhysics,mpuccio/AliPhysics,rihanphys/AliPhysics,lfeldkam/AliPhysics,akubera/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,dstocco/AliPhysics,lfeldkam/AliPhysics,btrzecia/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,mkrzewic/AliPhysics,lfeldkam/AliPhysics,amaringarcia/AliPhysics,lcunquei/AliPhysics,dstocco/AliPhysics,sebaleh/AliPhysics,kreisl/AliPhysics,ppribeli/AliPhysics,adriansev/AliPhysics,rderradi/AliPhysics,mbjadhav/AliPhysics,mazimm/AliPhysics,pbatzing/AliPhysics,jmargutt/AliPhysics,carstooon/AliPhysics,aaniin/AliPhysics,kreisl/AliPhysics,dmuhlhei/AliPhysics,ALICEHLT/AliPhysics,mpuccio/AliPhysics,akubera/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,pbuehler/AliPhysics,jgronefe/AliPhysics,AMechler/AliPhysics,SHornung1/AliPhysics,mbjadhav/AliPhysics,nschmidtALICE/AliPhysics
|
8e1291d8150d4af656c374df11723fa6f34231b1
|
ParseHelper.BlockParseState.cpp
|
ParseHelper.BlockParseState.cpp
|
/**
Copyright (c) 2014 Alex Tsui
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 "ParseHelper.h"
ParseHelper::BlockParseState::
BlockParseState( ParseHelper& parent ):
ParseState( parent )
{ }
ParseHelper::BlockParseState::
BlockParseState( ParseHelper& parent, const std::string& indent_ ):
ParseState( parent ),
indent( indent_ )
{ }
bool ParseHelper::BlockParseState::
process(const std::string& str)
{
bool ok = initializeIndent(str);
if ( ! ok )
{
// finish processing
return true;
}
Indent ind;
bool isIndented = PeekIndent( str, &ind );
if ( isIndented )
{
#ifndef NDEBUG
std::cout << "current line indent: ";
print( ind );
#endif
// check if indent matches
if ( ind.Token != indent.Token )
{
// dedent until we match or empty the stack
bool found = false;
while ( !found )
{
parent.stateStack.pop_back( );
if ( !parent.stateStack.size( ) )
break;
boost::shared_ptr<BlockParseState> parseState =
boost::dynamic_pointer_cast<BlockParseState>(
parent.stateStack.back( ));
found = ( ind.Token == parseState->indent.Token );
}
if ( ! found )
{
#ifndef NDEBUG
std::cout << "indent mismatch\n";
#endif
parent.reset( );
ParseMessage msg( 1, "IndentationError: unexpected indent");
parent.broadcast( msg );
return true;
}
}
// process command
// enter indented block state
if ( str[str.size()-1] == ':' )
{
parent.commandBuffer.push_back( str );
//parent.inBlock = (boost::dynamic_pointer_cast<BlockParseState>(
// parent.stateStack.back()));
//expectingIndent = true;
boost::shared_ptr<ParseState> parseState(
new BlockParseState( parent ) );
parent.stateStack.push_back( parseState );
return true;
}
if ( str[str.size()-1] == '\\' )
{
parent.commandBuffer.push_back( str );
boost::shared_ptr<ParseState> parseState(
new ContinuationParseState( parent ) );
parent.stateStack.push_back( parseState );
return true;
}
if (BracketParseState::HasOpenBrackets( str ))
{
// FIXME: Every parse state should have its own local buffer
boost::shared_ptr<ParseState> parseState(
new BracketParseState( parent, str ) );
parent.stateStack.push_back( parseState );
return true;
}
parent.commandBuffer.push_back( str );
return true;
}
else
{
#ifndef NDEBUG
std::cout << "Leaving block\n";
#endif
parent.flush( );
parent.reset( );
return true;
}
}
bool ParseHelper::BlockParseState::
initializeIndent(const std::string& str)
{
bool expectingIndent = (indent.Token == "");
if ( !expectingIndent )
{
std::cout << "already initialized indent: ";
print( indent );
return true;
}
Indent ind;
bool isIndented = parent.PeekIndent( str, &ind );
if ( !isIndented )
{
#ifndef NDEBUG
std::cout << "Expected indented block\n";
#endif
parent.reset( );
ParseMessage msg( 1, "IndentationError: expected an indented block" );
parent.broadcast( msg );
return false;
}
indent = ind;
//parent.currentIndent = ind;
//parent.indentStack.push_back( parent.currentIndent );
//parent.expectingIndent = false;
#ifndef NDEBUG
std::cout << "initializing indent: ";
print( ind );
#endif
return true;
}
|
/**
Copyright (c) 2014 Alex Tsui
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 "ParseHelper.h"
ParseHelper::BlockParseState::
BlockParseState( ParseHelper& parent ):
ParseState( parent )
{ }
ParseHelper::BlockParseState::
BlockParseState( ParseHelper& parent, const std::string& indent_ ):
ParseState( parent ),
indent( indent_ )
{ }
bool ParseHelper::BlockParseState::
process(const std::string& str)
{
bool ok = initializeIndent(str);
if ( ! ok )
{
// finish processing
return true;
}
Indent ind;
bool isIndented = PeekIndent( str, &ind );
if ( isIndented )
{
#ifndef NDEBUG
std::cout << "current line indent: ";
print( ind );
#endif
// check if indent matches
if ( ind.Token != indent.Token )
{
// dedent until we match or empty the stack
bool found = false;
while ( !found )
{
parent.stateStack.pop_back( );
if ( !parent.stateStack.size( ) )
break;
boost::shared_ptr<BlockParseState> parseState =
boost::dynamic_pointer_cast<BlockParseState>(
parent.stateStack.back( ));
found = ( ind.Token == parseState->indent.Token );
}
if ( ! found )
{
#ifndef NDEBUG
std::cout << "indent mismatch\n";
#endif
parent.reset( );
ParseMessage msg( 1, "IndentationError: unexpected indent");
parent.broadcast( msg );
return true;
}
}
// process command
// enter indented block state
if ( str[str.size()-1] == ':' )
{
parent.commandBuffer.push_back( str );
//parent.inBlock = (boost::dynamic_pointer_cast<BlockParseState>(
// parent.stateStack.back()));
//expectingIndent = true;
boost::shared_ptr<ParseState> parseState(
new BlockParseState( parent ) );
parent.stateStack.push_back( parseState );
return true;
}
if ( str[str.size()-1] == '\\' )
{
parent.commandBuffer.push_back( str );
boost::shared_ptr<ParseState> parseState(
new ContinuationParseState( parent ) );
parent.stateStack.push_back( parseState );
return true;
}
if (BracketParseState::HasOpenBrackets( str ))
{
// FIXME: Every parse state should have its own local buffer
boost::shared_ptr<ParseState> parseState(
new BracketParseState( parent, str ) );
parent.stateStack.push_back( parseState );
return true;
}
parent.commandBuffer.push_back( str );
return true;
}
else
{
if ( str.size() )
{
{
#ifndef NDEBUG
std::cout << "Expected indented block\n";
#endif
parent.reset( );
ParseMessage msg( 1, "IndentationError: expected an indented block" );
parent.broadcast( msg );
return false;
}
}
#ifndef NDEBUG
std::cout << "Leaving block\n";
#endif
parent.stateStack.pop_back();
parent.flush( );
parent.reset( );
return true;
}
}
bool ParseHelper::BlockParseState::
initializeIndent(const std::string& str)
{
bool expectingIndent = (indent.Token == "");
if ( !expectingIndent )
{
std::cout << "already initialized indent: ";
print( indent );
return true;
}
Indent ind;
bool isIndented = parent.PeekIndent( str, &ind );
if ( !isIndented )
{
#ifndef NDEBUG
std::cout << "Expected indented block\n";
#endif
parent.reset( );
ParseMessage msg( 1, "IndentationError: expected an indented block" );
parent.broadcast( msg );
return false;
}
indent = ind;
//parent.currentIndent = ind;
//parent.indentStack.push_back( parent.currentIndent );
//parent.expectingIndent = false;
#ifndef NDEBUG
std::cout << "initializing indent: ";
print( ind );
#endif
return true;
}
|
Correct edge case where last block is closed.
|
Correct edge case where last block is closed.
|
C++
|
mit
|
alextsui05/python-console,alextsui05/python-console
|
4fd072ebdf1eab565c189a5247f99ae3dada4b7f
|
moveit_ros/manipulation/pick_place/src/reachable_valid_pose_filter.cpp
|
moveit_ros/manipulation/pick_place/src/reachable_valid_pose_filter.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/pick_place/reachable_valid_pose_filter.h>
#include <moveit/kinematic_constraints/utils.h>
#include <eigen_conversions/eigen_msg.h>
#include <boost/bind.hpp>
#include <ros/console.h>
namespace pick_place
{
ReachableAndValidPoseFilter::ReachableAndValidPoseFilter(const planning_scene::PlanningSceneConstPtr &scene,
const collision_detection::AllowedCollisionMatrixConstPtr &collision_matrix,
const constraint_samplers::ConstraintSamplerManagerPtr &constraints_sampler_manager) :
ManipulationStage("reachable & valid pose filter"),
planning_scene_(scene),
collision_matrix_(collision_matrix),
constraints_sampler_manager_(constraints_sampler_manager)
{
}
bool ReachableAndValidPoseFilter::isStateCollisionFree(const ManipulationPlan *manipulation_plan,
robot_state::JointStateGroup *joint_state_group,
const std::vector<double> &joint_group_variable_values) const
{
joint_state_group->setVariableValues(joint_group_variable_values);
// apply approach posture for the end effector (we always apply it here since it could be the case the sampler changes this posture)
joint_state_group->getRobotState()->setStateValues(manipulation_plan->approach_posture_);
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
req.group_name = manipulation_plan->shared_data_->planning_group_;
planning_scene_->checkCollision(req, res, *joint_state_group->getRobotState(), *collision_matrix_);
if (res.collision == false)
return planning_scene_->isStateFeasible(*joint_state_group->getRobotState());
else
return false;
}
bool ReachableAndValidPoseFilter::isEndEffectorFree(const ManipulationPlanPtr &plan, robot_state::RobotState &token_state) const
{
tf::poseMsgToEigen(plan->goal_pose_.pose, plan->transformed_goal_pose_);
plan->transformed_goal_pose_ = planning_scene_->getFrameTransform(token_state, plan->goal_pose_.header.frame_id) * plan->transformed_goal_pose_;
token_state.updateStateWithLinkAt(plan->shared_data_->ik_link_name_, plan->transformed_goal_pose_);
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
req.group_name = plan->shared_data_->end_effector_group_;
planning_scene_->checkCollision(req, res, token_state, *collision_matrix_);
return res.collision == false;
}
bool ReachableAndValidPoseFilter::evaluate(const ManipulationPlanPtr &plan) const
{
// initialize with scene state
robot_state::RobotStatePtr token_state(new robot_state::RobotState(planning_scene_->getCurrentState()));
if (isEndEffectorFree(plan, *token_state))
{
// update the goal pose message if anything has changed; this is because the name of the frame in the input goal pose
// can be that of objects in the collision world but most components are unaware of those transforms,
// so we convert to a frame that is certainly known
if (planning_scene_->getPlanningFrame() != plan->goal_pose_.header.frame_id)
{
tf::poseEigenToMsg(plan->transformed_goal_pose_, plan->goal_pose_.pose);
plan->goal_pose_.header.frame_id = planning_scene_->getPlanningFrame();
}
// convert the pose we want to reach to a set of constraints
plan->goal_constraints_ = kinematic_constraints::constructGoalConstraints(plan->shared_data_->ik_link_name_, plan->goal_pose_);
const std::string &planning_group = plan->shared_data_->planning_group_;
// construct a sampler for the specified constraints; this can end up calling just IK, but it is more general
// and allows for robot-specific samplers, producing samples that also change the base position if needed, etc
plan->goal_sampler_ = constraints_sampler_manager_->selectSampler(planning_scene_, planning_group, plan->goal_constraints_);
if (plan->goal_sampler_)
{
plan->goal_sampler_->setStateValidityCallback(boost::bind(&ReachableAndValidPoseFilter::isStateCollisionFree, this, plan.get(), _1, _2));
if (plan->goal_sampler_->sample(token_state->getJointStateGroup(planning_group), *token_state, plan->shared_data_->max_goal_sampling_attempts_))
{
plan->possible_goal_states_.push_back(token_state);
return true;
}
}
else
ROS_ERROR_THROTTLE(1, "No sampler was constructed");
}
plan->error_code_.val = moveit_msgs::MoveItErrorCodes::GOAL_IN_COLLISION;
return false;
}
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/pick_place/reachable_valid_pose_filter.h>
#include <moveit/kinematic_constraints/utils.h>
#include <eigen_conversions/eigen_msg.h>
#include <boost/bind.hpp>
#include <ros/console.h>
namespace pick_place
{
ReachableAndValidPoseFilter::ReachableAndValidPoseFilter(const planning_scene::PlanningSceneConstPtr &scene,
const collision_detection::AllowedCollisionMatrixConstPtr &collision_matrix,
const constraint_samplers::ConstraintSamplerManagerPtr &constraints_sampler_manager) :
ManipulationStage("reachable & valid pose filter"),
planning_scene_(scene),
collision_matrix_(collision_matrix),
constraints_sampler_manager_(constraints_sampler_manager)
{
}
bool ReachableAndValidPoseFilter::isStateCollisionFree(const ManipulationPlan *manipulation_plan,
robot_state::JointStateGroup *joint_state_group,
const std::vector<double> &joint_group_variable_values) const
{
joint_state_group->setVariableValues(joint_group_variable_values);
// apply approach posture for the end effector (we always apply it here since it could be the case the sampler changes this posture)
joint_state_group->getRobotState()->setStateValues(manipulation_plan->approach_posture_);
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
req.group_name = manipulation_plan->shared_data_->planning_group_;
planning_scene_->checkCollision(req, res, *joint_state_group->getRobotState(), *collision_matrix_);
if (res.collision == false)
return planning_scene_->isStateFeasible(*joint_state_group->getRobotState());
else
return false;
}
bool ReachableAndValidPoseFilter::isEndEffectorFree(const ManipulationPlanPtr &plan, robot_state::RobotState &token_state) const
{
tf::poseMsgToEigen(plan->goal_pose_.pose, plan->transformed_goal_pose_);
plan->transformed_goal_pose_ = planning_scene_->getFrameTransform(token_state, plan->goal_pose_.header.frame_id) * plan->transformed_goal_pose_;
token_state.updateStateWithLinkAt(plan->shared_data_->ik_link_name_, plan->transformed_goal_pose_);
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
req.group_name = plan->shared_data_->end_effector_group_;
planning_scene_->checkCollision(req, res, token_state, *collision_matrix_);
return res.collision == false;
}
namespace
{
bool sameFrames(const std::string& frame1, const std::string& frame2)
{
// Remove preceeding '/' from frame names, eg /base_link
if (!frame1.empty() && frame1[0] == '/')
return sameFrames(frame1.substr(1), frame2);
if (!frame2.empty() && frame2[0] == '/')
return sameFrames(frame1, frame2.substr(1));
return frame1 == frame2;
}
}
bool ReachableAndValidPoseFilter::evaluate(const ManipulationPlanPtr &plan) const
{
// initialize with scene state
robot_state::RobotStatePtr token_state(new robot_state::RobotState(planning_scene_->getCurrentState()));
if (isEndEffectorFree(plan, *token_state))
{
// update the goal pose message if anything has changed; this is because the name of the frame in the input goal pose
// can be that of objects in the collision world but most components are unaware of those transforms,
// so we convert to a frame that is certainly known
if (sameFrames(planning_scene_->getPlanningFrame(), plan->goal_pose_.header.frame_id))
{
tf::poseEigenToMsg(plan->transformed_goal_pose_, plan->goal_pose_.pose);
plan->goal_pose_.header.frame_id = planning_scene_->getPlanningFrame();
}
// convert the pose we want to reach to a set of constraints
plan->goal_constraints_ = kinematic_constraints::constructGoalConstraints(plan->shared_data_->ik_link_name_, plan->goal_pose_);
const std::string &planning_group = plan->shared_data_->planning_group_;
// construct a sampler for the specified constraints; this can end up calling just IK, but it is more general
// and allows for robot-specific samplers, producing samples that also change the base position if needed, etc
plan->goal_sampler_ = constraints_sampler_manager_->selectSampler(planning_scene_, planning_group, plan->goal_constraints_);
if (plan->goal_sampler_)
{
plan->goal_sampler_->setStateValidityCallback(boost::bind(&ReachableAndValidPoseFilter::isStateCollisionFree, this, plan.get(), _1, _2));
if (plan->goal_sampler_->sample(token_state->getJointStateGroup(planning_group), *token_state, plan->shared_data_->max_goal_sampling_attempts_))
{
plan->possible_goal_states_.push_back(token_state);
return true;
}
}
else
ROS_ERROR_THROTTLE(1, "No sampler was constructed");
}
plan->error_code_.val = moveit_msgs::MoveItErrorCodes::GOAL_IN_COLLISION;
return false;
}
}
|
check for frame equality in a more robust fashion
|
check for frame equality in a more robust fashion
|
C++
|
bsd-3-clause
|
v4hn/moveit,ros-planning/moveit,davetcoleman/moveit,davetcoleman/moveit,ros-planning/moveit,davetcoleman/moveit,v4hn/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit,v4hn/moveit,ros-planning/moveit,v4hn/moveit
|
62ecf54aaa2bde21d9c82173fcb257d76d3a09b0
|
cpp/ql/src/experimental/Security/CWE/CWE-476/DangerousUseOfExceptionBlocks.cpp
|
cpp/ql/src/experimental/Security/CWE/CWE-476/DangerousUseOfExceptionBlocks.cpp
|
...
try {
if (checkValue) throw exception();
valData->bufMyData = new myData*[valData->sizeInt];
}
catch (...)
{
for (size_t i = 0; i < valData->sizeInt; i++)
{
delete[] valData->bufMyData[i]->buffer; // BAD
delete valData->bufMyData[i];
}
...
try {
if (checkValue) throw exception();
valData->bufMyData = new myData*[valData->sizeInt];
}
catch (...)
{
for (size_t i = 0; i < valData->sizeInt; i++)
{
if(delete valData->bufMyData[i])
{
delete[] valData->bufMyData[i]->buffer; // GOOD
delete valData->bufMyData[i];
}
}
...
catch (const exception &) {
delete valData;
throw;
}
catch (...)
{
delete valData; // BAD
...
catch (const exception &) {
delete valData;
valData = NULL;
throw;
}
catch (...)
{
delete valData; // GOOD
...
|
...
try {
if (checkValue) throw exception();
valData->bufMyData = new myData*[valData->sizeInt];
}
catch (...)
{
for (size_t i = 0; i < valData->sizeInt; i++)
{
delete[] valData->bufMyData[i]->buffer; // BAD
delete valData->bufMyData[i];
}
...
try {
if (checkValue) throw exception();
valData->bufMyData = new myData*[valData->sizeInt];
}
catch (...)
{
for (size_t i = 0; i < valData->sizeInt; i++)
{
if(valData->bufMyData[i])
{
delete[] valData->bufMyData[i]->buffer; // GOOD
delete valData->bufMyData[i];
}
}
...
catch (const exception &) {
delete valData;
throw;
}
catch (...)
{
delete valData; // BAD
...
catch (const exception &) {
delete valData;
valData = NULL;
throw;
}
catch (...)
{
delete valData; // GOOD
...
|
Update DangerousUseOfExceptionBlocks.cpp
|
Update DangerousUseOfExceptionBlocks.cpp
|
C++
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
b5c74d47c84dada12ac690c78d9bb127aa463db8
|
engine/byte_array.cpp
|
engine/byte_array.cpp
|
// The MIT License(MIT)
//
// Copyright 2017 Huldra
//
// 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.
//t800
//
// Copyright 2017 Bogdan Kozyrev [email protected]
// Desert Engine project
//
#if defined(LINUX)
#include <cstring>
#endif
// Примечание: контрибут от Андрея Коновода и Владимира Победина от 4.07.2017
//
//t800
#include "engine/byte_array.h"
#include <memory>
#include "engine/arctic_platform.h"
namespace arctic {
ByteArray::ByteArray() {
allocated_size_ = 128;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::ByteArray(Ui64 size) {
allocated_size_ = size;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::~ByteArray() {
allocated_size_ = 0;
size_ = 0;
free(data_);
data_ = nullptr;
}
void* ByteArray::GetVoidData() const {
return static_cast<void*>(data_);
}
Ui8* ByteArray::data() const {
return data_;
}
Ui64 ByteArray::size() const {
return size_;
}
void ByteArray::Resize(Ui64 size) {
if (size <= allocated_size_) {
size_ = size;
} else {
Ui8 *data = static_cast<Ui8*>(malloc(static_cast<size_t>(size)));
Check(data != nullptr, "Allocaton error.");
memcpy(data, data_, static_cast<size_t>(size_));
free(data_);
allocated_size_ = size;
size_ = size;
data_ = data;
}
}
void ByteArray::Reserve(Ui64 size) {
if (size > size_) {
Ui64 oldSize = size_;
Resize(size);
Resize(oldSize);
}
}
} // namespace arctic
|
// The MIT License(MIT)
//
// Copyright 2017 Huldra
//
// 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.
//t800
//
// Copyright 2017 Bogdan Kozyrev [email protected]
// Desert Engine project
//
#if defined(LINUX)
#include <cstring>
#endif
// Примечание: контрибут от Андрея Коновода от 4.07.2017
//
//t800
#include "engine/byte_array.h"
#include <memory>
#include "engine/arctic_platform.h"
namespace arctic {
ByteArray::ByteArray() {
allocated_size_ = 128;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::ByteArray(Ui64 size) {
allocated_size_ = size;
size_ = 0;
data_ = static_cast<Ui8*>(malloc(static_cast<size_t>(allocated_size_)));
}
ByteArray::~ByteArray() {
allocated_size_ = 0;
size_ = 0;
free(data_);
data_ = nullptr;
}
void* ByteArray::GetVoidData() const {
return static_cast<void*>(data_);
}
Ui8* ByteArray::data() const {
return data_;
}
Ui64 ByteArray::size() const {
return size_;
}
void ByteArray::Resize(Ui64 size) {
if (size <= allocated_size_) {
size_ = size;
} else {
Ui8 *data = static_cast<Ui8*>(malloc(static_cast<size_t>(size)));
Check(data != nullptr, "Allocaton error.");
memcpy(data, data_, static_cast<size_t>(size_));
free(data_);
allocated_size_ = size;
size_ = size;
data_ = data;
}
}
void ByteArray::Reserve(Ui64 size) {
if (size > size_) {
Ui64 oldSize = size_;
Resize(size);
Resize(oldSize);
}
}
} // namespace arctic
|
Update byte_array.cpp
|
Update byte_array.cpp
|
C++
|
mit
|
t800danya/desert-engine,t800danya/desert-engine,t800danya/desert-engine,t800danya/desert-engine
|
7540cacfbf00155b0c3cde9c4019e8fff08f5012
|
tests/CppUTestExt/OrderedTestTest.cpp
|
tests/CppUTestExt/OrderedTestTest.cpp
|
/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTestExt/OrderedTest.h"
TEST_GROUP(TestOrderedTest)
{
TestTestingFixture* fixture;
OrderedTestShell orderedTest;
OrderedTestShell orderedTest2;
OrderedTestShell orderedTest3;
ExecFunctionTestShell normalTest;
ExecFunctionTestShell normalTest2;
ExecFunctionTestShell normalTest3;
OrderedTestShell* orderedTestCache;
void setup()
{
orderedTestCache = OrderedTestShell::getOrderedTestHead();
OrderedTestShell::setOrderedTestHead(0);
fixture = new TestTestingFixture();
fixture->registry_->unDoLastAddTest();
}
void teardown()
{
delete fixture;
OrderedTestShell::setOrderedTestHead(orderedTestCache);
}
void InstallOrderedTest(OrderedTestShell& test, int level)
{
OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level);
}
void InstallNormalTest(UtestShell& test)
{
TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__);
}
UtestShell* firstTest()
{
return fixture->registry_->getFirstTest();
}
UtestShell* secondTest()
{
return fixture->registry_->getFirstTest()->getNext();
}
};
TEST(TestOrderedTest, TestInstallerSetsFields)
{
OrderedTestInstaller(orderedTest, "testgroup", "testname", "this.cpp", 10, 5);
STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString());
STRCMP_EQUAL("testname", orderedTest.getName().asCharString());
STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString());
LONGS_EQUAL(10, orderedTest.getLineNumber());
LONGS_EQUAL(5, orderedTest.getLevel());
}
TEST(TestOrderedTest, InstallOneText)
{
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &orderedTest);
}
TEST(TestOrderedTest, OrderedTestsAreLast)
{
InstallNormalTest(normalTest);
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &normalTest);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInReverseOrder)
{
InstallOrderedTest(orderedTest, 5);
InstallOrderedTest(orderedTest2, 3);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInOrder)
{
InstallOrderedTest(orderedTest2, 3);
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, MultipleOrderedTests)
{
InstallNormalTest(normalTest);
InstallOrderedTest(orderedTest2, 3);
InstallNormalTest(normalTest2);
InstallOrderedTest(orderedTest, 5);
InstallNormalTest(normalTest3);
InstallOrderedTest(orderedTest3, 7);
UtestShell * firstOrderedTest = firstTest()->getNext()->getNext()->getNext();
CHECK(firstOrderedTest == &orderedTest2);
CHECK(firstOrderedTest->getNext() == &orderedTest);
CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3);
}
TEST(TestOrderedTest, MultipleOrderedTests2)
{
InstallOrderedTest(orderedTest, 3);
InstallOrderedTest(orderedTest2, 1);
InstallOrderedTest(orderedTest3, 2);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest3);
CHECK(secondTest()->getNext() == &orderedTest);
}
TEST_GROUP(TestOrderedTestMacros)
{
};
static int testNumber = 0;
TEST(TestOrderedTestMacros, NormalTest)
{
CHECK(testNumber == 0);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test2, 2)
{
CHECK(testNumber == 2);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test1, 1)
{
CHECK(testNumber == 1);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test4, 4)
{
CHECK(testNumber == 4);
testNumber++;
}
TEST_ORDERED(TestOrderedTestMacros, Test3, 3)
{
CHECK(testNumber == 3);
testNumber++;
}
|
/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTestExt/OrderedTest.h"
TEST_GROUP(TestOrderedTest)
{
TestTestingFixture* fixture;
OrderedTestShell orderedTest;
OrderedTestShell orderedTest2;
OrderedTestShell orderedTest3;
ExecFunctionTestShell normalTest;
ExecFunctionTestShell normalTest2;
ExecFunctionTestShell normalTest3;
OrderedTestShell* orderedTestCache;
void setup()
{
orderedTestCache = OrderedTestShell::getOrderedTestHead();
OrderedTestShell::setOrderedTestHead(0);
fixture = new TestTestingFixture();
fixture->registry_->unDoLastAddTest();
}
void teardown()
{
delete fixture;
OrderedTestShell::setOrderedTestHead(orderedTestCache);
}
void InstallOrderedTest(OrderedTestShell& test, int level)
{
OrderedTestInstaller(test, "testgroup", "testname", __FILE__, __LINE__, level);
}
void InstallNormalTest(UtestShell& test)
{
TestInstaller(test, "testgroup", "testname", __FILE__, __LINE__);
}
UtestShell* firstTest()
{
return fixture->registry_->getFirstTest();
}
UtestShell* secondTest()
{
return fixture->registry_->getFirstTest()->getNext();
}
};
TEST(TestOrderedTest, TestInstallerSetsFields)
{
OrderedTestInstaller(orderedTest, "testgroup", "testname", "this.cpp", 10, 5);
STRCMP_EQUAL("testgroup", orderedTest.getGroup().asCharString());
STRCMP_EQUAL("testname", orderedTest.getName().asCharString());
STRCMP_EQUAL("this.cpp", orderedTest.getFile().asCharString());
LONGS_EQUAL(10, orderedTest.getLineNumber());
LONGS_EQUAL(5, orderedTest.getLevel());
}
TEST(TestOrderedTest, InstallOneText)
{
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &orderedTest);
}
TEST(TestOrderedTest, OrderedTestsAreLast)
{
InstallNormalTest(normalTest);
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &normalTest);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInReverseOrder)
{
InstallOrderedTest(orderedTest, 5);
InstallOrderedTest(orderedTest2, 3);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, TwoTestsAddedInOrder)
{
InstallOrderedTest(orderedTest2, 3);
InstallOrderedTest(orderedTest, 5);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest);
}
TEST(TestOrderedTest, MultipleOrderedTests)
{
InstallNormalTest(normalTest);
InstallOrderedTest(orderedTest2, 3);
InstallNormalTest(normalTest2);
InstallOrderedTest(orderedTest, 5);
InstallNormalTest(normalTest3);
InstallOrderedTest(orderedTest3, 7);
UtestShell * firstOrderedTest = firstTest()->getNext()->getNext()->getNext();
CHECK(firstOrderedTest == &orderedTest2);
CHECK(firstOrderedTest->getNext() == &orderedTest);
CHECK(firstOrderedTest->getNext()->getNext() == &orderedTest3);
}
TEST(TestOrderedTest, MultipleOrderedTests2)
{
InstallOrderedTest(orderedTest, 3);
InstallOrderedTest(orderedTest2, 1);
InstallOrderedTest(orderedTest3, 2);
CHECK(firstTest() == &orderedTest2);
CHECK(secondTest() == &orderedTest3);
CHECK(secondTest()->getNext() == &orderedTest);
}
TEST_GROUP(TestOrderedTestMacros)
{
int run;
void setup()
{
run = TestRegistry::getCurrentRegistry()->getCurrentRepetition();
}
};
static int testNumber[] = { 0, 0};
TEST(TestOrderedTestMacros, NormalTest)
{
CHECK(testNumber[run] == 0);
testNumber[run]++;
}
TEST_ORDERED(TestOrderedTestMacros, Test2, 2)
{
CHECK(testNumber[run] == 2);
testNumber[run]++;
}
TEST_ORDERED(TestOrderedTestMacros, Test1, 1)
{
CHECK(testNumber[run] == 1);
testNumber[run]++;
}
TEST_ORDERED(TestOrderedTestMacros, Test4, 4)
{
CHECK(testNumber[run] == 4);
testNumber[run]++;
}
TEST_ORDERED(TestOrderedTestMacros, Test3, 3)
{
CHECK(testNumber[run] == 3);
testNumber[run]++;
}
|
Fix OrderedTestTest
|
Fix OrderedTestTest
|
C++
|
bsd-3-clause
|
Mindtribe/cpputest,bithium/cpputest,arstrube/cpputest,devMichaelJones/cpputest,asgeroverby/cpputest,bithium/cpputest,offa/cpputest,cpputest/cpputest,chenlianbing/cpputest,chenlianbing/cpputest,offa/cpputest,jaeguly/cpputest,Andne/cpputest,Mindtribe/cpputest,asgeroverby/cpputest,jaeguly/cpputest,cpputest/cpputest,maxilai/cpputest,PaulBussmann/cpputest,PaulBussmann/cpputest,PaulBussmann/cpputest,offa/cpputest,dawid-aurobit/cpputest,maxilai/cpputest,jaeguly/cpputest,asgeroverby/cpputest,dawid-aurobit/cpputest,Andne/cpputest,maxilai/cpputest,KisImre/cpputest,KisImre/cpputest,basvodde/cpputest,asgeroverby/cpputest,basvodde/cpputest,dawid-aurobit/cpputest,chenlianbing/cpputest,cpputest/cpputest,basvodde/cpputest,bithium/cpputest,bithium/cpputest,basvodde/cpputest,jaeguly/cpputest,maxilai/cpputest,arstrube/cpputest,cpputest/cpputest,arstrube/cpputest,Andne/cpputest,arstrube/cpputest,devMichaelJones/cpputest,dawid-aurobit/cpputest,Mindtribe/cpputest,chenlianbing/cpputest,devMichaelJones/cpputest,offa/cpputest,Andne/cpputest,devMichaelJones/cpputest,KisImre/cpputest,KisImre/cpputest,Mindtribe/cpputest,PaulBussmann/cpputest
|
6ef0d0e16991df35276061143f978bf85f338133
|
tests/environment/EnvironmentTest.cpp
|
tests/environment/EnvironmentTest.cpp
|
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "Environment.h"
#include "MockSensor.h"
static const char* dummy_name_01 = "dummy_01";
static const char* dummy_name_02 = "dummy_02";
typedef std::vector<MockSensor *> MockSensorList;
TEST_GROUP(Environment)
{
Environment* env;
void setup()
{
env = new Environment();
}
void teardown()
{
mock().clear();
delete env;
}
int createSensors(std::string names[], unsigned int size, MockSensorList* sensors)
{
if(names == NULL || size < 1)
return -1;
if(sensors == NULL)
return -1;
sensors->clear();
for(unsigned int i = 0; i < size; i++)
sensors->push_back( new MockSensor(names[i]) );
return 0;
}
void addSensorsToEnv(MockSensorList* sensors)
{
for(unsigned int i = 0; i < sensors->size(); i++)
env->addSensor(sensors->at(i)->getName(), sensors->at(i));
}
void checkSensorsInEnv(std::string names[], MockSensorList* sensors)
{
LONGS_EQUAL(sensors->size(), env->getNumSensor());
for(unsigned int i = 0; i < sensors->size(); i++)
POINTERS_EQUAL(sensors->at(i), env->getSensorByName(names[i]));
}
void expectOneCallOfInitIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#init()").onObject(sensor);
}
void expectOneCallOfStartIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#start()").onObject(sensor);
}
void expectOneCallOfStopIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#stop()").onObject(sensor);
}
void checkExpectations()
{
mock().checkExpectations();
}
};
TEST(Environment, AddSensor)
{
MockSensor* sensor = new MockSensor(dummy_name_01);
env->addSensor(dummy_name_01, sensor);
LONGS_EQUAL(1, env->getNumSensor());
}
TEST(Environment, AddMultipleSensor)
{
MockSensorList sensors;
std::string names[] = {dummy_name_01, dummy_name_02};
createSensors(names, 2, &sensors);
addSensorsToEnv(&sensors);
checkSensorsInEnv(names, &sensors);
}
TEST(Environment, SingleSensorControl)
{
MockSensor* sensor = new MockSensor(dummy_name_01);
env->addSensor(dummy_name_01, sensor);
expectOneCallOfInitIn(sensor);
env->init();
expectOneCallOfStartIn(sensor);
env->start();
expectOneCallOfStopIn(sensor);
env->stop();
checkExpectations();
}
|
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "Environment.h"
#include "MockSensor.h"
static const char* dummy_name_01 = "dummy_01";
static const char* dummy_name_02 = "dummy_02";
typedef std::vector<MockSensor *> MockSensorList;
TEST_GROUP(Environment)
{
Environment* env;
void setup()
{
env = new Environment();
}
void teardown()
{
mock().clear();
delete env;
}
int createSensors(std::string names[], unsigned int size, MockSensorList* sensors)
{
if(names == NULL || size < 1)
return -1;
if(sensors == NULL)
return -1;
sensors->clear();
for(unsigned int i = 0; i < size; i++)
sensors->push_back( new MockSensor(names[i]) );
return 0;
}
void addSensorsToEnv(MockSensorList* sensors)
{
for(unsigned int i = 0; i < sensors->size(); i++)
env->addSensor(sensors->at(i)->getName(), sensors->at(i));
}
void checkSensorsInEnv(std::string names[], MockSensorList* sensors)
{
LONGS_EQUAL(sensors->size(), env->getNumSensor());
for(unsigned int i = 0; i < sensors->size(); i++)
POINTERS_EQUAL(sensors->at(i), env->getSensorByName(names[i]));
}
void expectOneCallOfInitIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#init()").onObject(sensor);
}
void expectOneCallOfStartIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#start()").onObject(sensor);
}
void expectOneCallOfStopIn(MockSensor* sensor)
{
mock().expectOneCall("Sensor#stop()").onObject(sensor);
}
void checkExpectations()
{
mock().checkExpectations();
}
};
TEST(Environment, AddSensor)
{
MockSensor* sensor = new MockSensor(dummy_name_01);
env->addSensor(dummy_name_01, sensor);
LONGS_EQUAL(1, env->getNumSensor());
}
TEST(Environment, AddMultipleSensor)
{
MockSensorList sensors;
std::string names[] = {dummy_name_01, dummy_name_02};
createSensors(names, 2, &sensors);
addSensorsToEnv(&sensors);
checkSensorsInEnv(names, &sensors);
}
TEST(Environment, SingleSensorControl)
{
MockSensor* sensor = new MockSensor(dummy_name_01);
env->addSensor(dummy_name_01, sensor);
expectOneCallOfInitIn(sensor);
env->init();
expectOneCallOfStartIn(sensor);
env->start();
expectOneCallOfStopIn(sensor);
env->stop();
checkExpectations();
}
TEST(Environment, MultipleSensorControl)
{
MockSensorList sensors;
std::string names[] = {dummy_name_01, dummy_name_02};
createSensors(names, 2, &sensors);
addSensorsToEnv(&sensors);
expectOneCallOfInitIn(sensors[0]);
expectOneCallOfInitIn(sensors[1]);
env->init();
expectOneCallOfStartIn(sensors[0]);
expectOneCallOfStartIn(sensors[1]);
env->start();
expectOneCallOfStopIn(sensors[0]);
expectOneCallOfStopIn(sensors[1]);
env->stop();
checkExpectations();
}
|
add Multiple Sensor Control Test in Environment Test
|
add Multiple Sensor Control Test in Environment Test
|
C++
|
mit
|
cad-san/subsumption,cad-san/subsumption
|
4ea681048a26034b11b83e87ce5202b76b24f93d
|
tutorials/geom/gdml/testoptical.C
|
tutorials/geom/gdml/testoptical.C
|
/// \file
/// \ingroup tutorial_geom
/// Tests importing/exporting optical surfaces from GDML
///
/// Optical surfaces, skin surfaces and border surfaces are imported in object arrays
/// stored by TGeoManager class. Optical surfaces do not store property arrays but point
/// to GDML matrices describing such properties. One can get the data for such property
/// like:
/// TGeoOpticalSurface *surf = geom->GetOpticalSurface("surf1");
/// const char *property = surf=>GetPropertyRef("REFLECTIVITY");
/// TGeoGDMLMatrix *m = geom->GetGDMLMatrix(property);
/// Skin surfaces and border surfaces can be retrieved from the TGeoManager object by using:
/// TObjArray *skin_array = geom->GetListOfSkinSurfaces();
/// TObjArra8 *border_array = geom->GetListOfBorderSurfaces();
/// Alternatively accessors by name can also be used: GetSkinSurface(name)/GetBorderSurface(name)
///
/// \author Andrei Gheata
#include <cassert>
#include <TObjArray.h>
#include <TROOT.h>
#include <TGeoOpticalSurface.h>
#include <TGeoManager.h>
double Checksum(TGeoManager *geom)
{
double sum = 0.;
TIter next(geom->GetListOfOpticalSurfaces());
TGeoOpticalSurface *surf;
while ((surf = (TGeoOpticalSurface *)next())) {
sum += (double)surf->GetType() + (double)surf->GetModel() + (double)surf->GetFinish() + surf->GetValue();
TString name = surf->GetName();
sum += (double)name.Hash();
name = surf->GetTitle();
sum += (double)name.Hash();
}
return sum;
}
int testoptical()
{
TString geofile = gROOT->GetTutorialDir() + "/geom/gdml/opticalsurfaces.gdml";
TGeoManager::SetExportPrecision(8);
TGeoManager::SetVerboseLevel(0);
printf("=== Importing %s ...\n", geofile.Data());
TGeoManager *geom = TGeoManager::Import(geofile);
printf("=== List of GDML matrices:\n");
geom->GetListOfGDMLMatrices()->Print();
printf("=== List of optical surfaces:\n");
geom->GetListOfOpticalSurfaces()->Print();
printf("=== List of skin surfaces:\n");
geom->GetListOfSkinSurfaces()->Print();
printf("=== List of border surfaces:\n");
geom->GetListOfBorderSurfaces()->Print();
// Compute some checksum for optical surfaces
double checksum1 = Checksum(geom);
printf("=== Exporting as .gdml, then importing back\n");
geom->Export("tmp.gdml");
geom = TGeoManager::Import("tmp.gdml");
double checksum2 = Checksum(geom);
assert((checksum2 == checksum1) && "Exporting/importing as .gdml not OK");
printf("=== Exporting as .root, then importing back\n");
geom->Export("tmp.root");
geom = TGeoManager::Import("tmp.root");
double checksum3 = Checksum(geom);
assert((checksum3 == checksum1) && "Exporting/importing as .root not OK");
printf("all OK\n");
return 0;
}
|
/// \file
/// \ingroup tutorial_geom
/// Tests importing/exporting optical surfaces from GDML
///
/// Optical surfaces, skin surfaces and border surfaces are imported in object arrays
/// stored by TGeoManager class. Optical surfaces do not store property arrays but point
/// to GDML matrices describing such properties. One can get the data for such property
/// like:
/// TGeoOpticalSurface *surf = geom->GetOpticalSurface("surf1");
/// const char *property = surf=>GetPropertyRef("REFLECTIVITY");
/// TGeoGDMLMatrix *m = geom->GetGDMLMatrix(property);
/// Skin surfaces and border surfaces can be retrieved from the TGeoManager object by using:
/// TObjArray *skin_array = geom->GetListOfSkinSurfaces();
/// TObjArra8 *border_array = geom->GetListOfBorderSurfaces();
/// Alternatively accessors by name can also be used: GetSkinSurface(name)/GetBorderSurface(name)
///
/// \author Andrei Gheata
#include <cassert>
#include <TObjArray.h>
#include <TROOT.h>
#include <TGeoOpticalSurface.h>
#include <TGeoManager.h>
double Checksum(TGeoManager *geom)
{
double sum = 0.;
TIter next(geom->GetListOfOpticalSurfaces());
TGeoOpticalSurface *surf;
while ((surf = (TGeoOpticalSurface *)next())) {
sum += (double)surf->GetType() + (double)surf->GetModel() + (double)surf->GetFinish() + surf->GetValue();
TString name = surf->GetName();
sum += (double)name.Hash();
name = surf->GetTitle();
sum += (double)name.Hash();
}
return sum;
}
int testoptical()
{
TString geofile = gROOT->GetTutorialDir() + "/geom/gdml/opticalsurfaces.gdml";
geofile.ReplaceAll("\\", "/");
TGeoManager::SetExportPrecision(8);
TGeoManager::SetVerboseLevel(0);
printf("=== Importing %s ...\n", geofile.Data());
TGeoManager *geom = TGeoManager::Import(geofile);
printf("=== List of GDML matrices:\n");
geom->GetListOfGDMLMatrices()->Print();
printf("=== List of optical surfaces:\n");
geom->GetListOfOpticalSurfaces()->Print();
printf("=== List of skin surfaces:\n");
geom->GetListOfSkinSurfaces()->Print();
printf("=== List of border surfaces:\n");
geom->GetListOfBorderSurfaces()->Print();
// Compute some checksum for optical surfaces
double checksum1 = Checksum(geom);
printf("=== Exporting as .gdml, then importing back\n");
geom->Export("tmp.gdml");
geom = TGeoManager::Import("tmp.gdml");
double checksum2 = Checksum(geom);
assert((checksum2 == checksum1) && "Exporting/importing as .gdml not OK");
printf("=== Exporting as .root, then importing back\n");
geom->Export("tmp.root");
geom = TGeoManager::Import("tmp.root");
double checksum3 = Checksum(geom);
assert((checksum3 == checksum1) && "Exporting/importing as .root not OK");
printf("all OK\n");
return 0;
}
|
fix testoptical.C (use only forward slashes in the path)
|
Windows: fix testoptical.C (use only forward slashes in the path)
|
C++
|
lgpl-2.1
|
root-mirror/root,olifre/root,root-mirror/root,olifre/root,karies/root,olifre/root,karies/root,root-mirror/root,olifre/root,olifre/root,olifre/root,karies/root,root-mirror/root,root-mirror/root,karies/root,karies/root,root-mirror/root,karies/root,karies/root,olifre/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,root-mirror/root,karies/root,karies/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,olifre/root,karies/root
|
b95ad5de8205b9cef1eacb58e047c587ff5e6e0c
|
src/asp/ControlNetTK/render_gcp.cc
|
src/asp/ControlNetTK/render_gcp.cc
|
// Boost
#include <boost/program_options.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
#include <vw/Core.h>
#include <vw/Math/Vector.h>
#include <vw/FileIO.h>
#include <vw/Image/Algorithms.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
struct Options : public asp::BaseOptions {
std::vector<std::pair<std::string,Vector2> > input_files;
std::string gcp_file;
std::string output_file;
Vector2i grid_size;
size_t kernel_size;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("kernel-size",po::value(&opt.kernel_size)->default_value(25),
"Size of the individual crops thats make up the output image")
("output,o",po::value(&opt.output_file),
"Output file for this process. If blank it will produce output with extension \"-render.tif\".");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("gcp-file", po::value(&opt.gcp_file));
po::positional_options_description positional_desc;
positional_desc.add("gcp-file", 1);
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <gcp file> \n";
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options,
positional, positional_desc, usage.str() );
if ( opt.gcp_file.empty() )
vw_throw( ArgumentErr() << "Missing input GCP file!\n"
<< usage.str() << general_options );
if ( opt.output_file.empty() )
opt.output_file =
fs::path( opt.gcp_file ).stem()+"-render.tif";
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
// Open GCP file
vw_out() << " -> Opening \"" << opt.gcp_file << "\".\n";
std::ifstream ifile( opt.gcp_file.c_str() );
if ( !ifile.is_open() )
vw_throw( ArgumentErr() << "Unable to open GCP file!\n" );
size_t count = 0;
while (!ifile.eof()) {
if ( count == 0 ) {
// Don't really care about this line
Vector3 eh, ei;
ifile >> eh[0] >> eh[1] >> eh[2] >> ei[0] >> ei[1] >> ei[2];
} else {
std::string file_name;
Vector2 location;
ifile >> file_name >> location[0] >> location[1];
opt.input_files.push_back( std::make_pair(file_name,location) );
}
count++;
}
ifile.close();
// Find and locate input images
vw_out() << " -> Checking input files.\n";
typedef std::pair<std::string,Vector2> ElementType;
BOOST_FOREACH( ElementType const& input, opt.input_files ) {
if ( !fs::exists(input.first) )
vw_throw( IOErr() << "Unable to open \"" << input.first << "\". Is it in the current working directory?" );
}
opt.grid_size[0] = ceil( sqrt( float(opt.input_files.size() ) ) );
opt.grid_size[1] = ceil( float(opt.input_files.size())/float(opt.grid_size[0] ) );
// Render image in memory
vw_out() << " -> Rasterizing \"" << opt.output_file << "\" in memory.\n";
ImageView<PixelGray<uint8> > output(opt.grid_size[0]*opt.kernel_size,
opt.grid_size[1]*opt.kernel_size);
count = 0;
BOOST_FOREACH( ElementType const& input, opt.input_files ) {
// Working out write location
Vector2i index;
index[0] = count - floor(float(count)/float(opt.grid_size[0]))*opt.grid_size[0];
index[1] = floor(float(count)/float(opt.grid_size[0]));
// Applying to image
DiskImageView<PixelGray<float> > image( input.first );
crop( output, index[0]*opt.kernel_size, index[1]*opt.kernel_size,
opt.kernel_size, opt.kernel_size ) =
channel_cast_rescale<uint8>(normalize(crop( image, input.second[0]-opt.kernel_size/2,
input.second[1]-opt.kernel_size/2,
opt.kernel_size, opt.kernel_size )));
count++;
}
write_image( opt.output_file, output );
} ASP_STANDARD_CATCHES;
return 0;
}
|
// Boost
#include <boost/program_options.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;
#include <vw/Core.h>
#include <vw/Math/Vector.h>
#include <vw/FileIO.h>
#include <vw/Image/Algorithms.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
using namespace vw;
// Support for ISIS image files
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
#include <asp/IsisIO/DiskImageResourceIsis.h>
#endif
struct Options : public asp::BaseOptions {
std::vector<std::pair<std::string,Vector2> > input_files;
std::string gcp_file;
std::string output_file;
Vector2i grid_size;
size_t kernel_size;
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("kernel-size",po::value(&opt.kernel_size)->default_value(25),
"Size of the individual crops thats make up the output image")
("output,o",po::value(&opt.output_file),
"Output file for this process. If blank it will produce output with extension \"-render.tif\".");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("gcp-file", po::value(&opt.gcp_file));
po::positional_options_description positional_desc;
positional_desc.add("gcp-file", 1);
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <gcp file> \n";
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options,
positional, positional_desc, usage.str() );
if ( opt.gcp_file.empty() )
vw_throw( ArgumentErr() << "Missing input GCP file!\n"
<< usage.str() << general_options );
if ( opt.output_file.empty() )
opt.output_file =
fs::path( opt.gcp_file ).stem()+"-render.tif";
}
int main( int argc, char *argv[] ) {
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
// Register the Isis file handler with the Vision Workbench
// DiskImageResource system.
DiskImageResource::register_file_type(".cub",
DiskImageResourceIsis::type_static(),
&DiskImageResourceIsis::construct_open,
&DiskImageResourceIsis::construct_create);
#endif
Options opt;
try {
handle_arguments( argc, argv, opt );
// Open GCP file
vw_out() << " -> Opening \"" << opt.gcp_file << "\".\n";
std::ifstream ifile( opt.gcp_file.c_str() );
if ( !ifile.is_open() )
vw_throw( ArgumentErr() << "Unable to open GCP file!\n" );
size_t count = 0;
while (!ifile.eof()) {
if ( count == 0 ) {
// Don't really care about this line
Vector3 eh, ei;
ifile >> eh[0] >> eh[1] >> eh[2] >> ei[0] >> ei[1] >> ei[2];
} else {
std::string file_name;
Vector2 location;
ifile >> file_name >> location[0] >> location[1];
opt.input_files.push_back( std::make_pair(file_name,location) );
}
count++;
}
ifile.close();
// Find and locate input images
vw_out() << " -> Checking input files.\n";
typedef std::pair<std::string,Vector2> ElementType;
BOOST_FOREACH( ElementType const& input, opt.input_files ) {
if ( !fs::exists(input.first) )
vw_throw( IOErr() << "Unable to open \"" << input.first << "\". Is it in the current working directory?" );
}
opt.grid_size[0] = ceil( sqrt( float(opt.input_files.size() ) ) );
opt.grid_size[1] = ceil( float(opt.input_files.size())/float(opt.grid_size[0] ) );
// Render image in memory
vw_out() << " -> Rasterizing \"" << opt.output_file << "\" in memory.\n";
ImageView<PixelGray<uint8> > output(opt.grid_size[0]*opt.kernel_size,
opt.grid_size[1]*opt.kernel_size);
count = 0;
BOOST_FOREACH( ElementType const& input, opt.input_files ) {
// Working out write location
Vector2i index;
index[0] = count - floor(float(count)/float(opt.grid_size[0]))*opt.grid_size[0];
index[1] = floor(float(count)/float(opt.grid_size[0]));
// Applying to image
DiskImageView<PixelGray<float> > image( input.first );
crop( output, index[0]*opt.kernel_size, index[1]*opt.kernel_size,
opt.kernel_size, opt.kernel_size ) =
channel_cast_rescale<uint8>(normalize(crop( image, input.second[0]-opt.kernel_size/2,
input.second[1]-opt.kernel_size/2,
opt.kernel_size, opt.kernel_size )));
count++;
}
write_image( opt.output_file, output );
} ASP_STANDARD_CATCHES;
return 0;
}
|
Make render_gcp use our ISIS driver by default
|
Make render_gcp use our ISIS driver by default
GDAL has some weird issues.
|
C++
|
apache-2.0
|
njwilson23/StereoPipeline,DougFirErickson/StereoPipeline,ScottMcMichael/StereoPipeline,njwilson23/StereoPipeline,oleg-alexandrov/StereoPipeline,DougFirErickson/StereoPipeline,oleg-alexandrov/StereoPipeline,NeoGeographyToolkit/StereoPipeline,DougFirErickson/StereoPipeline,njwilson23/StereoPipeline,DougFirErickson/StereoPipeline,NeoGeographyToolkit/StereoPipeline,aaronknister/StereoPipeline,NeoGeographyToolkit/StereoPipeline,ScottMcMichael/StereoPipeline,ScottMcMichael/StereoPipeline,aaronknister/StereoPipeline,NeoGeographyToolkit/StereoPipeline,ScottMcMichael/StereoPipeline,njwilson23/StereoPipeline,oleg-alexandrov/StereoPipeline,oleg-alexandrov/StereoPipeline,aaronknister/StereoPipeline,ScottMcMichael/StereoPipeline,DougFirErickson/StereoPipeline,oleg-alexandrov/StereoPipeline,DougFirErickson/StereoPipeline,aaronknister/StereoPipeline,ScottMcMichael/StereoPipeline,NeoGeographyToolkit/StereoPipeline,aaronknister/StereoPipeline,oleg-alexandrov/StereoPipeline,NeoGeographyToolkit/StereoPipeline,njwilson23/StereoPipeline,njwilson23/StereoPipeline
|
a01605a95bcec08e2e30abd869a5b6bbd64dfa3a
|
tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/lhlo_legalize_to_gpu.cc
|
tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/lhlo_legalize_to_gpu.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file implements logic for lowering LHLO dialect to GPU dialect.
#include <cstdint>
#include "llvm/ADT/ArrayRef.h"
#include "mlir-hlo/Dialect/lhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/lhlo/transforms/PassDetail.h"
#include "mlir-hlo/Dialect/lhlo/transforms/map_lmhlo_to_scalar_op.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/GPU/GPUDialect.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace lmhlo {
namespace {
// A simple translation of LHLO reduce operations to a corresponding gpu
// launch operation. The transformation does no tiling and also only supports
// 1d results.
class LhloReduceToGPULaunchConverter : public OpConversionPattern<ReduceOp> {
public:
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
ReduceOp reduce_op, OpAdaptor adaptor,
ConversionPatternRewriter& rewriter) const final {
auto loc = reduce_op.getLoc();
// Only support 1d reductions for now.
int64_t size = 0;
for (auto result : reduce_op.out()) {
auto shaped_type = result.getType().dyn_cast<ShapedType>();
if (!shaped_type || shaped_type.getRank() != 1) {
return failure();
}
auto dim_size = shaped_type.getDimSize(0);
if (size && size != dim_size) {
return failure();
}
size = dim_size;
}
auto reducing_dimension = *reduce_op.dimensions().value_begin<APInt>();
// Require all inputs to have the same shape.
int64_t reduce_dim_size = 0;
for (auto input : reduce_op.inputs()) {
auto shaped_type = input.getType().dyn_cast<ShapedType>();
if (!shaped_type || !shaped_type.hasStaticShape()) {
return failure();
}
reduce_dim_size =
shaped_type.getDimSize(reducing_dimension.getSExtValue());
}
// Create a launch that is parallel in the result dimension.
auto block_size_x = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), size));
auto one = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 1));
auto launch_op = rewriter.create<mlir::gpu::LaunchOp>(
loc, one, one, one, block_size_x, one, one);
{
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToEnd(&launch_op.body().front());
auto index = launch_op.getThreadIds().x;
// Load the initial value and store it to the output.
for (auto pair : llvm::zip(reduce_op.init_values(), reduce_op.out())) {
auto init_value =
rewriter.create<mlir::memref::LoadOp>(loc, std::get<0>(pair));
rewriter.create<mlir::memref::StoreOp>(
loc, init_value, std::get<1>(pair), ArrayRef<Value>{index});
}
// Insert a loop into the body to compute the reduction. The loop ranges
// from [0.dim).
auto zero = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 0));
// TODO(b/137624192) Use dimOp to make it shape independent.
auto upper = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), reduce_dim_size));
auto step = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 1));
auto loop = rewriter.create<mlir::scf::ForOp>(loc, zero, upper, step);
rewriter.setInsertionPointToStart(loop.getBody());
// Compute memrefs for the value to reduce. This makes it easier to just
// inline the body.
auto output = *reduce_op.out().begin();
auto resType = MemRefType::get(
llvm::None, getElementTypeOrSelf(output.getType()),
makeStridedLinearLayoutMap(llvm::None,
MemRefType::getDynamicStrideOrOffset(),
rewriter.getContext()));
OpFoldResult offset = launch_op.getThreadIds().x;
auto oneAttr = rewriter.getI64IntegerAttr(1);
OpFoldResult size = oneAttr;
OpFoldResult stride = oneAttr;
auto accumulator = rewriter.create<memref::SubViewOp>(
loc, resType, output, offset, size, stride);
llvm::SmallVector<Value, 4> indexings;
Value input_buffer = reduce_op.inputs().front();
auto input_type_rank =
input_buffer.getType().cast<MemRefType>().getRank();
Value input = *reduce_op.operand_begin();
SmallVector<OpFoldResult> offsets = llvm::to_vector<4>(llvm::map_range(
llvm::seq<int>(0, input_type_rank), [&](int dim) -> OpFoldResult {
return dim == reducing_dimension ? loop.getInductionVar()
: launch_op.getThreadIds().x;
}));
SmallVector<OpFoldResult> sizes(input_type_rank, oneAttr);
SmallVector<OpFoldResult> strides(input_type_rank, oneAttr);
auto rhs = rewriter.create<memref::SubViewOp>(
loc, accumulator.getType(), input, offsets, sizes, strides);
// Now copy over the actual body of the reduction, leaving out the
// terminator.
BlockAndValueMapping mapping;
mapping.map(reduce_op.body().getArgument(0), accumulator);
mapping.map(reduce_op.body().getArgument(1), rhs);
mapping.map(reduce_op.body().getArgument(2), accumulator);
for (auto& nested : reduce_op.body().front().without_terminator()) {
auto* clone = rewriter.clone(nested, mapping);
for (auto pair : llvm::zip(nested.getResults(), clone->getResults())) {
mapping.map(std::get<0>(pair), std::get<1>(pair));
}
}
// Finally, insert the terminator for the launchOp.
rewriter.setInsertionPointToEnd(&launch_op.body().front());
rewriter.create<mlir::gpu::TerminatorOp>(loc);
}
rewriter.eraseOp(reduce_op);
return success();
};
};
struct LhloLegalizeToGpuPass
: public LhloLegalizeToGpuPassBase<LhloLegalizeToGpuPass> {
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<AffineDialect, gpu::GPUDialect, linalg::LinalgDialect,
memref::MemRefDialect, scf::SCFDialect>();
}
void runOnFunction() override {
OwningRewritePatternList patterns(&getContext());
ConversionTarget target(getContext());
target.addLegalDialect<arith::ArithmeticDialect, linalg::LinalgDialect,
memref::MemRefDialect, StandardOpsDialect,
gpu::GPUDialect, scf::SCFDialect, LmhloDialect>();
target.addIllegalOp<ReduceOp>();
auto func = getFunction();
patterns.insert<LhloReduceToGPULaunchConverter>(func.getContext());
if (failed(applyPartialConversion(func, target, std::move(patterns)))) {
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<FunctionPass> createLegalizeToGpuPass() {
return std::make_unique<LhloLegalizeToGpuPass>();
}
} // namespace lmhlo
} // namespace mlir
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file implements logic for lowering LHLO dialect to GPU dialect.
#include <cstdint>
#include "llvm/ADT/ArrayRef.h"
#include "mlir-hlo/Dialect/lhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/lhlo/transforms/PassDetail.h"
#include "mlir-hlo/Dialect/lhlo/transforms/map_lmhlo_to_scalar_op.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/GPU/GPUDialect.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace lmhlo {
namespace {
// A simple translation of LHLO reduce operations to a corresponding gpu
// launch operation. The transformation does no tiling and also only supports
// 1d results.
class LhloReduceToGPULaunchConverter : public OpConversionPattern<ReduceOp> {
public:
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
ReduceOp reduce_op, OpAdaptor /*adaptor*/,
ConversionPatternRewriter& rewriter) const final {
auto loc = reduce_op.getLoc();
// Only support 1d reductions for now.
int64_t size = 0;
for (auto result : reduce_op.out()) {
auto shaped_type = result.getType().dyn_cast<ShapedType>();
if (!shaped_type || shaped_type.getRank() != 1) {
return failure();
}
auto dim_size = shaped_type.getDimSize(0);
if (size && size != dim_size) {
return failure();
}
size = dim_size;
}
auto reducing_dimension = *reduce_op.dimensions().value_begin<APInt>();
// Require all inputs to have the same shape.
int64_t reduce_dim_size = 0;
for (auto input : reduce_op.inputs()) {
auto shaped_type = input.getType().dyn_cast<ShapedType>();
if (!shaped_type || !shaped_type.hasStaticShape()) {
return failure();
}
reduce_dim_size =
shaped_type.getDimSize(reducing_dimension.getSExtValue());
}
// Create a launch that is parallel in the result dimension.
auto block_size_x = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), size));
auto one = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 1));
auto launch_op = rewriter.create<mlir::gpu::LaunchOp>(
loc, one, one, one, block_size_x, one, one);
{
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToEnd(&launch_op.body().front());
auto index = launch_op.getThreadIds().x;
// Load the initial value and store it to the output.
for (auto pair : llvm::zip(reduce_op.init_values(), reduce_op.out())) {
auto init_value =
rewriter.create<mlir::memref::LoadOp>(loc, std::get<0>(pair));
rewriter.create<mlir::memref::StoreOp>(
loc, init_value, std::get<1>(pair), ArrayRef<Value>{index});
}
// Insert a loop into the body to compute the reduction. The loop ranges
// from [0.dim).
auto zero = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 0));
// TODO(b/137624192) Use dimOp to make it shape independent.
auto upper = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), reduce_dim_size));
auto step = rewriter.create<mlir::arith::ConstantOp>(
loc, rewriter.getIndexType(),
rewriter.getIntegerAttr(rewriter.getIndexType(), 1));
auto loop = rewriter.create<mlir::scf::ForOp>(loc, zero, upper, step);
rewriter.setInsertionPointToStart(loop.getBody());
// Compute memrefs for the value to reduce. This makes it easier to just
// inline the body.
auto output = *reduce_op.out().begin();
auto resType = MemRefType::get(
llvm::None, getElementTypeOrSelf(output.getType()),
makeStridedLinearLayoutMap(llvm::None,
MemRefType::getDynamicStrideOrOffset(),
rewriter.getContext()));
OpFoldResult offset = launch_op.getThreadIds().x;
auto oneAttr = rewriter.getI64IntegerAttr(1);
OpFoldResult size = oneAttr;
OpFoldResult stride = oneAttr;
auto accumulator = rewriter.create<memref::SubViewOp>(
loc, resType, output, offset, size, stride);
llvm::SmallVector<Value, 4> indexings;
Value input_buffer = reduce_op.inputs().front();
auto input_type_rank =
input_buffer.getType().cast<MemRefType>().getRank();
Value input = *reduce_op.operand_begin();
SmallVector<OpFoldResult> offsets = llvm::to_vector<4>(llvm::map_range(
llvm::seq<int>(0, input_type_rank), [&](int dim) -> OpFoldResult {
return dim == reducing_dimension ? loop.getInductionVar()
: launch_op.getThreadIds().x;
}));
SmallVector<OpFoldResult> sizes(input_type_rank, oneAttr);
SmallVector<OpFoldResult> strides(input_type_rank, oneAttr);
auto rhs = rewriter.create<memref::SubViewOp>(
loc, accumulator.getType(), input, offsets, sizes, strides);
// Now copy over the actual body of the reduction, leaving out the
// terminator.
BlockAndValueMapping mapping;
mapping.map(reduce_op.body().getArgument(0), accumulator);
mapping.map(reduce_op.body().getArgument(1), rhs);
mapping.map(reduce_op.body().getArgument(2), accumulator);
for (auto& nested : reduce_op.body().front().without_terminator()) {
auto* clone = rewriter.clone(nested, mapping);
for (auto pair : llvm::zip(nested.getResults(), clone->getResults())) {
mapping.map(std::get<0>(pair), std::get<1>(pair));
}
}
// Finally, insert the terminator for the launchOp.
rewriter.setInsertionPointToEnd(&launch_op.body().front());
rewriter.create<mlir::gpu::TerminatorOp>(loc);
}
rewriter.eraseOp(reduce_op);
return success();
};
};
struct LhloLegalizeToGpuPass
: public LhloLegalizeToGpuPassBase<LhloLegalizeToGpuPass> {
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<AffineDialect, gpu::GPUDialect, linalg::LinalgDialect,
memref::MemRefDialect, scf::SCFDialect>();
}
void runOnFunction() override {
OwningRewritePatternList patterns(&getContext());
ConversionTarget target(getContext());
target.addLegalDialect<arith::ArithmeticDialect, linalg::LinalgDialect,
memref::MemRefDialect, StandardOpsDialect,
gpu::GPUDialect, scf::SCFDialect, LmhloDialect>();
target.addIllegalOp<ReduceOp>();
auto func = getFunction();
patterns.insert<LhloReduceToGPULaunchConverter>(func.getContext());
if (failed(applyPartialConversion(func, target, std::move(patterns)))) {
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<FunctionPass> createLegalizeToGpuPass() {
return std::make_unique<LhloLegalizeToGpuPass>();
}
} // namespace lmhlo
} // namespace mlir
|
Apply clang-tidy fixes for misc-unused-parameters in lhlo_legalize_to_gpu.cc (NFC)
|
Apply clang-tidy fixes for misc-unused-parameters in lhlo_legalize_to_gpu.cc (NFC)
PiperOrigin-RevId: 418611653
Change-Id: I0ea1884c5ae7cc6e4db2709d72fe2807ae4d2aa0
|
C++
|
apache-2.0
|
paolodedios/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once
|
2cec28a6c484366c621b25f0d67300836ca7dd98
|
3RVX/LayeredWnd/LayeredWnd.cpp
|
3RVX/LayeredWnd/LayeredWnd.cpp
|
#include "LayeredWnd.h"
#include <iostream>
bool LayeredWnd::Init() {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = &LayeredWnd::StaticWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = m_className;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return false;
}
m_hWnd = CreateWindowEx(
WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_NOACTIVATE,
m_className, m_title,
WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
1, 1,
NULL, NULL, m_hInstance, this);
if (m_hWnd == NULL) {
return false;
}
m_transparency = 255;
m_location.x = 0;
m_location.y = 0;
m_size.cx = 1;
m_size.cy = 1;
return true;
}
void LayeredWnd::UpdateLayeredWnd() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = m_transparency;
HDC screenDc = GetDC(GetDesktopWindow());
HDC sourceDc = CreateCompatibleDC(screenDc);
HBITMAP hBmp;
m_buffer->GetHBITMAP(Gdiplus::Color(0, 0, 0, 0), &hBmp);
HGDIOBJ hReplaced = SelectObject(sourceDc, hBmp);
POINT pt = { 0, 0 };
SIZE size = { m_buffer->GetWidth(), m_buffer->GetHeight() };
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = screenDc;
lwInfo.hdcSrc = sourceDc;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = &m_location;
lwInfo.pptSrc = &pt;
lwInfo.prcDirty = m_dirtyRect;
lwInfo.psize = &size;
UpdateLayeredWindowIndirect(m_hWnd, &lwInfo);
SelectObject(sourceDc, hReplaced);
DeleteDC(sourceDc);
DeleteObject(hBmp);
ReleaseDC(GetDesktopWindow(), screenDc);
}
void LayeredWnd::Show() {
UpdateLocation();
ShowWindow(m_hWnd, SW_SHOW);
}
void LayeredWnd::Hide() {
ShowWindow(m_hWnd, SW_HIDE);
}
void LayeredWnd::UpdateTransparency() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = m_transparency;
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = NULL;
lwInfo.hdcSrc = NULL;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = NULL;
lwInfo.pptSrc = NULL;
lwInfo.prcDirty = NULL;
lwInfo.psize = NULL;
UpdateLayeredWindowIndirect(m_hWnd, &lwInfo);
}
LayeredWnd::~LayeredWnd() {
return;
}
//
// UpdateLocation()
//
// Uses MoveWindow() to set the window's X,Y coordinates its size.
//
void LayeredWnd::UpdateLocation() {
MoveWindow(m_hWnd, m_location.x, m_location.y, m_size.cx, m_size.cy, FALSE);
}
LRESULT CALLBACK
LayeredWnd::StaticWndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
LayeredWnd* lWnd;
if (message == WM_CREATE) {
lWnd = (LayeredWnd*) ((LPCREATESTRUCT) lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) lWnd);
} else {
lWnd = (LayeredWnd*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!lWnd) {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return lWnd->WndProc(message, wParam, lParam);
}
LRESULT LayeredWnd::WndProc(UINT message, WPARAM wParam, LPARAM lParam) {
return DefWindowProc(m_hWnd, message, wParam, lParam);
}
// - GETTERS --------------------------------------------------------------- //
int LayeredWnd::X() const {
return m_location.x;
}
void LayeredWnd::X(int x) {
m_location.x = x;
}
int LayeredWnd::Y() const {
return m_location.y;
}
void LayeredWnd::Y(int y) {
m_location.y = y;
}
int LayeredWnd::Height() const {
return m_size.cy;
}
int LayeredWnd::Width() const {
return m_size.cx;
}
byte LayeredWnd::Transparency() const {
return m_transparency;
}
void LayeredWnd::Transparency(byte transparency) {
m_transparency = transparency;
UpdateTransparency();
}
HWND LayeredWnd::Hwnd() const {
return m_hWnd;
}
Gdiplus::Bitmap *LayeredWnd::Image() {
return m_buffer;
}
void LayeredWnd::Image(Gdiplus::Bitmap *image) {
m_buffer = image;
m_size.cx = image->GetWidth();
m_size.cy = image->GetHeight();
UpdateLayeredWnd();
}
|
#include "LayeredWnd.h"
#include <iostream>
bool LayeredWnd::Init() {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = &LayeredWnd::StaticWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = m_className;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return false;
}
m_hWnd = CreateWindowEx(
WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_NOACTIVATE \
| WS_EX_TOPMOST | WS_EX_TRANSPARENT,
m_className, m_title,
WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
1, 1,
NULL, NULL, m_hInstance, this);
if (m_hWnd == NULL) {
return false;
}
m_transparency = 255;
m_location.x = 0;
m_location.y = 0;
m_size.cx = 1;
m_size.cy = 1;
return true;
}
void LayeredWnd::UpdateLayeredWnd() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = m_transparency;
HDC screenDc = GetDC(GetDesktopWindow());
HDC sourceDc = CreateCompatibleDC(screenDc);
HBITMAP hBmp;
m_buffer->GetHBITMAP(Gdiplus::Color(0, 0, 0, 0), &hBmp);
HGDIOBJ hReplaced = SelectObject(sourceDc, hBmp);
POINT pt = { 0, 0 };
SIZE size = { m_buffer->GetWidth(), m_buffer->GetHeight() };
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = screenDc;
lwInfo.hdcSrc = sourceDc;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = &m_location;
lwInfo.pptSrc = &pt;
lwInfo.prcDirty = m_dirtyRect;
lwInfo.psize = &size;
UpdateLayeredWindowIndirect(m_hWnd, &lwInfo);
SelectObject(sourceDc, hReplaced);
DeleteDC(sourceDc);
DeleteObject(hBmp);
ReleaseDC(GetDesktopWindow(), screenDc);
}
void LayeredWnd::Show() {
UpdateLocation();
ShowWindow(m_hWnd, SW_SHOW);
}
void LayeredWnd::Hide() {
ShowWindow(m_hWnd, SW_HIDE);
}
void LayeredWnd::UpdateTransparency() {
BLENDFUNCTION bFunc;
bFunc.AlphaFormat = AC_SRC_ALPHA;
bFunc.BlendFlags = 0;
bFunc.BlendOp = AC_SRC_OVER;
bFunc.SourceConstantAlpha = m_transparency;
UPDATELAYEREDWINDOWINFO lwInfo;
lwInfo.cbSize = sizeof(UPDATELAYEREDWINDOWINFO);
lwInfo.crKey = 0;
lwInfo.dwFlags = ULW_ALPHA;
lwInfo.hdcDst = NULL;
lwInfo.hdcSrc = NULL;
lwInfo.pblend = &bFunc;
lwInfo.pptDst = NULL;
lwInfo.pptSrc = NULL;
lwInfo.prcDirty = NULL;
lwInfo.psize = NULL;
UpdateLayeredWindowIndirect(m_hWnd, &lwInfo);
}
LayeredWnd::~LayeredWnd() {
return;
}
//
// UpdateLocation()
//
// Uses MoveWindow() to set the window's X,Y coordinates its size.
//
void LayeredWnd::UpdateLocation() {
MoveWindow(m_hWnd, m_location.x, m_location.y, m_size.cx, m_size.cy, FALSE);
}
LRESULT CALLBACK
LayeredWnd::StaticWndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
LayeredWnd* lWnd;
if (message == WM_CREATE) {
lWnd = (LayeredWnd*) ((LPCREATESTRUCT) lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) lWnd);
} else {
lWnd = (LayeredWnd*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!lWnd) {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return lWnd->WndProc(message, wParam, lParam);
}
LRESULT LayeredWnd::WndProc(UINT message, WPARAM wParam, LPARAM lParam) {
return DefWindowProc(m_hWnd, message, wParam, lParam);
}
// - GETTERS --------------------------------------------------------------- //
int LayeredWnd::X() const {
return m_location.x;
}
void LayeredWnd::X(int x) {
m_location.x = x;
}
int LayeredWnd::Y() const {
return m_location.y;
}
void LayeredWnd::Y(int y) {
m_location.y = y;
}
int LayeredWnd::Height() const {
return m_size.cy;
}
int LayeredWnd::Width() const {
return m_size.cx;
}
byte LayeredWnd::Transparency() const {
return m_transparency;
}
void LayeredWnd::Transparency(byte transparency) {
m_transparency = transparency;
UpdateTransparency();
}
HWND LayeredWnd::Hwnd() const {
return m_hWnd;
}
Gdiplus::Bitmap *LayeredWnd::Image() {
return m_buffer;
}
void LayeredWnd::Image(Gdiplus::Bitmap *image) {
m_buffer = image;
m_size.cx = image->GetWidth();
m_size.cy = image->GetHeight();
UpdateLayeredWnd();
}
|
Make window topmost and pass clicks through
|
Make window topmost and pass clicks through
|
C++
|
bsd-2-clause
|
malensek/3RVX,malensek/3RVX,Soulflare3/3RVX,Soulflare3/3RVX,malensek/3RVX,Soulflare3/3RVX
|
9514a455b175fbe98c4c312554fe625832d75d91
|
razor-config-mouse/thememodel.cpp
|
razor-config-mouse/thememodel.cpp
|
/* Copyright © 2005-2007 Fredrik Höglund <[email protected]>
* (c)GPL2 (c)GPL3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 or at your option version 3 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* additional code: Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
*/
#include <QDebug>
#include "thememodel.h"
#include <QDir>
#include "crtheme.h"
#include "cfgfile.h"
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
//#define DUMP_FOUND_THEMES
///////////////////////////////////////////////////////////////////////////////
XCursorThemeModel::XCursorThemeModel (QObject *parent) : QAbstractTableModel(parent) {
insertThemes();
}
XCursorThemeModel::~XCursorThemeModel () {
qDeleteAll(mList);
mList.clear();
}
QVariant XCursorThemeModel::headerData (int section, Qt::Orientation orientation, int role) const {
// Only provide text for the headers
if (role != Qt::DisplayRole) return QVariant();
// Horizontal header labels
if (orientation == Qt::Horizontal) {
switch (section) {
case NameColumn: return tr("Name");
case DescColumn: return tr("Description");
default: return QVariant();
}
}
// Numbered vertical header lables
return QString(section);
}
QVariant XCursorThemeModel::data (const QModelIndex &index, int role) const {
if (!index.isValid() || index.row() < 0 || index.row() >= mList.count()) return QVariant();
const XCursorThemeData *theme = mList.at(index.row());
// Text label
if (role == Qt::DisplayRole) {
switch (index.column()) {
case NameColumn: return theme->title();
case DescColumn: return theme->description();
default: return QVariant();
}
}
// Description for the first name column
if (role == XCursorThemeData::DisplayDetailRole && index.column() == NameColumn) return theme->description();
// Icon for the name column
if (role == Qt::DecorationRole && index.column() == NameColumn) return theme->icon();
//
return QVariant();
}
void XCursorThemeModel::sort (int column, Qt::SortOrder order) {
Q_UNUSED(column);
Q_UNUSED(order);
// Sorting of the model isn't implemented, as the KCM currently uses
// a sorting proxy model.
}
const XCursorThemeData *XCursorThemeModel::theme (const QModelIndex &index) {
if (!index.isValid()) return NULL;
if (index.row() < 0 || index.row() >= mList.count()) return NULL;
return mList.at(index.row());
}
QModelIndex XCursorThemeModel::findIndex (const QString &name) {
uint hash = qHash(name);
for (int i = 0; i < mList.count(); i++) {
const XCursorThemeData *theme = mList.at(i);
if (theme->hash() == hash) return index(i, 0);
}
return QModelIndex();
}
QModelIndex XCursorThemeModel::defaultIndex () {
return findIndex(mDefaultName);
}
const QStringList XCursorThemeModel::searchPaths () {
if (!mBaseDirs.isEmpty()) return mBaseDirs;
// Get the search path from Xcursor
QString path = XcursorLibraryPath();
// Separate the paths
mBaseDirs = path.split(':', QString::SkipEmptyParts);
// Remove duplicates
QMutableStringListIterator i(mBaseDirs);
while (i.hasNext()) {
const QString path = i.next();
QMutableStringListIterator j(i);
while (j.hasNext()) if (j.next() == path) j.remove();
}
// Expand all occurrences of ~/ to the home dir
mBaseDirs.replaceInStrings(QRegExp("^~\\/"), QDir::home().path() + '/');
return mBaseDirs;
}
bool XCursorThemeModel::hasTheme (const QString &name) const {
const uint hash = qHash(name);
foreach (const XCursorThemeData *theme, mList) if (theme->hash() == hash) return true;
return false;
}
bool XCursorThemeModel::isCursorTheme (const QString &theme, const int depth) {
// Prevent infinite recursion
if (depth > 10) return false;
// Search each icon theme directory for 'theme'
foreach (const QString &baseDir, searchPaths()) {
QDir dir(baseDir);
if (!dir.exists() || !dir.cd(theme)) continue;
// If there's a cursors subdir, we'll assume this is a cursor theme
if (dir.exists("cursors")) return true;
// If the theme doesn't have an index.theme file, it can't inherit any themes
if (!dir.exists("index.theme")) continue;
// Open the index.theme file, so we can get the list of inherited themes
QMultiMap<QString, QString> cfg = loadCfgFile(dir.path()+"/index.theme", true);
QStringList inherits = cfg.values("icon theme/inherits");
// Recurse through the list of inherited themes, to check if one of them is a cursor theme
// note that items are reversed
for (int f = inherits.size()-1; f >= 0; f--) {
QString inh = inherits.at(f);
// Avoid possible DoS
if (inh == theme) continue;
if (isCursorTheme(inh, depth+1)) return true;
}
}
return false;
}
bool XCursorThemeModel::handleDefault (const QDir &themeDir) {
QFileInfo info(themeDir.path());
// If "default" is a symlink
if (info.isSymLink()) {
QFileInfo target(info.symLinkTarget());
if (target.exists() && (target.isDir() || target.isSymLink())) mDefaultName = target.fileName();
return true;
}
// If there's no cursors subdir, or if it's empty
if (!themeDir.exists("cursors") || QDir(themeDir.path() + "/cursors").entryList(QDir::Files | QDir::NoDotAndDotDot).isEmpty()) {
if (themeDir.exists("index.theme")) {
XCursorThemeData theme(themeDir);
if (!theme.inherits().isEmpty()) mDefaultName = theme.inherits().at(0);
}
return true;
}
mDefaultName = QLatin1String("default");
return false;
}
//#define DUMP_FOUND_THEMES
void XCursorThemeModel::processThemeDir (const QDir &themeDir) {
#ifdef DUMP_FOUND_THEMES
qDebug() << "looking at:" << themeDir.path();
#endif
bool haveCursors = themeDir.exists("cursors");
// Special case handling of "default", since it's usually either a
// symlink to another theme, or an empty theme that inherits another theme
if (mDefaultName.isNull() && themeDir.dirName() == "default") {
if (handleDefault(themeDir)) return;
}
// If the directory doesn't have a cursors subdir and lacks an
// index.theme file it can't be a cursor theme.
if (!themeDir.exists("index.theme") && !haveCursors) {
// qDebug() << "IS NOT THEME" << themeDir;
return;
}
// Create a cursor theme object for the theme dir
XCursorThemeData *theme = new XCursorThemeData(themeDir);
// Skip this theme if it's hidden
#ifdef DUMP_FOUND_THEMES
qDebug() <<
" theme name:" << theme->name() <<
"\n theme title:" << theme->title() <<
"\n theme desc:" << theme->description() <<
"\n theme sample:" << theme->sample() <<
"\n theme inherits:" << theme->inherits()
;
#endif
if (theme->isHidden()) {
// qDebug() << "HIDDEN THEME" << theme->name() << themeDir;
delete theme;
return;
}
// If there's no cursors subdirectory we'll do a recursive scan
// to check if the theme inherits a theme with one
if (!haveCursors) {
bool foundCursorTheme = false;
foreach (const QString &name, theme->inherits()) if ((foundCursorTheme = isCursorTheme(name))) break;
if (!foundCursorTheme) {
delete theme;
return;
}
}
// Append the theme to the list
mList.append(theme);
}
void XCursorThemeModel::insertThemes () {
// Scan each base dir for Xcursor themes and add them to the list
foreach (const QString &baseDir, searchPaths()) {
QDir dir(baseDir);
// qDebug() << "TOPLEVEL" << baseDir;
if (!dir.exists()) continue;
// qDebug() << " continue passed";
// Process each subdir in the directory
foreach (const QString &name, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Readable | QDir::Executable)) {
// qDebug() << " SUBDIR" << name;
// Don't process the theme if a theme with the same name already exists
// in the list. Xcursor will pick the first one it finds in that case,
// and since we use the same search order, the one Xcursor picks should
// be the one already in the list
if (hasTheme(name)) {
qDebug() << "duplicate theme:" << dir.path()+name;
}
if (!dir.cd(name)) {
qDebug() << "can't cd:" << dir.path()+name;
continue;
}
processThemeDir(dir);
dir.cdUp(); // Return to the base dir
}
}
// The theme Xcursor will end up using if no theme is configured
//if (mDefaultName.isNull() || !hasTheme(mDefaultName)) mDefaultName = legacy->name();
}
bool XCursorThemeModel::addTheme (const QDir &dir) {
XCursorThemeData *theme = new XCursorThemeData(dir);
// Don't add the theme to the list if it's hidden
if (theme->isHidden()) {
delete theme;
return false;
}
// If an item with the same name already exists in the list,
// we'll remove it before inserting the new one.
for (int i = 0; i < mList.count(); i++) {
if (mList.at(i)->hash() == theme->hash()) {
removeTheme(index(i, 0));
break;
}
}
// Append the theme to the list
beginInsertRows(QModelIndex(), rowCount(), rowCount());
mList.append(theme);
endInsertRows();
return true;
}
void XCursorThemeModel::removeTheme (const QModelIndex &index) {
if (!index.isValid()) return;
beginRemoveRows(QModelIndex(), index.row(), index.row());
delete mList.takeAt(index.row());
endRemoveRows();
}
|
/* Copyright © 2005-2007 Fredrik Höglund <[email protected]>
* (c)GPL2 (c)GPL3
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 or at your option version 3 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* additional code: Ketmar // Vampire Avalon (psyc://ketmar.no-ip.org/~Ketmar)
*/
#include <QtCore/QDebug>
#include "thememodel.h"
#include <QtCore/QDir>
#include "crtheme.h"
#include "cfgfile.h"
#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
//#define DUMP_FOUND_THEMES
///////////////////////////////////////////////////////////////////////////////
XCursorThemeModel::XCursorThemeModel (QObject *parent) : QAbstractTableModel(parent) {
insertThemes();
}
XCursorThemeModel::~XCursorThemeModel () {
qDeleteAll(mList);
mList.clear();
}
QVariant XCursorThemeModel::headerData (int section, Qt::Orientation orientation, int role) const {
// Only provide text for the headers
if (role != Qt::DisplayRole) return QVariant();
// Horizontal header labels
if (orientation == Qt::Horizontal) {
switch (section) {
case NameColumn: return tr("Name");
case DescColumn: return tr("Description");
default: return QVariant();
}
}
// Numbered vertical header lables
return QString(section);
}
QVariant XCursorThemeModel::data (const QModelIndex &index, int role) const {
if (!index.isValid() || index.row() < 0 || index.row() >= mList.count()) return QVariant();
const XCursorThemeData *theme = mList.at(index.row());
// Text label
if (role == Qt::DisplayRole) {
switch (index.column()) {
case NameColumn: return theme->title();
case DescColumn: return theme->description();
default: return QVariant();
}
}
// Description for the first name column
if (role == XCursorThemeData::DisplayDetailRole && index.column() == NameColumn) return theme->description();
// Icon for the name column
if (role == Qt::DecorationRole && index.column() == NameColumn) return theme->icon();
//
return QVariant();
}
void XCursorThemeModel::sort (int column, Qt::SortOrder order) {
Q_UNUSED(column);
Q_UNUSED(order);
// Sorting of the model isn't implemented, as the KCM currently uses
// a sorting proxy model.
}
const XCursorThemeData *XCursorThemeModel::theme (const QModelIndex &index) {
if (!index.isValid()) return NULL;
if (index.row() < 0 || index.row() >= mList.count()) return NULL;
return mList.at(index.row());
}
QModelIndex XCursorThemeModel::findIndex (const QString &name) {
uint hash = qHash(name);
for (int i = 0; i < mList.count(); i++) {
const XCursorThemeData *theme = mList.at(i);
if (theme->hash() == hash) return index(i, 0);
}
return QModelIndex();
}
QModelIndex XCursorThemeModel::defaultIndex () {
return findIndex(mDefaultName);
}
const QStringList XCursorThemeModel::searchPaths () {
if (!mBaseDirs.isEmpty()) return mBaseDirs;
// Get the search path from Xcursor
QString path = XcursorLibraryPath();
// Separate the paths
mBaseDirs = path.split(':', QString::SkipEmptyParts);
// Remove duplicates
QMutableStringListIterator i(mBaseDirs);
while (i.hasNext()) {
const QString path = i.next();
QMutableStringListIterator j(i);
while (j.hasNext()) if (j.next() == path) j.remove();
}
// Expand all occurrences of ~/ to the home dir
mBaseDirs.replaceInStrings(QRegExp("^~\\/"), QDir::home().path() + '/');
return mBaseDirs;
}
bool XCursorThemeModel::hasTheme (const QString &name) const {
const uint hash = qHash(name);
foreach (const XCursorThemeData *theme, mList) if (theme->hash() == hash) return true;
return false;
}
bool XCursorThemeModel::isCursorTheme (const QString &theme, const int depth) {
// Prevent infinite recursion
if (depth > 10) return false;
// Search each icon theme directory for 'theme'
foreach (const QString &baseDir, searchPaths()) {
QDir dir(baseDir);
if (!dir.exists() || !dir.cd(theme)) continue;
// If there's a cursors subdir, we'll assume this is a cursor theme
if (dir.exists("cursors")) return true;
// If the theme doesn't have an index.theme file, it can't inherit any themes
if (!dir.exists("index.theme")) continue;
// Open the index.theme file, so we can get the list of inherited themes
QMultiMap<QString, QString> cfg = loadCfgFile(dir.path()+"/index.theme", true);
QStringList inherits = cfg.values("icon theme/inherits");
// Recurse through the list of inherited themes, to check if one of them is a cursor theme
// note that items are reversed
for (int f = inherits.size()-1; f >= 0; f--) {
QString inh = inherits.at(f);
// Avoid possible DoS
if (inh == theme) continue;
if (isCursorTheme(inh, depth+1)) return true;
}
}
return false;
}
bool XCursorThemeModel::handleDefault (const QDir &themeDir) {
QFileInfo info(themeDir.path());
// If "default" is a symlink
if (info.isSymLink()) {
QFileInfo target(info.symLinkTarget());
if (target.exists() && (target.isDir() || target.isSymLink())) mDefaultName = target.fileName();
return true;
}
// If there's no cursors subdir, or if it's empty
if (!themeDir.exists("cursors") || QDir(themeDir.path() + "/cursors").entryList(QDir::Files | QDir::NoDotAndDotDot).isEmpty()) {
if (themeDir.exists("index.theme")) {
XCursorThemeData theme(themeDir);
if (!theme.inherits().isEmpty()) mDefaultName = theme.inherits().at(0);
}
return true;
}
mDefaultName = QLatin1String("default");
return false;
}
//#define DUMP_FOUND_THEMES
void XCursorThemeModel::processThemeDir (const QDir &themeDir) {
#ifdef DUMP_FOUND_THEMES
qDebug() << "looking at:" << themeDir.path();
#endif
bool haveCursors = themeDir.exists("cursors");
// Special case handling of "default", since it's usually either a
// symlink to another theme, or an empty theme that inherits another theme
if (mDefaultName.isNull() && themeDir.dirName() == "default") {
if (handleDefault(themeDir)) return;
}
// If the directory doesn't have a cursors subdir and lacks an
// index.theme file it can't be a cursor theme.
if (!themeDir.exists("index.theme") && !haveCursors) {
// qDebug() << "IS NOT THEME" << themeDir;
return;
}
// Create a cursor theme object for the theme dir
XCursorThemeData *theme = new XCursorThemeData(themeDir);
// Skip this theme if it's hidden
#ifdef DUMP_FOUND_THEMES
qDebug() <<
" theme name:" << theme->name() <<
"\n theme title:" << theme->title() <<
"\n theme desc:" << theme->description() <<
"\n theme sample:" << theme->sample() <<
"\n theme inherits:" << theme->inherits()
;
#endif
if (theme->isHidden()) {
// qDebug() << "HIDDEN THEME" << theme->name() << themeDir;
delete theme;
return;
}
// If there's no cursors subdirectory we'll do a recursive scan
// to check if the theme inherits a theme with one
if (!haveCursors) {
bool foundCursorTheme = false;
foreach (const QString &name, theme->inherits()) if ((foundCursorTheme = isCursorTheme(name))) break;
if (!foundCursorTheme) {
delete theme;
return;
}
}
// Append the theme to the list
mList.append(theme);
}
void XCursorThemeModel::insertThemes () {
// Scan each base dir for Xcursor themes and add them to the list
foreach (const QString &baseDir, searchPaths()) {
QDir dir(baseDir);
// qDebug() << "TOPLEVEL" << baseDir;
if (!dir.exists()) continue;
// qDebug() << " continue passed";
// Process each subdir in the directory
foreach (const QString &name, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Readable | QDir::Executable)) {
// qDebug() << " SUBDIR" << name;
// Don't process the theme if a theme with the same name already exists
// in the list. Xcursor will pick the first one it finds in that case,
// and since we use the same search order, the one Xcursor picks should
// be the one already in the list
if (hasTheme(name)) {
qDebug() << "duplicate theme:" << dir.path()+name;
}
if (!dir.cd(name)) {
qDebug() << "can't cd:" << dir.path()+name;
continue;
}
processThemeDir(dir);
dir.cdUp(); // Return to the base dir
}
}
// The theme Xcursor will end up using if no theme is configured
//if (mDefaultName.isNull() || !hasTheme(mDefaultName)) mDefaultName = legacy->name();
}
bool XCursorThemeModel::addTheme (const QDir &dir) {
XCursorThemeData *theme = new XCursorThemeData(dir);
// Don't add the theme to the list if it's hidden
if (theme->isHidden()) {
delete theme;
return false;
}
// If an item with the same name already exists in the list,
// we'll remove it before inserting the new one.
for (int i = 0; i < mList.count(); i++) {
if (mList.at(i)->hash() == theme->hash()) {
removeTheme(index(i, 0));
break;
}
}
// Append the theme to the list
beginInsertRows(QModelIndex(), rowCount(), rowCount());
mList.append(theme);
endInsertRows();
return true;
}
void XCursorThemeModel::removeTheme (const QModelIndex &index) {
if (!index.isValid()) return;
beginRemoveRows(QModelIndex(), index.row(), index.row());
delete mList.takeAt(index.row());
endRemoveRows();
}
|
add module names to includes
|
add module names to includes
|
C++
|
lgpl-2.1
|
masterweb121/lxqt-config,rbazaud/lxqt-config,zvacet/lxqt-config,ThomasVie/lxqt-config,smart2128/lxqt-config,rbazaud/lxqt-config,masterweb121/lxqt-config,gilir/lxqt-config,lxde/lxqt-config,stefonarch/lxqt-config,smart2128/lxqt-config,lxde/lxqt-config,jubalh/lxqt-config,rbazaud/lxqt-config,zvacet/lxqt-config,masterweb121/lxqt-config,stefonarch/lxqt-config,ThomasVie/lxqt-config,stefonarch/lxqt-config,lxde/lxqt-config,smart2128/lxqt-config,zvacet/lxqt-config,ThomasVie/lxqt-config,lxde/lxqt-config,gilir/lxqt-config,gilir/lxqt-config,jubalh/lxqt-config,jubalh/lxqt-config
|
ec34c97bf23e656ace9df49cc194758ce088ea58
|
tests/ut_devicelock/ut_devicelock.cpp
|
tests/ut_devicelock/ut_devicelock.cpp
|
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** Copyright (C) 2012 Jolla Ltd.
** Contact: Robin Burchell <[email protected]>
**
** This file is part of lipstick.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QTimer>
#include <QSettings>
#include "qmlocks_stub.h"
#include "qmactivity_stub.h"
#include "qmdisplaystate_stub.h"
#include "devicelock.h"
#include "ut_devicelock.h"
QVariant qSettingsValue;
QVariant QSettings::value(const QString &, const QVariant &) const
{
return qSettingsValue;
}
bool qProcessWaitForFinished = false;
bool QProcess::waitForFinished(int)
{
return qProcessWaitForFinished;
}
QString qProcessStartProgram;
QStringList qProcessStartArguments;
void QProcess::start(const QString &program, const QStringList &arguments, OpenMode)
{
qProcessStartProgram = program;
qProcessStartArguments = arguments;
}
int qProcessExitCode = 0;
int QProcess::exitCode() const
{
return qProcessExitCode;
}
QByteArray QProcess::readAllStandardError()
{
return QByteArray();
}
QByteArray QProcess::readAllStandardOutput()
{
return QByteArray();
}
QList<int> qTimerStartMsec;
void QTimer::start(int msec)
{
qTimerStartMsec.append(msec);
}
int qTimerStopCount = 0;
void QTimer::stop()
{
qTimerStopCount++;
}
void QTimer::singleShot(int, const QObject *receiver, const char *member)
{
// The "member" string is of form "1member()", so remove the trailing 1 and the ()
int memberLength = strlen(member) - 3;
char modifiedMember[memberLength + 1];
strncpy(modifiedMember, member + 1, memberLength);
modifiedMember[memberLength] = 0;
QMetaObject::invokeMethod(const_cast<QObject *>(receiver), modifiedMember, Qt::DirectConnection);
}
void Ut_DeviceLock::init()
{
qSettingsValue = "test";
qProcessStartProgram.clear();
qProcessStartArguments.clear();
qProcessWaitForFinished = true;
qProcessExitCode = 1;
deviceLock = new DeviceLock();
}
void Ut_DeviceLock::cleanup()
{
delete deviceLock;
qTimerStartMsec.clear();
qTimerStopCount = 0;
}
void Ut_DeviceLock::testSignalConnections()
{
QCOMPARE(disconnect(deviceLock->lockTimer, SIGNAL(timeout()), deviceLock, SLOT(lock())), true);
QCOMPARE(disconnect(deviceLock->qmActivity, SIGNAL(activityChanged(MeeGo::QmActivity::Activity)), deviceLock, SLOT(setStateAndSetupLockTimer())), true);
QCOMPARE(disconnect(deviceLock->qmLocks, SIGNAL(stateChanged(MeeGo::QmLocks::Lock,MeeGo::QmLocks::State)), deviceLock, SLOT(setStateAndSetupLockTimer())), true);
QCOMPARE(disconnect(deviceLock->qmDisplayState, SIGNAL(displayStateChanged(MeeGo::QmDisplayState::DisplayState)), deviceLock, SLOT(checkDisplayState(MeeGo::QmDisplayState::DisplayState))), true);
}
void Ut_DeviceLock::testInitialState()
{
delete deviceLock;
qSettingsValue.clear();
qProcessWaitForFinished = false;
qProcessExitCode = 0;
deviceLock = new DeviceLock();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Undefined);
delete deviceLock;
qSettingsValue = "-1";
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(qProcessStartProgram, qSettingsValue.toString());
QCOMPARE(qProcessStartArguments, QStringList() << "--is-set" << "lockcode");
delete deviceLock;
qProcessWaitForFinished = true;
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
delete deviceLock;
qProcessExitCode = 1;
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
}
void Ut_DeviceLock::testSetState()
{
QSignalSpy spy(deviceLock, SIGNAL(stateChanged(int)));
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(spy.count(), 2);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Unlocked);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(spy.count(), 2);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Unlocked);
}
void Ut_DeviceLock::testLockTimerWhenDeviceIsLocked()
{
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(qTimerStopCount, 1);
QCOMPARE(qTimerStartMsec.count(), 0);
}
Q_DECLARE_METATYPE(MeeGo::QmActivity::Activity)
void Ut_DeviceLock::testLockTimerWhenDeviceIsUnlocked_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmActivity::Activity>("activity");
QTest::addColumn<int>("stopCount");
QTest::addColumn<int>("startMSec");
QTest::newRow("Automatic locking disabled, active") << -1 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking immediate, active") << 0 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking in 5 minutes, active") << 5 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking disabled, inactive") << -1 << MeeGo::QmActivity::Inactive << 1 << 0;
QTest::newRow("Automatic locking immediate, inactive") << 0 << MeeGo::QmActivity::Inactive << 1 << 0;
QTest::newRow("Automatic locking in 5 minutes, inactive") << 5 << MeeGo::QmActivity::Inactive << 0 << (5 * 60 * 1000);
}
void Ut_DeviceLock::testLockTimerWhenDeviceIsUnlocked()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmActivity::Activity, activity);
QFETCH(int, stopCount);
QFETCH(int, startMSec);
deviceLock->setState(DeviceLock::Locked);
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->lockingDelay = lockingDelayValue;
gQmActivityStub->stubSetReturnValue("get", activity);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(qTimerStopCount, stopCount);
QCOMPARE(qTimerStartMsec.count(), startMSec > 0 ? 1 : 0);
}
Q_DECLARE_METATYPE(MeeGo::QmLocks::State)
Q_DECLARE_METATYPE(MeeGo::QmDisplayState::DisplayState)
Q_DECLARE_METATYPE(DeviceLock::LockState)
void Ut_DeviceLock::testDisplayStateWhenDeviceScreenIsLocked_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmDisplayState::DisplayState>("state");
QTest::addColumn<MeeGo::QmLocks::State>("touchScreenLockState");
QTest::addColumn<int>("stopCount");
QTest::addColumn<DeviceLock::LockState>("deviceLockState");
QTest::newRow("Automatic locking disabled, display on, screen unlocked")
<< -1 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Unlocked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display on, screen unlocked")
<< 0 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Unlocked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display on, screen locked")
<< 0 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Locked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display off, screen locked")
<< 0 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 1 << DeviceLock::Locked;
QTest::newRow("Automatic locking immediate, display off, screen unlocked")
<< 0 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Unlocked << 1 << DeviceLock::Locked;
QTest::newRow("Automatic locking in 5 minutes, display off, screen locked")
<< 5 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking disabled, display off, screen locked")
<< -1 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 1 << DeviceLock::Unlocked;
}
void Ut_DeviceLock::testDisplayStateWhenDeviceScreenIsLocked()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmDisplayState::DisplayState, state);
QFETCH(MeeGo::QmLocks::State, touchScreenLockState);
QFETCH(int, stopCount);
QFETCH(DeviceLock::LockState, deviceLockState);
deviceLock->setState(DeviceLock::Unlocked);
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->lockingDelay = lockingDelayValue;
gQmLocksStub->stubSetReturnValue("getState", touchScreenLockState);
gQmDisplayStateStub->stubSetReturnValue("get", state);
deviceLock->checkDisplayState(state);
QCOMPARE(deviceLock->state(), (int)deviceLockState);
QCOMPARE(qTimerStopCount, stopCount);
}
void Ut_DeviceLock::testLockTimerTimeout()
{
QSignalSpy spy(deviceLock, SIGNAL(stateChanged(int)));
deviceLock->lock();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
}
void Ut_DeviceLock::testStateOnAutomaticLockingAndTouchScreenLockState_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmLocks::State>("touchScreenLockState");
QTest::addColumn<DeviceLock::LockState>("deviceLockState");
QTest::newRow("Automatic locking disabled, touch screen lock unlocked") << -1 << MeeGo::QmLocks::Unlocked << DeviceLock::Unlocked;
}
void Ut_DeviceLock::testStateOnAutomaticLockingAndTouchScreenLockState()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmLocks::State, touchScreenLockState);
QFETCH(DeviceLock::LockState, deviceLockState);
deviceLock->setState(DeviceLock::Undefined);
deviceLock->lockingDelay = lockingDelayValue;
gQmLocksStub->stubSetReturnValue("getState", touchScreenLockState);
deviceLock->setStateAndSetupLockTimer();
QCOMPARE(deviceLock->state(), (int)deviceLockState);
}
QTEST_MAIN(Ut_DeviceLock)
|
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** Copyright (C) 2012 Jolla Ltd.
** Contact: Robin Burchell <[email protected]>
**
** This file is part of lipstick.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QTimer>
#include <QSettings>
#include "qmlocks_stub.h"
#include "qmactivity_stub.h"
#include "qmdisplaystate_stub.h"
#include "devicelock.h"
#include "ut_devicelock.h"
QVariant qSettingsValue;
QVariant QSettings::value(const QString &, const QVariant &) const
{
return qSettingsValue;
}
bool qProcessWaitForFinished = false;
bool QProcess::waitForFinished(int)
{
return qProcessWaitForFinished;
}
QString qProcessStartProgram;
QStringList qProcessStartArguments;
void QProcess::start(const QString &program, const QStringList &arguments, OpenMode)
{
qProcessStartProgram = program;
qProcessStartArguments = arguments;
}
int qProcessExitCode = 0;
int QProcess::exitCode() const
{
return qProcessExitCode;
}
QByteArray QProcess::readAllStandardError()
{
return QByteArray();
}
QByteArray QProcess::readAllStandardOutput()
{
return QByteArray();
}
QList<int> qTimerStartMsec;
void QTimer::start(int msec)
{
qTimerStartMsec.append(msec);
}
int qTimerStopCount = 0;
void QTimer::stop()
{
qTimerStopCount++;
}
void QTimer::singleShot(int, const QObject *receiver, const char *member)
{
// The "member" string is of form "1member()", so remove the trailing 1 and the ()
int memberLength = strlen(member) - 3;
char modifiedMember[memberLength + 1];
strncpy(modifiedMember, member + 1, memberLength);
modifiedMember[memberLength] = 0;
QMetaObject::invokeMethod(const_cast<QObject *>(receiver), modifiedMember, Qt::DirectConnection);
}
void Ut_DeviceLock::init()
{
qSettingsValue = "test";
qProcessStartProgram.clear();
qProcessStartArguments.clear();
qProcessWaitForFinished = true;
qProcessExitCode = 1;
deviceLock = new DeviceLock();
}
void Ut_DeviceLock::cleanup()
{
delete deviceLock;
qTimerStartMsec.clear();
qTimerStopCount = 0;
}
void Ut_DeviceLock::testSignalConnections()
{
QCOMPARE(disconnect(deviceLock->lockTimer, SIGNAL(timeout()), deviceLock, SLOT(lock())), true);
QCOMPARE(disconnect(deviceLock->qmActivity, SIGNAL(activityChanged(MeeGo::QmActivity::Activity)), deviceLock, SLOT(setStateAndSetupLockTimer())), true);
QCOMPARE(disconnect(deviceLock->qmLocks, SIGNAL(stateChanged(MeeGo::QmLocks::Lock,MeeGo::QmLocks::State)), deviceLock, SLOT(setStateAndSetupLockTimer())), true);
QCOMPARE(disconnect(deviceLock->qmDisplayState, SIGNAL(displayStateChanged(MeeGo::QmDisplayState::DisplayState)), deviceLock, SLOT(checkDisplayState(MeeGo::QmDisplayState::DisplayState))), true);
}
void Ut_DeviceLock::testInitialState()
{
delete deviceLock;
qSettingsValue.clear();
qProcessWaitForFinished = false;
qProcessExitCode = 0;
deviceLock = new DeviceLock();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Undefined);
delete deviceLock;
qSettingsValue = "-1";
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(qProcessStartProgram, qSettingsValue.toString());
QCOMPARE(qProcessStartArguments, QStringList() << "--is-set" << "lockcode");
delete deviceLock;
qProcessWaitForFinished = true;
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
delete deviceLock;
qProcessExitCode = 1;
deviceLock = new DeviceLock();
deviceLock->init();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
}
void Ut_DeviceLock::testSetState()
{
QSignalSpy spy(deviceLock, SIGNAL(stateChanged(int)));
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(spy.count(), 2);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Unlocked);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(deviceLock->state(), (int)DeviceLock::Unlocked);
QCOMPARE(spy.count(), 2);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Unlocked);
}
void Ut_DeviceLock::testLockTimerWhenDeviceIsLocked()
{
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->setState(DeviceLock::Locked);
QCOMPARE(qTimerStopCount, 1);
QCOMPARE(qTimerStartMsec.count(), 0);
}
Q_DECLARE_METATYPE(MeeGo::QmActivity::Activity)
void Ut_DeviceLock::testLockTimerWhenDeviceIsUnlocked_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmActivity::Activity>("activity");
QTest::addColumn<int>("stopCount");
QTest::addColumn<int>("startMSec");
QTest::newRow("Automatic locking disabled, active") << -1 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking immediate, active") << 0 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking in 5 minutes, active") << 5 << MeeGo::QmActivity::Active << 1 << 0;
QTest::newRow("Automatic locking disabled, inactive") << -1 << MeeGo::QmActivity::Inactive << 1 << 0;
QTest::newRow("Automatic locking immediate, inactive") << 0 << MeeGo::QmActivity::Inactive << 1 << 0;
QTest::newRow("Automatic locking in 5 minutes, inactive") << 5 << MeeGo::QmActivity::Inactive << 0 << (5 * 60 * 1000);
}
void Ut_DeviceLock::testLockTimerWhenDeviceIsUnlocked()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmActivity::Activity, activity);
QFETCH(int, stopCount);
QFETCH(int, startMSec);
deviceLock->setState(DeviceLock::Locked);
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->lockingDelay = lockingDelayValue;
gQmActivityStub->stubSetReturnValue("get", activity);
deviceLock->setState(DeviceLock::Unlocked);
QCOMPARE(qTimerStopCount, stopCount);
QCOMPARE(qTimerStartMsec.count(), startMSec > 0 ? 1 : 0);
}
Q_DECLARE_METATYPE(MeeGo::QmLocks::State)
Q_DECLARE_METATYPE(MeeGo::QmDisplayState::DisplayState)
Q_DECLARE_METATYPE(DeviceLock::LockState)
void Ut_DeviceLock::testDisplayStateWhenDeviceScreenIsLocked_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmDisplayState::DisplayState>("state");
QTest::addColumn<MeeGo::QmLocks::State>("touchScreenLockState");
QTest::addColumn<int>("stopCount");
QTest::addColumn<DeviceLock::LockState>("deviceLockState");
QTest::newRow("Automatic locking disabled, display on, screen unlocked")
<< -1 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Unlocked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display on, screen unlocked")
<< 0 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Unlocked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display on, screen locked")
<< 0 << MeeGo::QmDisplayState::DisplayState::On << MeeGo::QmLocks::Locked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking immediate, display off, screen locked")
<< 0 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 1 << DeviceLock::Locked;
QTest::newRow("Automatic locking immediate, display off, screen unlocked")
<< 0 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Unlocked << 1 << DeviceLock::Locked;
QTest::newRow("Automatic locking in 5 minutes, display off, screen locked")
<< 5 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 0 << DeviceLock::Unlocked;
QTest::newRow("Automatic locking disabled, display off, screen locked")
<< -1 << MeeGo::QmDisplayState::DisplayState::Off << MeeGo::QmLocks::Locked << 1 << DeviceLock::Unlocked;
}
void Ut_DeviceLock::testDisplayStateWhenDeviceScreenIsLocked()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmDisplayState::DisplayState, state);
QFETCH(MeeGo::QmLocks::State, touchScreenLockState);
QFETCH(int, stopCount);
QFETCH(DeviceLock::LockState, deviceLockState);
deviceLock->setState(DeviceLock::Unlocked);
qTimerStartMsec.clear();
qTimerStopCount = 0;
deviceLock->lockingDelay = lockingDelayValue;
gQmLocksStub->stubSetReturnValue("getState", touchScreenLockState);
gQmDisplayStateStub->stubSetReturnValue("get", state);
deviceLock->checkDisplayState(state);
QCOMPARE(deviceLock->state(), (int)deviceLockState);
QCOMPARE(qTimerStopCount, stopCount);
}
void Ut_DeviceLock::testLockTimerTimeout()
{
QSignalSpy spy(deviceLock, SIGNAL(stateChanged(int)));
deviceLock->lock();
QCOMPARE(deviceLock->state(), (int)DeviceLock::Locked);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().at(0).toInt(), (int)DeviceLock::Locked);
}
void Ut_DeviceLock::testStateOnAutomaticLockingAndTouchScreenLockState_data()
{
QTest::addColumn<int>("lockingDelayValue");
QTest::addColumn<MeeGo::QmLocks::State>("touchScreenLockState");
QTest::addColumn<DeviceLock::LockState>("deviceLockState");
QTest::newRow("Automatic locking disabled, touch screen lock unlocked") << -1 << MeeGo::QmLocks::Unlocked << DeviceLock::Unlocked;
}
void Ut_DeviceLock::testStateOnAutomaticLockingAndTouchScreenLockState()
{
QFETCH(int, lockingDelayValue);
QFETCH(MeeGo::QmLocks::State, touchScreenLockState);
QFETCH(DeviceLock::LockState, deviceLockState);
deviceLock->setState(DeviceLock::Locked);
deviceLock->lockingDelay = lockingDelayValue;
gQmLocksStub->stubSetReturnValue("getState", touchScreenLockState);
deviceLock->setStateAndSetupLockTimer();
QCOMPARE(deviceLock->state(), (int)deviceLockState);
}
QTEST_MAIN(Ut_DeviceLock)
|
Fix devicelock tests to correspond with latest changes
|
[lipstick] Fix devicelock tests to correspond with latest changes
|
C++
|
lgpl-2.1
|
giucam/lipstick,sletta/lipstick,pvuorela/lipstick,giucam/lipstick,pvuorela/lipstick,sletta/lipstick,pvuorela/lipstick,giucam/lipstick,sletta/lipstick
|
ebd028b1aa78452682a1126a51d9d783e8f9ea80
|
C++/range-sum-query-2d-mutable.cpp
|
C++/range-sum-query-2d-mutable.cpp
|
// Time: ctor: O(m * n),
// update: O(logm + logn),
// query: O(logm + logn)
// Space: O(m * n)
// Segment Tree solution.
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) {
if (!matrix.empty() && !matrix[0].empty()) {
const int m = matrix.size();
const int n = matrix[0].size();
root_ = buildHelper(matrix,
make_pair(0, 0),
make_pair(m - 1, n - 1));
}
}
void update(int row, int col, int val) {
if (matrix_[row][col] != val) {
matrix_[row][col] = val;
updateHelper(root_, make_pair(row, col), val);
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sumRangeHelper(root_, make_pair(row1, col1), make_pair(row2, col2));
}
private:
vector<vector<int>>& matrix_;
class SegmentTreeNode {
public:
pair<int, int> start, end;
int sum;
vector<SegmentTreeNode *> neighbor;
SegmentTreeNode(const pair<int, int>& i, const pair<int, int>& j, int s) :
start(i), end(j), sum(s) {
}
};
SegmentTreeNode *root_;
// Build segment tree.
SegmentTreeNode *buildHelper(const vector<vector<int>>& matrix,
const pair<int, int>& start,
const pair<int, int>& end) {
if (start.first > end.first || start.second > end.second) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeNode *root = new SegmentTreeNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = matrix[start.first][start.second];
return root;
}
int mid_x = (start.first + end.first) / 2;
int mid_y = (start.second + end.second) / 2;
root->neighbor.emplace_back(buildHelper(matrix, start, make_pair(mid_x, mid_y)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end));
for (auto& node : root->neighbor) {
if (node) {
root->sum += node->sum;
}
}
return root;
}
void updateHelper(SegmentTreeNode *root, const pair<int, int>& i, int val) {
// Out of range.
if (root == nullptr ||
(root->start.first > i.first || root->start.second > i.second) ||
(root->end.first < i.first || root->end.second < i.second)) {
return;
}
// Change the node's value with [i] to the new given value.
if ((root->start.first == i.first && root->start.second == i.second) &&
(root->end.first == i.first && root->end.second == i.second)) {
root->sum = val;
return;
}
for (auto& node : root->neighbor) {
updateHelper(node, i, val);
}
root->sum = 0;
for (auto& node : root->neighbor) {
if (node) {
root->sum += node->sum;
}
}
}
int sumRangeHelper(SegmentTreeNode *root, const pair<int, int>& start, const pair<int, int>& end) {
// Out of range.
if (root == nullptr ||
(root->start.first > end.first || root->start.second > end.second) ||
(root->end.first < start.first || root->end.second < start.second)) {
return 0;
}
// Current segment is totally within range [start, end]
if ((root->start.first >= start.first && root->start.second >= start.second) &&
(root->end.first <= end.first && root->end.second <= end.second)) {
return root->sum;
}
int sum = 0;
for (auto& node : root->neighbor) {
if (node) {
sum += sumRangeHelper(node, start, end);
}
}
return sum;
}
};
// Time: ctor: O(m * n)
// update: O(logm * logn)
// query: O(logm * logn)
// Space: O(m * n)
// Binary Indexed Tree (BIT) solution.
class NumMatrix2 {
public:
NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) {
if (matrix_.empty()) {
return;
}
bit_ = vector<vector<int>>(matrix_.size() + 1,
vector<int>(matrix_[0].size() + 1));
for (int i = 1; i < bit_.size(); ++i) {
for (int j = 1; j < bit_[0].size(); ++j) {
bit_[i][j] = matrix[i - 1][j - 1] + bit_[i - 1][j] +
bit_[i][j - 1] - bit_[i - 1][j - 1];
}
}
for (int i = bit_.size() - 1; i >= 1; --i) {
for (int j = bit_[0].size() - 1; j >= 1; --j) {
int last_i = i - (i & -i), last_j = j - (j & -j);
bit_[i][j] = bit_[i][j] - bit_[i][last_j] -
bit_[last_i][j] + bit_[last_i][last_j];
}
}
}
void update(int row, int col, int val) {
if (val - matrix_[row][col]) {
add(row, col, val - matrix_[row][col]);
matrix_[row][col] = val;
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sum(row2, col2) - sum(row2, col1 - 1) -
sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1);
}
private:
vector<vector<int>> &matrix_;
vector<vector<int>> bit_;
int sum(int row, int col) {
if (row < 0 || col < 0) {
return 0;
}
++row, ++col;
int sum = 0;
for (int i = row; i > 0; i -= lower_bit(i)) {
for (int j = col; j > 0; j -= lower_bit(j)) {
sum += bit_[i][j];
}
}
return sum;
}
void add(int row, int col, int val) {
++row, ++col;
for (int i = row; i <= matrix_.size(); i += lower_bit(i)) {
for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) {
bit_[i][j] += val;
}
}
}
int lower_bit(int i) {
return i & -i;
}
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.update(1, 1, 10);
// numMatrix.sumRegion(1, 2, 3, 4);
|
// Time: ctor: O(m * n),
// update: O(logm + logn),
// query: O(logm + logn)
// Space: O(m * n)
// Segment Tree solution.
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) {
if (!matrix.empty() && !matrix[0].empty()) {
const int m = matrix.size();
const int n = matrix[0].size();
root_ = buildHelper(matrix,
make_pair(0, 0),
make_pair(m - 1, n - 1));
}
}
void update(int row, int col, int val) {
if (matrix_[row][col] != val) {
matrix_[row][col] = val;
updateHelper(root_, make_pair(row, col), val);
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sumRangeHelper(root_, make_pair(row1, col1), make_pair(row2, col2));
}
private:
vector<vector<int>>& matrix_;
class SegmentTreeNode {
public:
pair<int, int> start, end;
int sum;
vector<SegmentTreeNode *> neighbor;
SegmentTreeNode(const pair<int, int>& i, const pair<int, int>& j, int s) :
start(i), end(j), sum(s) {
}
};
SegmentTreeNode *root_;
// Build segment tree.
SegmentTreeNode *buildHelper(const vector<vector<int>>& matrix,
const pair<int, int>& start,
const pair<int, int>& end) {
if (start.first > end.first || start.second > end.second) {
return nullptr;
}
// The root's start and end is given by build method.
SegmentTreeNode *root = new SegmentTreeNode(start, end, 0);
// If start equals to end, there will be no children for this node.
if (start == end) {
root->sum = matrix[start.first][start.second];
return root;
}
int mid_x = (start.first + end.first) / 2;
int mid_y = (start.second + end.second) / 2;
root->neighbor.emplace_back(buildHelper(matrix, start, make_pair(mid_x, mid_y)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(start.first, mid_y + 1), make_pair(mid_x, end.second)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, start.second), make_pair(end.first, mid_y)));
root->neighbor.emplace_back(buildHelper(matrix, make_pair(mid_x + 1, mid_y + 1), end));
for (auto& node : root->neighbor) {
if (node) {
root->sum += node->sum;
}
}
return root;
}
void updateHelper(SegmentTreeNode *root, const pair<int, int>& i, int val) {
// Out of range.
if (root == nullptr ||
(root->start.first > i.first || root->start.second > i.second) ||
(root->end.first < i.first || root->end.second < i.second)) {
return;
}
// Change the node's value with [i] to the new given value.
if ((root->start.first == i.first && root->start.second == i.second) &&
(root->end.first == i.first && root->end.second == i.second)) {
root->sum = val;
return;
}
for (auto& node : root->neighbor) {
updateHelper(node, i, val);
}
root->sum = 0;
for (auto& node : root->neighbor) {
if (node) {
root->sum += node->sum;
}
}
}
int sumRangeHelper(SegmentTreeNode *root, const pair<int, int>& start, const pair<int, int>& end) {
// Out of range.
if (root == nullptr ||
(root->start.first > end.first || root->start.second > end.second) ||
(root->end.first < start.first || root->end.second < start.second)) {
return 0;
}
// Current segment is totally within range [start, end]
if ((root->start.first >= start.first && root->start.second >= start.second) &&
(root->end.first <= end.first && root->end.second <= end.second)) {
return root->sum;
}
int sum = 0;
for (auto& node : root->neighbor) {
if (node) {
sum += sumRangeHelper(node, start, end);
}
}
return sum;
}
};
// Time: ctor: O(m * n)
// update: O(logm * logn)
// query: O(logm * logn)
// Space: O(m * n)
// Binary Indexed Tree (BIT) solution.
class NumMatrix2 {
public:
NumMatrix(vector<vector<int>> &matrix) : matrix_(matrix) {
if (matrix_.empty()) {
return;
}
bit_ = vector<vector<int>>(matrix_.size() + 1,
vector<int>(matrix_[0].size() + 1));
for (int i = 1; i < bit_.size(); ++i) {
for (int j = 1; j < bit_[0].size(); ++j) {
bit_[i][j] = matrix[i - 1][j - 1] + bit_[i - 1][j] +
bit_[i][j - 1] - bit_[i - 1][j - 1];
}
}
for (int i = bit_.size() - 1; i >= 1; --i) {
for (int j = bit_[0].size() - 1; j >= 1; --j) {
int last_i = i - lower_bit(i), last_j = j - lower_bit(j);
bit_[i][j] = bit_[i][j] - bit_[i][last_j] -
bit_[last_i][j] + bit_[last_i][last_j];
}
}
}
void update(int row, int col, int val) {
if (val - matrix_[row][col]) {
add(row, col, val - matrix_[row][col]);
matrix_[row][col] = val;
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sum(row2, col2) - sum(row2, col1 - 1) -
sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1);
}
private:
vector<vector<int>> &matrix_;
vector<vector<int>> bit_;
int sum(int row, int col) {
if (row < 0 || col < 0) {
return 0;
}
++row, ++col;
int sum = 0;
for (int i = row; i > 0; i -= lower_bit(i)) {
for (int j = col; j > 0; j -= lower_bit(j)) {
sum += bit_[i][j];
}
}
return sum;
}
void add(int row, int col, int val) {
++row, ++col;
for (int i = row; i <= matrix_.size(); i += lower_bit(i)) {
for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) {
bit_[i][j] += val;
}
}
}
int lower_bit(int i) {
return i & -i;
}
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.update(1, 1, 10);
// numMatrix.sumRegion(1, 2, 3, 4);
|
Update range-sum-query-2d-mutable.cpp
|
Update range-sum-query-2d-mutable.cpp
|
C++
|
mit
|
jaredkoontz/leetcode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,yiwen-luo/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode
|
228eea96a4d2862f33374866bb5bbd7fedf4ed8e
|
src/Hyperlink.cpp
|
src/Hyperlink.cpp
|
//
// BatchEncoder (Audio Conversion GUI)
// Copyright (C) 2005-2017 Wiesław Šoltés <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Hyperlink.h"
#include ".\hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Hyperlink.h"
#include ".\hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
|
Update Hyperlink.cpp
|
Update Hyperlink.cpp
|
C++
|
mit
|
wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder,wieslawsoltes/BatchEncoder
|
7a54dd4bef9a02273fe20e6745db8d17f3f5e192
|
opencog/reasoning/RuleEngine/rule-engine-src/JsonicControlPolicyParamLoader.cc
|
opencog/reasoning/RuleEngine/rule-engine-src/JsonicControlPolicyParamLoader.cc
|
/*
* JsonicControlPolicyLoader.cc
*
* Created on: 29 Dec, 2014
* Author: misgana
*/
#include "JsonicControlPolicyParamLoader.h"
#include "PolicyParams.h"
#include <fstream>
#include <lib/json_spirit/json_spirit.h>
#include <lib/json_spirit/json_spirit_stream_reader.h>
#include <opencog/guile/load-file.h>
#include <opencog/util/files.h>
#include <opencog/util/misc.h>
#include <opencog/util/Config.h>
JsonicControlPolicyParamLoader::JsonicControlPolicyParamLoader(AtomSpace * as,
string conf_path) :
ControlPolicyParamLoader(as, conf_path) {
cur_read_rule_ = NULL;
}
JsonicControlPolicyParamLoader::~JsonicControlPolicyParamLoader() {
}
void JsonicControlPolicyParamLoader::set_disjunct_rules(void) {
for (auto i = rule_mutex_map_.begin(); i != rule_mutex_map_.end(); ++i) {
auto mset = i->second;
auto cur_rule = i->first;
for (string name : mset) {
Rule* r = get_rule(name);
if (!r)
throw invalid_argument(
"A rule by name " + name + " doesn't exist"); //TODO throw appropriate exception
cur_rule->add_disjunct_rule(r);
}
}
}
Rule* JsonicControlPolicyParamLoader::get_rule(string& name) {
for (Rule* r : rules_) {
if (r->get_name() == name)
return r;
}
return NULL;
}
void JsonicControlPolicyParamLoader::load_config() {
try {
ifstream is(conf_path_);
Stream_reader<ifstream, Value> reader(is);
Value value;
while (reader.read_next(value))
read_json(value);
set_disjunct_rules();
} catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
}
void JsonicControlPolicyParamLoader::read_array(const Value &v, int lev) {
const Array& a = v.get_array();
for (Array::size_type i = 0; i < a.size(); ++i)
read_json(a[i], lev + 1);
}
void JsonicControlPolicyParamLoader::read_obj(const Value &v, int lev) {
const Object& o = v.get_obj();
for (Object::size_type i = 0; i < o.size(); ++i) {
const Pair& p = o[i];
auto key = p.name_;
Value value = p.value_;
if (key == RULES) {
read_json(value, lev + 1);
} else if (key == RULE_NAME) {
cur_read_rule_ = new Rule(Handle::UNDEFINED);
cur_read_rule_->set_name(value.get_value<string>());
rules_.push_back(cur_read_rule_); //xxx take care of pointers
} else if (key == FILE_PATH) {
load_scm_file_relative(*as_, value.get_value<string>(),
DEFAULT_MODULE_PATHS);
Handle rule_handle = scm_eval_->eval_h(cur_read_rule_->get_name());
cur_read_rule_->set_rule_handle(rule_handle);
} else if (key == PRIORITY) {
cur_read_rule_->set_cost(value.get_value<int>());
} else if (key == CATEGORY) {
cur_read_rule_->set_category(value.get_value<string>());
} else if (key == ATTENTION_ALLOC) {
attention_alloc_ = value.get_value<bool>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else if (key == MUTEX_RULES and value.type() != null_type) {
const Array& a = value.get_array();
for (Array::size_type i = 0; i < a.size(); ++i) {
rule_mutex_map_[cur_read_rule_].push_back(
a[i].get_value<string>());
}
} else if (key == MAX_ITER) {
max_iter_ = value.get_value<int>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else {
read_json(value, lev + 1);
}
}
}
void JsonicControlPolicyParamLoader::read_json(const Value &v,
int level /* = -1*/) {
switch (v.type()) {
case obj_type:
read_obj(v, level + 1);
break;
case array_type:
read_array(v, level + 1);
break;
case str_type:
break;
case bool_type:
break;
case int_type:
break;
case real_type:
break;
case null_type:
break;
default:
break;
}
}
void JsonicControlPolicyParamLoader::read_null(const Value &v, int lev) {
}
template<typename > void JsonicControlPolicyParamLoader::read_primitive(
const Value &v, int lev) {
}
|
/*
* JsonicControlPolicyLoader.cc
*
* Created on: 29 Dec, 2014
* Author: misgana
*/
#include "JsonicControlPolicyParamLoader.h"
#include "PolicyParams.h"
#include <fstream>
#include <lib/json_spirit/json_spirit.h>
#include <lib/json_spirit/json_spirit_stream_reader.h>
#include <opencog/guile/load-file.h>
#include <opencog/util/files.h>
#include <opencog/util/misc.h>
#include <opencog/util/Config.h>
JsonicControlPolicyParamLoader::JsonicControlPolicyParamLoader(AtomSpace * as,
string conf_path) :
ControlPolicyParamLoader(as, conf_path)
{
cur_read_rule_ = NULL;
}
JsonicControlPolicyParamLoader::~JsonicControlPolicyParamLoader()
{
}
void JsonicControlPolicyParamLoader::set_disjunct_rules(void)
{
for (auto i = rule_mutex_map_.begin(); i != rule_mutex_map_.end(); ++i) {
auto mset = i->second;
auto cur_rule = i->first;
for (string name : mset) {
Rule* r = get_rule(name);
if (!r)
throw invalid_argument(
"A rule by name " + name + " doesn't exist"); //TODO throw appropriate exception
cur_rule->add_disjunct_rule(r);
}
}
}
Rule* JsonicControlPolicyParamLoader::get_rule(string& name)
{
for (Rule* r : rules_) {
if (r->get_name() == name)
return r;
}
return NULL;
}
void JsonicControlPolicyParamLoader::load_config()
{
try {
ifstream is(conf_path_);
Stream_reader<ifstream, Value> reader(is);
Value value;
while (reader.read_next(value))
read_json(value);
set_disjunct_rules();
} catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
}
void JsonicControlPolicyParamLoader::read_array(const Value &v, int lev)
{
const Array& a = v.get_array();
for (Array::size_type i = 0; i < a.size(); ++i)
read_json(a[i], lev + 1);
}
void JsonicControlPolicyParamLoader::read_obj(const Value &v, int lev)
{
const Object& o = v.get_obj();
for (Object::size_type i = 0; i < o.size(); ++i) {
const Pair& p = o[i];
auto key = p.name_;
Value value = p.value_;
if (key == RULES) {
read_json(value, lev + 1);
} else if (key == RULE_NAME) {
cur_read_rule_ = new Rule(Handle::UNDEFINED);
cur_read_rule_->set_name(value.get_value<string>());
rules_.push_back(cur_read_rule_); //xxx take care of pointers
} else if (key == FILE_PATH) {
load_scm_file_relative(*as_, value.get_value<string>(),
DEFAULT_MODULE_PATHS);
Handle rule_handle = scm_eval_->eval_h(cur_read_rule_->get_name());
cur_read_rule_->set_rule_handle(rule_handle);
} else if (key == PRIORITY) {
cur_read_rule_->set_cost(value.get_value<int>());
} else if (key == CATEGORY) {
cur_read_rule_->set_category(value.get_value<string>());
} else if (key == ATTENTION_ALLOC) {
attention_alloc_ = value.get_value<bool>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else if (key == MUTEX_RULES and value.type() != null_type) {
const Array& a = value.get_array();
for (Array::size_type i = 0; i < a.size(); ++i) {
rule_mutex_map_[cur_read_rule_].push_back(
a[i].get_value<string>());
}
} else if (key == MAX_ITER) {
max_iter_ = value.get_value<int>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else {
read_json(value, lev + 1);
}
}
}
void JsonicControlPolicyParamLoader::read_json(const Value &v,
int level /* = -1*/)
{
switch (v.type()) {
case obj_type:
read_obj(v, level + 1);
break;
case array_type:
read_array(v, level + 1);
break;
case str_type:
break;
case bool_type:
break;
case int_type:
break;
case real_type:
break;
case null_type:
break;
default:
break;
}
}
void JsonicControlPolicyParamLoader::read_null(const Value &v, int lev)
{
}
template<typename > void JsonicControlPolicyParamLoader::read_primitive(
const Value &v, int lev)
{
}
|
Fix whitespace
|
Fix whitespace
|
C++
|
agpl-3.0
|
kinoc/opencog,inflector/opencog,misgeatgit/opencog,roselleebarle04/opencog,AmeBel/atomspace,kinoc/opencog,rTreutlein/atomspace,Selameab/atomspace,ruiting/opencog,gavrieltal/opencog,AmeBel/opencog,misgeatgit/opencog,printedheart/opencog,jlegendary/opencog,ceefour/opencog,jlegendary/opencog,yantrabuddhi/opencog,iAMr00t/opencog,Selameab/opencog,misgeatgit/atomspace,yantrabuddhi/opencog,prateeksaxena2809/opencog,inflector/atomspace,williampma/opencog,gavrieltal/opencog,virneo/opencog,misgeatgit/opencog,misgeatgit/atomspace,printedheart/opencog,williampma/opencog,kim135797531/opencog,rohit12/opencog,inflector/opencog,AmeBel/opencog,ruiting/opencog,anitzkin/opencog,kinoc/opencog,AmeBel/opencog,Tiggels/opencog,cosmoharrigan/opencog,iAMr00t/opencog,eddiemonroe/opencog,Selameab/opencog,Allend575/opencog,inflector/opencog,rodsol/opencog,rTreutlein/atomspace,tim777z/opencog,yantrabuddhi/opencog,printedheart/opencog,cosmoharrigan/opencog,kinoc/opencog,Tiggels/opencog,prateeksaxena2809/opencog,eddiemonroe/atomspace,UIKit0/atomspace,gavrieltal/opencog,sanuj/opencog,anitzkin/opencog,UIKit0/atomspace,rohit12/atomspace,AmeBel/opencog,cosmoharrigan/atomspace,ceefour/opencog,rodsol/opencog,kim135797531/opencog,ruiting/opencog,rodsol/atomspace,TheNameIsNigel/opencog,anitzkin/opencog,shujingke/opencog,printedheart/opencog,kinoc/opencog,gavrieltal/opencog,rodsol/atomspace,ruiting/opencog,jswiergo/atomspace,kim135797531/opencog,eddiemonroe/atomspace,eddiemonroe/opencog,rohit12/atomspace,roselleebarle04/opencog,andre-senna/opencog,gavrieltal/opencog,misgeatgit/opencog,ceefour/opencog,iAMr00t/opencog,jlegendary/opencog,inflector/opencog,shujingke/opencog,roselleebarle04/opencog,Selameab/opencog,MarcosPividori/atomspace,gavrieltal/opencog,Selameab/opencog,Selameab/atomspace,sumitsourabh/opencog,prateeksaxena2809/opencog,rohit12/opencog,rodsol/opencog,rTreutlein/atomspace,shujingke/opencog,anitzkin/opencog,shujingke/opencog,iAMr00t/opencog,eddiemonroe/opencog,printedheart/atomspace,UIKit0/atomspace,Selameab/opencog,rodsol/atomspace,williampma/opencog,ArvinPan/atomspace,misgeatgit/atomspace,rohit12/atomspace,Allend575/opencog,prateeksaxena2809/opencog,Allend575/opencog,williampma/opencog,williampma/atomspace,williampma/opencog,yantrabuddhi/atomspace,andre-senna/opencog,misgeatgit/opencog,williampma/atomspace,yantrabuddhi/opencog,andre-senna/opencog,Allend575/opencog,tim777z/opencog,virneo/atomspace,AmeBel/atomspace,shujingke/opencog,ruiting/opencog,sumitsourabh/opencog,sumitsourabh/opencog,sumitsourabh/opencog,rTreutlein/atomspace,virneo/opencog,AmeBel/opencog,misgeatgit/atomspace,yantrabuddhi/opencog,iAMr00t/opencog,virneo/atomspace,ceefour/opencog,anitzkin/opencog,roselleebarle04/opencog,eddiemonroe/atomspace,jswiergo/atomspace,AmeBel/opencog,eddiemonroe/opencog,misgeatgit/opencog,MarcosPividori/atomspace,andre-senna/opencog,inflector/opencog,andre-senna/opencog,rohit12/opencog,roselleebarle04/opencog,eddiemonroe/opencog,ArvinPan/opencog,kim135797531/opencog,yantrabuddhi/opencog,rohit12/opencog,tim777z/opencog,misgeatgit/opencog,Selameab/opencog,virneo/opencog,rodsol/opencog,eddiemonroe/opencog,ceefour/atomspace,inflector/opencog,williampma/opencog,prateeksaxena2809/opencog,cosmoharrigan/opencog,andre-senna/opencog,rohit12/opencog,tim777z/opencog,shujingke/opencog,ArvinPan/atomspace,jswiergo/atomspace,ArvinPan/opencog,rohit12/atomspace,Tiggels/opencog,ArvinPan/atomspace,Allend575/opencog,ceefour/opencog,yantrabuddhi/atomspace,eddiemonroe/atomspace,ceefour/opencog,sumitsourabh/opencog,yantrabuddhi/atomspace,misgeatgit/atomspace,ceefour/opencog,misgeatgit/opencog,rodsol/atomspace,kinoc/opencog,MarcosPividori/atomspace,inflector/atomspace,inflector/opencog,Tiggels/opencog,inflector/atomspace,rodsol/opencog,printedheart/atomspace,printedheart/atomspace,rTreutlein/atomspace,sanuj/opencog,cosmoharrigan/opencog,sumitsourabh/opencog,cosmoharrigan/atomspace,rohit12/opencog,ceefour/atomspace,ArvinPan/opencog,MarcosPividori/atomspace,sanuj/opencog,kinoc/opencog,virneo/atomspace,virneo/opencog,TheNameIsNigel/opencog,cosmoharrigan/opencog,printedheart/opencog,eddiemonroe/atomspace,williampma/atomspace,roselleebarle04/opencog,Selameab/atomspace,AmeBel/atomspace,rodsol/opencog,TheNameIsNigel/opencog,kim135797531/opencog,jlegendary/opencog,cosmoharrigan/atomspace,jswiergo/atomspace,UIKit0/atomspace,andre-senna/opencog,gavrieltal/opencog,AmeBel/atomspace,ceefour/atomspace,Allend575/opencog,prateeksaxena2809/opencog,sanuj/opencog,roselleebarle04/opencog,tim777z/opencog,ruiting/opencog,Selameab/atomspace,ruiting/opencog,misgeatgit/opencog,TheNameIsNigel/opencog,inflector/atomspace,yantrabuddhi/atomspace,virneo/opencog,AmeBel/opencog,sumitsourabh/opencog,printedheart/opencog,kim135797531/opencog,iAMr00t/opencog,cosmoharrigan/opencog,yantrabuddhi/atomspace,ceefour/atomspace,TheNameIsNigel/opencog,sanuj/opencog,yantrabuddhi/opencog,inflector/opencog,Tiggels/opencog,ArvinPan/opencog,virneo/atomspace,virneo/opencog,anitzkin/opencog,Allend575/opencog,AmeBel/atomspace,anitzkin/opencog,jlegendary/opencog,cosmoharrigan/atomspace,jlegendary/opencog,ArvinPan/opencog,virneo/opencog,jlegendary/opencog,TheNameIsNigel/opencog,ArvinPan/opencog,prateeksaxena2809/opencog,kim135797531/opencog,shujingke/opencog,eddiemonroe/opencog,printedheart/atomspace,Tiggels/opencog,ArvinPan/atomspace,inflector/atomspace,williampma/atomspace,sanuj/opencog,tim777z/opencog
|
7eb08a5a483a1a2dee01c7f0b7d4da40b5e53cfb
|
src/Interface.hpp
|
src/Interface.hpp
|
#include "trainer.hpp" //includes the Trainer Class
#include <stdio.h> //Includes stidio functions
#include <string> //Includes std::string functions
class Interface //Used to connect the user to the program itself.
{
private:
bool opened; //used for the while loop
std::string input; //user input when chosing a cheat type
public:
Trainer trainer; //The trainer class
void Start(); //Starts the program
void ShowMenu(); //Shows the menu, next release it will be something like ShowUI();
int ProcessInput(); //Process the user input
void Close(); //Close the program
bool IsOpen(); //Returns the value of the opened variable
};
|
#pragma once
#include "trainer.hpp" //includes the Trainer Class
#include <stdio.h> //Includes stidio functions
#include <string> //Includes std::string functions
class Interface //Used to connect the user to the program itself.
{
private:
bool opened; //used for the while loop
std::string input; //user input when chosing a cheat type
public:
Trainer trainer; //The trainer class
void Start(); //Starts the program
void ShowMenu(); //Shows the menu, next release it will be something like ShowUI();
int ProcessInput(); //Process the user input
void Close(); //Close the program
bool IsOpen(); //Returns the value of the opened variable
};
|
Update Interface.hpp
|
Update Interface.hpp
|
C++
|
mit
|
RebeloX/TrainerX
|
9ca97158a7297fbdcf86635adf81feb2a3385055
|
wrappers/trace.cpp
|
wrappers/trace.cpp
|
/**************************************************************************
*
* Copyright 2010-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef ANDROID
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/system_properties.h>
#endif
#include "os.hpp"
#include "os_string.hpp"
#include "trace.hpp"
namespace trace {
#ifdef ANDROID
static bool
isZygoteProcess(void)
{
os::String proc_name;
proc_name = os::getProcessName();
proc_name.trimDirectory();
return strcmp(proc_name, "app_process") == 0;
}
static os::String
getZygoteProcessName(void)
{
os::String path;
size_t size = PATH_MAX;
char *buf = path.buf(size);
ssize_t len;
int fd = open("/proc/self/cmdline", O_RDONLY);
assert(fd >= 0);
len = read(fd, buf, size - 1);
close(fd);
path.truncate(len);
return path;
}
bool
isTracingEnabled(void)
{
static pid_t cached_pid;
static bool enabled;
pid_t pid;
pid = getpid();
if (cached_pid == pid)
return enabled;
cached_pid = pid;
if (!isZygoteProcess()) {
os::log("apitrace[%d]: enabled for standalone %s",
pid, (const char *)os::getProcessName());
enabled = true;
return true;
}
char target_proc_name[PROP_VALUE_MAX] = "";
os::String proc_name;
proc_name = getZygoteProcessName();
proc_name.trimDirectory();
__system_property_get("debug.apitrace.procname", target_proc_name);
enabled = !strcmp(target_proc_name, proc_name);
os::log("apitrace[%d]: %s for %s",
pid, enabled ? "enabled" : "disabled", (const char *)proc_name);
return enabled;
}
#endif /* ANDROID */
} /* namespace trace */
|
/**************************************************************************
*
* Copyright 2010-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef ANDROID
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/system_properties.h>
#endif
#include "os.hpp"
#include "os_string.hpp"
#include "trace.hpp"
namespace trace {
#ifdef ANDROID
static bool
isZygoteProcess(void)
{
os::String proc_name;
proc_name = os::getProcessName();
proc_name.trimDirectory();
return strcmp(proc_name, "app_process") == 0;
}
static os::String
getZygoteProcessName(void)
{
os::String path;
size_t size = PATH_MAX;
char *buf = path.buf(size);
ssize_t len;
int fd = open("/proc/self/cmdline", O_RDONLY);
assert(fd >= 0);
len = read(fd, buf, size - 1);
close(fd);
path.truncate(len);
return path;
}
bool
isTracingEnabled(void)
{
static pid_t cached_pid;
static bool enabled;
pid_t pid;
pid = getpid();
if (cached_pid == pid)
return enabled;
cached_pid = pid;
if (!isZygoteProcess()) {
os::log("apitrace[%d]: enabled for standalone %s",
pid, (const char *)os::getProcessName());
enabled = true;
return true;
}
char target_proc_name[PROP_VALUE_MAX] = "";
os::String proc_name;
proc_name = getZygoteProcessName();
__system_property_get("debug.apitrace.procname", target_proc_name);
enabled = !strcmp(target_proc_name, proc_name);
os::log("apitrace[%d]: %s for %s",
pid, enabled ? "enabled" : "disabled", (const char *)proc_name);
return enabled;
}
#endif /* ANDROID */
} /* namespace trace */
|
Fix tracing Zygote processes (v2)
|
egltrace/android: Fix tracing Zygote processes (v2)
Fixes egltrace.so on Android 4.2 x86.
Do not call trimDirectory() on the proc_name of Zygote processes, because
a Zyogote process name never contains a path separator. The proc_name of
a Zygote process is the application's package name (such as
com.exampe.myapp) because ActivityManager rewrites argv[0].
There exists an undiagnosed problem with trimDirectory, but I have been
unsuccessful diagnosing it. On the other hand, the call to trimDirectory
isn't needed and its removal fixes the bug's symptoms.
Signed-off-by: Chad Versace <[email protected]>
|
C++
|
mit
|
tuanthng/apitrace,trtt/apitrace,schulmar/apitrace,schulmar/apitrace,tuanthng/apitrace,surround-io/apitrace,tuanthng/apitrace,tuanthng/apitrace,trtt/apitrace,schulmar/apitrace,joshua5201/apitrace,EoD/apitrace,trtt/apitrace,tuanthng/apitrace,apitrace/apitrace,swq0553/apitrace,trtt/apitrace,schulmar/apitrace,EoD/apitrace,joshua5201/apitrace,apitrace/apitrace,schulmar/apitrace,apitrace/apitrace,trtt/apitrace,joshua5201/apitrace,surround-io/apitrace,EoD/apitrace,surround-io/apitrace,joshua5201/apitrace,EoD/apitrace,swq0553/apitrace,EoD/apitrace,surround-io/apitrace,swq0553/apitrace,surround-io/apitrace,apitrace/apitrace,swq0553/apitrace,joshua5201/apitrace,swq0553/apitrace
|
ab56043adb9e3933500342ac8fbfc6197122f9cf
|
src/MeshGroup.cpp
|
src/MeshGroup.cpp
|
//Copyright (C) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <string.h>
#include <stdio.h>
#include <limits>
#include "MeshGroup.h"
#include "utils/floatpoint.h"
#include "utils/gettime.h"
#include "utils/logoutput.h"
#include "utils/string.h"
namespace cura
{
FILE* binaryMeshBlob = nullptr;
/* Custom fgets function to support Mac line-ends in Ascii STL files. OpenSCAD produces this when used on Mac */
void* fgets_(char* ptr, size_t len, FILE* f)
{
while(len && fread(ptr, 1, 1, f) > 0)
{
if (*ptr == '\n' || *ptr == '\r')
{
*ptr = '\0';
return ptr;
}
ptr++;
len--;
}
return nullptr;
}
Point3 MeshGroup::min() const
{
if (meshes.size() < 1)
{
return Point3(0, 0, 0);
}
Point3 ret(std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max());
for (const Mesh& mesh : meshes)
{
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("cutting_mesh") || mesh.settings.get<bool>("anti_overhang_mesh")) //Don't count pieces that are not printed.
{
continue;
}
Point3 v = mesh.min();
ret.x = std::min(ret.x, v.x);
ret.y = std::min(ret.y, v.y);
ret.z = std::min(ret.z, v.z);
}
return ret;
}
Point3 MeshGroup::max() const
{
if (meshes.size() < 1)
{
return Point3(0, 0, 0);
}
Point3 ret(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min());
for (const Mesh& mesh : meshes)
{
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("cutting_mesh") || mesh.settings.get<bool>("anti_overhang_mesh")) //Don't count pieces that are not printed.
{
continue;
}
Point3 v = mesh.max();
ret.x = std::max(ret.x, v.x);
ret.y = std::max(ret.y, v.y);
ret.z = std::max(ret.z, v.z);
}
return ret;
}
void MeshGroup::clear()
{
for(Mesh& m : meshes)
{
m.clear();
}
}
void MeshGroup::finalize()
{
//If the machine settings have been supplied, offset the given position vertices to the center of vertices (0,0,0) is at the bed center.
Point3 meshgroup_offset(0, 0, 0);
if (!settings.get<bool>("machine_center_is_zero"))
{
meshgroup_offset.x = settings.get<coord_t>("machine_width") / 2;
meshgroup_offset.y = settings.get<coord_t>("machine_depth") / 2;
}
// If a mesh position was given, put the mesh at this position in 3D space.
for(Mesh& mesh : meshes)
{
Point3 mesh_offset(mesh.settings.get<coord_t>("mesh_position_x"), mesh.settings.get<coord_t>("mesh_position_y"), mesh.settings.get<coord_t>("mesh_position_z"));
if (mesh.settings.get<bool>("center_object"))
{
Point3 object_min = mesh.min();
Point3 object_max = mesh.max();
Point3 object_size = object_max - object_min;
mesh_offset += Point3(-object_min.x - object_size.x / 2, -object_min.y - object_size.y / 2, -object_min.z);
}
mesh.offset(mesh_offset + meshgroup_offset);
}
}
bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "rt");
char buffer[1024];
FPoint3 vertex;
int n = 0;
Point3 v0(0,0,0), v1(0,0,0), v2(0,0,0);
while(fgets_(buffer, sizeof(buffer), f))
{
if (sscanf(buffer, " vertex %f %f %f", &vertex.x, &vertex.y, &vertex.z) == 3)
{
n++;
switch(n)
{
case 1:
v0 = matrix.apply(vertex);
break;
case 2:
v1 = matrix.apply(vertex);
break;
case 3:
v2 = matrix.apply(vertex);
mesh->addFace(v0, v1, v2);
n = 0;
break;
}
}
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "rb");
fseek(f, 0L, SEEK_END);
long long file_size = ftell(f); //The file size is the position of the cursor after seeking to the end.
rewind(f); //Seek back to start.
size_t face_count = (file_size - 80 - sizeof(uint32_t)) / 50; //Subtract the size of the header. Every face uses exactly 50 bytes.
char buffer[80];
//Skip the header
if (fread(buffer, 80, 1, f) != 1)
{
fclose(f);
return false;
}
uint32_t reported_face_count;
//Read the face count. We'll use it as a sort of redundancy code to check for file corruption.
if (fread(&reported_face_count, sizeof(uint32_t), 1, f) != 1)
{
fclose(f);
return false;
}
if (reported_face_count != face_count)
{
logWarning("Face count reported by file (%s) is not equal to actual face count (%s). File could be corrupt!\n", std::to_string(reported_face_count).c_str(), std::to_string(face_count).c_str());
}
//For each face read:
//float(x,y,z) = normal, float(X,Y,Z)*3 = vertexes, uint16_t = flags
// Every Face is 50 Bytes: Normal(3*float), Vertices(9*float), 2 Bytes Spacer
mesh->faces.reserve(face_count);
mesh->vertices.reserve(face_count);
for (unsigned int i = 0; i < face_count; i++)
{
if (fread(buffer, 50, 1, f) != 1)
{
fclose(f);
return false;
}
float *v= ((float*)buffer)+3;
Point3 v0 = matrix.apply(FPoint3(v[0], v[1], v[2]));
Point3 v1 = matrix.apply(FPoint3(v[3], v[4], v[5]));
Point3 v2 = matrix.apply(FPoint3(v[6], v[7], v[8]));
mesh->addFace(v0, v1, v2);
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "r");
if (f == nullptr)
{
return false;
}
//assign filename to mesh_name
mesh->mesh_name = filename;
//Skip any whitespace at the beginning of the file.
unsigned long long num_whitespace = 0; //Number of whitespace characters.
unsigned char whitespace;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
while(isspace(whitespace))
{
num_whitespace++;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
}
fseek(f, num_whitespace, SEEK_SET); //Seek to the place after all whitespace (we may have just read too far).
char buffer[6];
if (fread(buffer, 5, 1, f) != 1)
{
fclose(f);
return false;
}
fclose(f);
buffer[5] = '\0';
if (stringcasecompare(buffer, "solid") == 0)
{
bool load_success = loadMeshSTL_ascii(mesh, filename, matrix);
if (!load_success)
return false;
// This logic is used to handle the case where the file starts with
// "solid" but is a binary file.
if (mesh->faces.size() < 1)
{
mesh->clear();
return loadMeshSTL_binary(mesh, filename, matrix);
}
return true;
}
return loadMeshSTL_binary(mesh, filename, matrix);
}
bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const FMatrix3x3& transformation, Settings& object_parent_settings)
{
TimeKeeper load_timer;
const char* ext = strrchr(filename, '.');
if (ext && (strcmp(ext, ".stl") == 0 || strcmp(ext, ".STL") == 0))
{
Mesh mesh(object_parent_settings);
if (loadMeshSTL(&mesh, filename, transformation)) //Load it! If successful...
{
meshgroup->meshes.push_back(mesh);
log("loading '%s' took %.3f seconds\n", filename, load_timer.restart());
return true;
}
}
return false;
}
}//namespace cura
|
//Copyright (C) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <string.h>
#include <stdio.h>
#include <limits>
#include "MeshGroup.h"
#include "utils/floatpoint.h"
#include "utils/gettime.h"
#include "utils/logoutput.h"
#include "utils/string.h"
namespace cura
{
FILE* binaryMeshBlob = nullptr;
/* Custom fgets function to support Mac line-ends in Ascii STL files. OpenSCAD produces this when used on Mac */
void* fgets_(char* ptr, size_t len, FILE* f)
{
while(len && fread(ptr, 1, 1, f) > 0)
{
if (*ptr == '\n' || *ptr == '\r')
{
*ptr = '\0';
return ptr;
}
ptr++;
len--;
}
return nullptr;
}
Point3 MeshGroup::min() const
{
if (meshes.size() < 1)
{
return Point3(0, 0, 0);
}
Point3 ret(std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max());
for (const Mesh& mesh : meshes)
{
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("cutting_mesh") || mesh.settings.get<bool>("anti_overhang_mesh")) //Don't count pieces that are not printed.
{
continue;
}
Point3 v = mesh.min();
ret.x = std::min(ret.x, v.x);
ret.y = std::min(ret.y, v.y);
ret.z = std::min(ret.z, v.z);
}
return ret;
}
Point3 MeshGroup::max() const
{
if (meshes.size() < 1)
{
return Point3(0, 0, 0);
}
Point3 ret(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min());
for (const Mesh& mesh : meshes)
{
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("cutting_mesh") || mesh.settings.get<bool>("anti_overhang_mesh")) //Don't count pieces that are not printed.
{
continue;
}
Point3 v = mesh.max();
ret.x = std::max(ret.x, v.x);
ret.y = std::max(ret.y, v.y);
ret.z = std::max(ret.z, v.z);
}
return ret;
}
void MeshGroup::clear()
{
for(Mesh& m : meshes)
{
m.clear();
}
}
void MeshGroup::finalize()
{
//If the machine settings have been supplied, offset the given position vertices to the center of vertices (0,0,0) is at the bed center.
Point3 meshgroup_offset(0, 0, 0);
if (!settings.get<bool>("machine_center_is_zero"))
{
meshgroup_offset.x = settings.get<coord_t>("machine_width") / 2;
meshgroup_offset.y = settings.get<coord_t>("machine_depth") / 2;
}
// If a mesh position was given, put the mesh at this position in 3D space.
for(Mesh& mesh : meshes)
{
Point3 mesh_offset(mesh.settings.get<coord_t>("mesh_position_x"), mesh.settings.get<coord_t>("mesh_position_y"), mesh.settings.get<coord_t>("mesh_position_z"));
if (mesh.settings.get<bool>("center_object"))
{
Point3 object_min = mesh.min();
Point3 object_max = mesh.max();
Point3 object_size = object_max - object_min;
mesh_offset += Point3(-object_min.x - object_size.x / 2, -object_min.y - object_size.y / 2, -object_min.z);
}
mesh.offset(mesh_offset + meshgroup_offset);
}
}
bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "rt");
char buffer[1024];
FPoint3 vertex;
int n = 0;
Point3 v0(0,0,0), v1(0,0,0), v2(0,0,0);
while(fgets_(buffer, sizeof(buffer), f))
{
if (sscanf(buffer, " vertex %f %f %f", &vertex.x, &vertex.y, &vertex.z) == 3)
{
n++;
switch(n)
{
case 1:
v0 = matrix.apply(vertex);
break;
case 2:
v1 = matrix.apply(vertex);
break;
case 3:
v2 = matrix.apply(vertex);
mesh->addFace(v0, v1, v2);
n = 0;
break;
}
}
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "rb");
fseek(f, 0L, SEEK_END);
long long file_size = ftell(f); //The file size is the position of the cursor after seeking to the end.
rewind(f); //Seek back to start.
size_t face_count = (file_size - 80 - sizeof(uint32_t)) / 50; //Subtract the size of the header. Every face uses exactly 50 bytes.
char buffer[80];
//Skip the header
if (fread(buffer, 80, 1, f) != 1)
{
fclose(f);
return false;
}
uint32_t reported_face_count;
//Read the face count. We'll use it as a sort of redundancy code to check for file corruption.
if (fread(&reported_face_count, sizeof(uint32_t), 1, f) != 1)
{
fclose(f);
return false;
}
if (reported_face_count != face_count)
{
logWarning("Face count reported by file (%s) is not equal to actual face count (%s). File could be corrupt!\n", std::to_string(reported_face_count).c_str(), std::to_string(face_count).c_str());
}
//For each face read:
//float(x,y,z) = normal, float(X,Y,Z)*3 = vertexes, uint16_t = flags
// Every Face is 50 Bytes: Normal(3*float), Vertices(9*float), 2 Bytes Spacer
mesh->faces.reserve(face_count);
mesh->vertices.reserve(face_count);
for (unsigned int i = 0; i < face_count; i++)
{
if (fread(buffer, 50, 1, f) != 1)
{
fclose(f);
return false;
}
float *v= ((float*)buffer)+3;
Point3 v0 = matrix.apply(FPoint3(v[0], v[1], v[2]));
Point3 v1 = matrix.apply(FPoint3(v[3], v[4], v[5]));
Point3 v2 = matrix.apply(FPoint3(v[6], v[7], v[8]));
mesh->addFace(v0, v1, v2);
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix3x3& matrix)
{
FILE* f = fopen(filename, "rb");
if (f == nullptr)
{
return false;
}
//assign filename to mesh_name
mesh->mesh_name = filename;
//Skip any whitespace at the beginning of the file.
unsigned long long num_whitespace = 0; //Number of whitespace characters.
unsigned char whitespace;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
while(isspace(whitespace))
{
num_whitespace++;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
}
fseek(f, num_whitespace, SEEK_SET); //Seek to the place after all whitespace (we may have just read too far).
char buffer[6];
if (fread(buffer, 5, 1, f) != 1)
{
fclose(f);
return false;
}
fclose(f);
buffer[5] = '\0';
if (stringcasecompare(buffer, "solid") == 0)
{
bool load_success = loadMeshSTL_ascii(mesh, filename, matrix);
if (!load_success)
return false;
// This logic is used to handle the case where the file starts with
// "solid" but is a binary file.
if (mesh->faces.size() < 1)
{
mesh->clear();
return loadMeshSTL_binary(mesh, filename, matrix);
}
return true;
}
return loadMeshSTL_binary(mesh, filename, matrix);
}
bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const FMatrix3x3& transformation, Settings& object_parent_settings)
{
TimeKeeper load_timer;
const char* ext = strrchr(filename, '.');
if (ext && (strcmp(ext, ".stl") == 0 || strcmp(ext, ".STL") == 0))
{
Mesh mesh(object_parent_settings);
if (loadMeshSTL(&mesh, filename, transformation)) //Load it! If successful...
{
meshgroup->meshes.push_back(mesh);
log("loading '%s' took %.3f seconds\n", filename, load_timer.restart());
return true;
}
}
return false;
}
}//namespace cura
|
Fix read STL file error
|
Fix read STL file error
The ASCII value of a character may be decimal 26 (0x1A, \SUB, SUBSTITUTE) in a binary STL file.Opening a file in “r” mode may return an error
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
3f1d2fac1a5276518a4255647f1cc50610cd304a
|
001-100/085-Maximal_Rectangle-h.cpp
|
001-100/085-Maximal_Rectangle-h.cpp
|
// Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
// containing only 1's and return its area.
// For example, given the following matrix:
// 1 0 1 0 0
// 1 0 1 1 1
// 1 1 1 1 1
// 1 0 0 1 0
// Return 6.
class Solution {
public:
int maximalRectangle(vector<vector<char>> &matrix) {
if (!matrix.size())
return 0;
int h = matrix.size(), w = matrix[0].size();
// row width, height
vector<int> ht(w + 1, 0);
// use w + 1 is for convenience of last compare
// see Mark#1
int ret = 0;
for (int i = 0; i < h; ++i) {
stack<int> rIndexes;
for (int j = 0; j < w; ++j)
if (matrix[i][j] == '1')
++ht[j];
else
ht[j] = 0;
for (int j = 0; j < w + 1; ++j) {
// Mark#1
// for height 1 2 3 4 5, h[j]==0
// calculate and compare 5×1, 4×2, 3×3, 2×4, 1×5
while (!rIndexes.empty() && ht[j] < ht[rIndexes.top()]) {
int pretop = rIndexes.top();
rIndexes.pop();
ret = max(ret,
ht[pretop] * (rIndexes.empty()
? j
: j - rIndexes.top() - 1));
}
rIndexes.push(j);
}
}
return ret;
}
};
|
// Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
// containing only 1's and return its area.
// For example, given the following matrix:
// 1 0 1 0 0
// 1 0 1 1 1
// 1 1 1 1 1
// 1 0 0 1 0
// Return 6.
class Solution {
public:
int maximalRectangle(vector<vector<char>> &matrix) {
if (matrix.empty() || matrix[0].empty())
return 0;
int h = matrix.size(), w = matrix[0].size();
// use w + 1 for convenience of last compare
vector<int> ht(w + 1, 0);
int ret = 0;
for (int i = 0; i < h; ++i) {
stack<int> cols;
for (int j = 0; j < w; ++j)
matrix[i][j] == '0' ? ht[j] = 0 : ++ht[j];
for (int j = 0; j < w + 1; ++j) {
// e.g. ht 1 2 3 4 5 0, ht[j] == 0 (j == 5)
// compare 5×1, 4×2, 3×3, 2×4, 1×5
while (!cols.empty() && ht[j] < ht[cols.top()]) {
int prev = cols.top();
cols.pop();
ret = max(ret, ht[prev] *
(cols.empty() ? j : j - cols.top() - 1));
}
cols.push(j);
}
}
return ret;
}
};
|
optimize codes
|
optimize codes
|
C++
|
bsd-3-clause
|
ysmiles/leetcode-cpp,ysmiles/leetcode-cpp
|
d09cbcfb12c6c2ff22fbe8384b252e44104f6580
|
x_event_source.hpp
|
x_event_source.hpp
|
#ifndef _X_EVENT_SOURCE
#define _X_EVENT_SOURCE
#include <list>
#include "x_connection.hpp"
class x_event_source {
public:
x_event_source(const x_connection & c) : _c(c) {}
virtual void register_handler(x_event_handler * eh)
{
_handler_list.push_back(eh);
}
virtual void unregister_handler(x_event_handler * eh)
{
_handler_list.remove(eh);
}
void run_event_loop(void)
{
xcb_generic_event_t * ge = NULL;
while (true) {
_c.flush();
ge = xcb_wait_for_event(_c());
if (! ge) {
continue;
} else {
for (auto eh : _handler_list) { eh->handle(ge); }
delete ge;
}
}
}
private:
const x_connection & _c;
std::list<x_event_handler *> _handler_list;
};
#endif
|
#ifndef _X_EVENT_SOURCE
#define _X_EVENT_SOURCE
#include <list>
#include "x_connection.hpp"
class x_event_source {
public:
x_event_source(const x_connection & c) : _c(c) {}
void register_handler(x_event_handler * eh)
{
_handler_list.push_back(eh);
}
void unregister_handler(x_event_handler * eh)
{
_handler_list.remove(eh);
}
void run_event_loop(void)
{
xcb_generic_event_t * ge = NULL;
while (true) {
_c.flush();
ge = xcb_wait_for_event(_c());
if (! ge) {
continue;
} else {
for (auto eh : _handler_list) { eh->handle(ge); }
delete ge;
}
}
}
private:
const x_connection & _c;
std::list<x_event_handler *> _handler_list;
};
#endif
|
Remove virtual keyword from non-virtual methods
|
Remove virtual keyword from non-virtual methods
|
C++
|
bsd-3-clause
|
jotrk/x-choyce,jotrk/x-choyce
|
28372491dc1efdc18160a4503808c8053ce2a028
|
InformationScripting/src/queries/VersionControlQuery.cpp
|
InformationScripting/src/queries/VersionControlQuery.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "VersionControlQuery.h"
#include "../query_framework/QueryRegistry.h"
#include "ModelBase/src/model/TreeManager.h"
#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/elements/StatementItem.h"
using namespace FilePersistence;
namespace InformationScripting {
const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"};
const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"};
Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet)
{
Model::TreeManager* treeManager = target()->manager();
// get GitRepository
QString path("projects/" + treeManager->name());
if (!GitRepository::repositoryExists(path)) return {"No repository found"};
GitRepository repository{path};
TupleSet result;
auto revisions = repository.revisions();
bool converts = false;
auto changeArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]);
const int CHANGE_COUNT = changeArgument.toInt(&converts);
int commitIndexToTake = 0;
if (converts)
commitIndexToTake = std::min(revisions.size() - 1, CHANGE_COUNT);
else if (changeArgument == "all")
commitIndexToTake = revisions.size() - 1;
else
return {"Invalid count argument"};
auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1]));
for (int i = commitIndexToTake; i > 0; --i)
{
QString oldCommitId = revisions[i];
QString newCommitId = revisions[i - 1];
Diff diff = repository.diff(newCommitId, oldCommitId);
auto changes = diff.changes();
addCommitMetaInformation(result, repository.getCommitInformation(newCommitId));
for (auto change : changes.values())
{
// We ignore structure only changes since a node with a structure only change,
// has a child which was deleted or added or modified, and this child will appear in the final representation.
if (change->isFake() || change->onlyStructureChange()) continue;
auto id = change->nodeId();
if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id)))
{
Model::Node* changedNode = nullptr;
if (auto statement = node->firstAncestorOfType(typeMatcher))
changedNode = statement;
else // The node is hopefully higher up in the node hierarchy thus we take it as is.
changedNode = node;
result.add({{"change", newCommitId}, {"ast", changedNode}});
}
}
}
return result;
}
void VersionControlQuery::registerDefaultQueries()
{
QueryRegistry::registerQuery<VersionControlQuery>("changes");
}
VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args)
: LinearQuery{target}, arguments_{{
{COUNT_ARGUMENT_NAMES, "The amount of revision to look at", COUNT_ARGUMENT_NAMES[1], "10"},
{NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"}
}, args}
{}
void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata)
{
ts.add({{"commit", metadata.sha1_},
{"message", metadata.message_},
{"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")},
{"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_},
{"author", metadata.author_.name_ + " " + metadata.author_.eMail_}});
}
} /* namespace InformationScripting */
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "VersionControlQuery.h"
#include "../query_framework/QueryRegistry.h"
#include "ModelBase/src/model/TreeManager.h"
#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/elements/StatementItem.h"
using namespace FilePersistence;
namespace InformationScripting {
const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"};
const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"};
Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet)
{
Model::TreeManager* treeManager = target()->manager();
// get GitRepository
QString path("projects/" + treeManager->name());
if (!GitRepository::repositoryExists(path)) return {"No repository found"};
GitRepository repository{path};
TupleSet result;
auto revisions = repository.revisions();
bool converts = false;
auto changeArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]);
const int CHANGE_COUNT = changeArgument.toInt(&converts);
int commitIndexToTake = 0;
if (converts)
commitIndexToTake = std::min(revisions.size() - 1, CHANGE_COUNT);
else if (changeArgument == "all")
commitIndexToTake = revisions.size() - 1;
else
return {"Invalid count argument"};
auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1]));
for (int i = commitIndexToTake; i > 0; --i)
{
QString oldCommitId = revisions[i];
QString newCommitId = revisions[i - 1];
Diff diff = repository.diff(newCommitId, oldCommitId);
auto changes = diff.changes();
addCommitMetaInformation(result, repository.getCommitInformation(newCommitId));
for (auto change : changes.values())
{
// We ignore structure only changes since a node with a structure only change,
// has a child which was deleted or added or modified, and this child will appear in the final representation.
if (change->isFake() || change->onlyStructureChange()) continue;
auto id = change->nodeId();
if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id)))
{
Model::Node* changedNode = nullptr;
if (auto statement = node->firstAncestorOfType(typeMatcher))
changedNode = statement;
else // The node is hopefully higher up in the node hierarchy thus we take it as is.
changedNode = node;
result.add({{"change", newCommitId}, {"ast", changedNode}});
}
}
}
return result;
}
void VersionControlQuery::registerDefaultQueries()
{
QueryRegistry::registerQuery<VersionControlQuery>("changes");
}
VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args)
: LinearQuery{target}, arguments_{{
{COUNT_ARGUMENT_NAMES, "The amount of revisions to look at", COUNT_ARGUMENT_NAMES[1], "10"},
{NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"}
}, args}
{}
void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata)
{
ts.add({{"commit", metadata.sha1_},
{"message", metadata.message_},
{"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")},
{"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_},
{"author", metadata.author_.name_ + " " + metadata.author_.eMail_}});
}
} /* namespace InformationScripting */
|
Fix a spelling mistake.
|
Fix a spelling mistake.
|
C++
|
bsd-3-clause
|
dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,mgalbier/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,mgalbier/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision
|
00c32d7005fdd2ff590117dea2660a2dcc0a3856
|
Metazion/Net/EpollSocketServer.cpp
|
Metazion/Net/EpollSocketServer.cpp
|
#include "Metazion/Net/EpollSocketServer.hpp"
#include <Metazion/Share/Time/Time.hpp>
#include <Metazion/Share/Utility/Random.hpp>
#if defined(MZ_PLATFORM_LINUX)
DECL_NAMESPACE_MZ_NET_BEGIN
static NS_SHARE::Random g_random;
EpollSocketServer::EpollSocketServer()
: m_epollfdList(nullptr)
, m_epollEventList(nullptr)
, m_socketCapacity(0)
, m_socketCount(0)
, m_socketCtrlList(nullptr)
, m_ioThreadNumber(0)
, m_ioThreadList(nullptr)
, m_maintenanceThread(nullptr) {}
EpollSocketServer::~EpollSocketServer() {}
bool EpollSocketServer::Initialize(int socketCapacity, int ioThreadNumber) {
m_socketCapacity = socketCapacity;
m_ioThreadNumber = ioThreadNumber;
m_epollfdList = new int[m_ioThreadNumber];
for (int index = 0; index < m_ioThreadNumber; ++index) {
int& epollfd = m_epollfdList[index];
const int socketCount = GetSocketCount(index);
epollfd = ::epoll_create(socketCount);
if (epollfd < 0) {
return false;
}
}
m_epollEventList = new struct epoll_event[m_socketCapacity];
::memset(m_epollEventList, 0, sizeof(struct epoll_event) * m_socketCapacity);
m_socketCtrlList = new SocketCtrl[m_socketCapacity];
m_ioThreadList = new EpollIoThread*[m_ioThreadNumber];
for (int index = 0; index < m_ioThreadNumber; ++index) {
EpollIoThread*& ioThread = m_ioThreadList[index];
ioThread = new EpollIoThread();
ioThread->Initialize(this, index);
ioThread->Run();
}
m_maintenanceThread = new EpollMaintenanceThread();
m_maintenanceThread->Init(this);
m_maintenanceThread->Run();
return true;
}
void EpollSocketServer::Finalize() {
m_maintenanceThread->Finalize();
SafeDelete(m_maintenanceThread);
for (int index = 0; index < m_ioThreadNumber; ++index) {
EpollIoThread*& ioThread = m_ioThreadList[index];
ioThread->Finalize();
SafeDelete(ioThread);
}
SafeDeleteArray(m_ioThreadList);
for (int index = 0; index < m_socketCapacity; ++index) {
SocketCtrl& socketInfo = m_socketCtrlList[index];
if (IsNull(socketInfo.m_socket)) {
continue;
}
if (socketInfo.m_active) {
socketInfo.m_socket->Close();
}
else {
socketInfo.m_socket->CloseSockId();
}
socketInfo.m_socket->Destory();
socketInfo.m_socket = nullptr;
}
SafeDeleteArray(m_socketCtrlList);
SafeDeleteArray(m_epollEventList);
for (int index = 0; index < m_ioThreadNumber; ++index) {
int& epollfd = m_epollfdList[index];
if (epollfd >= 0) {
::close(epollfd);
}
}
SafeDeleteArray(m_epollfdList);
}
bool EpollSocketServer::Attach(Socket* socket) {
EpollSocket* epollSocket = static_cast<EpollSocket*>(socket);
ASSERT_TRUE(!IsNull(epollSocket));
if (!CanAttachMore()) {
return false;
}
Lock();
const int index = GetVacantIndex();
AddSocketCtrl(index, epollSocket);
Unlock();
epollSocket->SetIndex(index);
epollSocket->SetSocketServer(this);
epollSocket->OnAttached();
return true;
}
bool EpollSocketServer::CanAttachMore() const {
return m_socketCount < m_socketCapacity;
}
void EpollSocketServer::MarkSocketActive(int index) {
ASSERT_TRUE(index >= 0 && index < m_socketCapacity);
ASSERT_TRUE(!IsNull(m_socketCtrlList[index].m_socket));
ASSERT_TRUE(!m_socketCtrlList[index].m_active);
SocketCtrl& socketInfo = m_socketCtrlList[index];
socketInfo.m_active = true;
EpollSocket* epollSocket = m_socketCtrlList[index].m_socket;
if (!AssociateWithEpoll(epollSocket)) {
epollSocket->CloseSockId();
return;
}
epollSocket->Rework();
}
void EpollSocketServer::MarkSocketClosed(int index) {
ASSERT_TRUE(index >= 0 && index < m_socketCapacity);
ASSERT_TRUE(!IsNull(m_socketCtrlList[index].m_socket));
ASSERT_TRUE(m_socketCtrlList[index].m_active);
SocketCtrl& socketInfo = m_socketCtrlList[index];
socketInfo.m_active = false;
}
EpollSocketServer::SocketCtrl& EpollSocketServer::GetSocketCtrl(int index) {
return m_socketCtrlList[index];
}
void EpollSocketServer::AddSocketCtrl(int index, EpollSocket* socket) {
m_socketCtrlList[index].m_socket = socket;
m_socketCtrlList[index].m_active = false;
++m_socketCount;
}
void EpollSocketServer::RemoveSocketCtrl(int index) {
m_socketCtrlList[index].m_socket = nullptr;
m_socketCtrlList[index].m_active = false;
--m_socketCount;
}
int EpollSocketServer::GetEpollfd(int threadIndex) const {
return m_epollfdList[threadIndex];
}
struct epoll_event& EpollSocketServer::GetEpollEvent(int index) {
return m_epollEventList[index];
}
bool EpollSocketServer::AssociateWithEpoll(EpollSocket* socket) {
const SockId_t& sockId = socket->GetSockId();
const int socketIndex = socket->GetIndex();
const int threadIndex = GetThreadIndex(socketIndex);
struct epoll_event event;
event.data.ptr = socket;
event.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
const int ret = epoll_ctl(m_epollfdList[threadIndex], EPOLL_CTL_ADD, sockId, &event);
if (ret == -1) {
return false;
}
return true;
}
int EpollSocketServer::GetVacantIndex() const {
const int threadIndex = g_random.GetRangeInt(0, m_ioThreadNumber - 1);
const int startIndex = GetStartIndex(threadIndex);
for (int index = startIndex; index < m_socketCapacity; ++index) {
if (IsNull(m_socketCtrlList[index].m_socket)) {
return index;
}
}
for (int index = 0; index < startIndex; ++index) {
if (IsNull(m_socketCtrlList[index].m_socket)) {
return index;
}
}
ASSERT_TRUE(false);
return -1;
}
int EpollSocketServer::GetThreadIndex(int socketIndex) {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
return socketIndex / eachCount;
}
int EpollSocketServer::GetStartIndex(int threadIndex) const {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
return eachCount * threadIndex;
}
int EpollSocketServer::GetSocketCount(int threadIndex) const {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
const int startIndex = eachCount * threadIndex;
const int restCount = m_socketCapacity - startIndex;
return restCount < eachCount ? restCount : eachCount;
}
EpollIoThread::EpollIoThread()
: m_socketServer(nullptr)
, m_index(0)
, m_epollfd(0)
, m_eventList(nullptr)
, m_socketCount(0)
, m_socketCtrlList(nullptr)
, m_stopDesired(false) {}
EpollIoThread::~EpollIoThread() {}
void EpollIoThread::Initialize(EpollSocketServer* socketServer, int index) {
m_socketServer = socketServer;
m_index = index;
const int startIndex = m_socketServer->GetStartIndex(m_index);
m_epollfd = m_socketServer->GetEpollfd(m_index);
m_eventList = &m_socketServer->GetEpollEvent(startIndex);
m_socketCount = m_socketServer->GetSocketCount(m_index);
m_socketCtrlList = &m_socketServer->GetSocketCtrl(startIndex);
m_stopDesired = false;
}
void EpollIoThread::Finalize() {
Stop();
}
void EpollIoThread::Stop() {
m_stopDesired = true;
Wait();
}
void EpollIoThread::Execute() {
while (!m_stopDesired) {
ProcessSockets();
ProcessEvents();
}
}
void EpollIoThread::ProcessSockets() {
for (int index = 0; index < m_socketCount; ++index) {
EpollSocketServer::SocketCtrl& socketCtrl = m_socketCtrlList[index];
if (IsNull(socketCtrl.m_socket)) {
continue;
}
if (socketCtrl.m_active) {
continue;
}
socketCtrl.m_socket->Output();
}
}
void EpollIoThread::ProcessEvents() {
const int count = ::epoll_wait(m_epollfd, m_eventList, m_socketCount, 10);
if (0 == count) {
return;
}
else if (count < 0) {
const int error = GetLastError();
if (EINTR != error) {
::printf("Socket Warning: epoll wait, error[%d]. [%s:%d]\n", error, __FILE__, __LINE__);
}
return;
}
for (int index = 0; index < count; ++index) {
struct epoll_event& event = m_eventList[index];
EpollSocket* epollSocket = static_cast<EpollSocket*>(event.data.ptr);
if (event.events & EPOLLRDHUP) {
::printf("Socket Info: socket close. [%s:%d]\n", __FILE__, __LINE__);
epollSocket->Close();
continue;
}
if (event.events & EPOLLIN) {
epollSocket->Input();
}
if (event.events & EPOLLOUT) {
epollSocket->SetCanOutput(true);
}
}
}
EpollMaintenanceThread::EpollMaintenanceThread()
: m_socketServer(nullptr)
, m_interval(0)
, m_stopDesired(false) {}
EpollMaintenanceThread::~EpollMaintenanceThread() {}
void EpollMaintenanceThread::Init(EpollSocketServer* socketServer) {
ASSERT_TRUE(!IsNull(socketServer));
m_socketServer = socketServer;
m_interval = 0;
m_stopDesired = false;
}
void EpollMaintenanceThread::Finalize() {
Stop();
}
void EpollMaintenanceThread::Stop() {
m_stopDesired = true;
Wait();
}
void EpollMaintenanceThread::Execute() {
int32_t lastTime = NS_SHARE::GetTickMillisecond();
int32_t lastTickTime = lastTime;
while (!m_stopDesired) {
const int32_t curTime = NS_SHARE::GetTickMillisecond();
if (curTime - lastTime < 10) {
MilliSleep(1);
continue;
}
m_interval = curTime - lastTickTime;
lastTickTime = curTime;
ProcessSockets();
lastTime = curTime;
}
}
void EpollMaintenanceThread::ProcessSockets() {
const int socketCapacity = m_socketServer->GetSocketCapacity();
for (int index = 0; index < socketCapacity; ++index) {
EpollSocketServer::SocketCtrl& socketCtrl = m_socketServer->GetSocketCtrl(index);
if (IsNull(socketCtrl.m_socket)) {
continue;
}
if (socketCtrl.m_active) {
ProcessActiveSocket(socketCtrl.m_socket, index);
}
else {
ProcessClosedSocket(socketCtrl.m_socket, index);
}
}
}
void EpollMaintenanceThread::ProcessActiveSocket(EpollSocket* epollSocket, int index) {
if (epollSocket->IsClosed()) {
m_socketServer->MarkSocketClosed(index);
return;
}
epollSocket->Tick(m_interval);
}
void EpollMaintenanceThread::ProcessClosedSocket(EpollSocket* epollSocket, int index) {
if (epollSocket->IsActive()) {
m_socketServer->MarkSocketActive(index);
return;
}
epollSocket->Tick(m_interval);
if (!epollSocket->IsClosing()) {
m_socketServer->Lock();
if (epollSocket->IsClosing()) {
m_socketServer->Unlock();
return;
}
m_socketServer->RemoveSocketCtrl(index);
m_socketServer->Unlock();
epollSocket->OnDetached();
epollSocket->Destory();
}
}
DECL_NAMESPACE_MZ_NET_END
#endif // MZ_PLATFORM_LINUX
|
#include "Metazion/Net/EpollSocketServer.hpp"
#include <Metazion/Share/Time/Time.hpp>
#include <Metazion/Share/Utility/Random.hpp>
#if defined(MZ_PLATFORM_LINUX)
DECL_NAMESPACE_MZ_NET_BEGIN
static NS_SHARE::Random g_random;
EpollSocketServer::EpollSocketServer()
: m_epollfdList(nullptr)
, m_epollEventList(nullptr)
, m_socketCapacity(0)
, m_socketCount(0)
, m_socketCtrlList(nullptr)
, m_ioThreadNumber(0)
, m_ioThreadList(nullptr)
, m_maintenanceThread(nullptr) {}
EpollSocketServer::~EpollSocketServer() {}
bool EpollSocketServer::Initialize(int socketCapacity, int ioThreadNumber) {
m_socketCapacity = socketCapacity;
m_ioThreadNumber = ioThreadNumber;
m_epollfdList = new int[m_ioThreadNumber];
for (int index = 0; index < m_ioThreadNumber; ++index) {
int& epollfd = m_epollfdList[index];
const int socketCount = GetSocketCount(index);
epollfd = ::epoll_create(socketCount);
if (epollfd < 0) {
return false;
}
}
m_epollEventList = new struct epoll_event[m_socketCapacity];
::memset(m_epollEventList, 0, sizeof(struct epoll_event) * m_socketCapacity);
m_socketCtrlList = new SocketCtrl[m_socketCapacity];
m_ioThreadList = new EpollIoThread*[m_ioThreadNumber];
for (int index = 0; index < m_ioThreadNumber; ++index) {
EpollIoThread*& ioThread = m_ioThreadList[index];
ioThread = new EpollIoThread();
ioThread->Initialize(this, index);
ioThread->Run();
}
m_maintenanceThread = new EpollMaintenanceThread();
m_maintenanceThread->Init(this);
m_maintenanceThread->Run();
return true;
}
void EpollSocketServer::Finalize() {
m_maintenanceThread->Finalize();
SafeDelete(m_maintenanceThread);
for (int index = 0; index < m_ioThreadNumber; ++index) {
EpollIoThread*& ioThread = m_ioThreadList[index];
ioThread->Finalize();
SafeDelete(ioThread);
}
SafeDeleteArray(m_ioThreadList);
for (int index = 0; index < m_socketCapacity; ++index) {
SocketCtrl& socketInfo = m_socketCtrlList[index];
if (IsNull(socketInfo.m_socket)) {
continue;
}
if (socketInfo.m_active) {
socketInfo.m_socket->Close();
}
else {
socketInfo.m_socket->CloseSockId();
}
socketInfo.m_socket->Destory();
socketInfo.m_socket = nullptr;
}
SafeDeleteArray(m_socketCtrlList);
SafeDeleteArray(m_epollEventList);
for (int index = 0; index < m_ioThreadNumber; ++index) {
int& epollfd = m_epollfdList[index];
if (epollfd >= 0) {
::close(epollfd);
}
}
SafeDeleteArray(m_epollfdList);
}
bool EpollSocketServer::Attach(Socket* socket) {
EpollSocket* epollSocket = static_cast<EpollSocket*>(socket);
ASSERT_TRUE(!IsNull(epollSocket));
if (!CanAttachMore()) {
return false;
}
Lock();
const int index = GetVacantIndex();
AddSocketCtrl(index, epollSocket);
Unlock();
epollSocket->SetIndex(index);
epollSocket->SetSocketServer(this);
epollSocket->OnAttached();
return true;
}
bool EpollSocketServer::CanAttachMore() const {
return m_socketCount < m_socketCapacity;
}
void EpollSocketServer::MarkSocketActive(int index) {
ASSERT_TRUE(index >= 0 && index < m_socketCapacity);
ASSERT_TRUE(!IsNull(m_socketCtrlList[index].m_socket));
ASSERT_TRUE(!m_socketCtrlList[index].m_active);
SocketCtrl& socketInfo = m_socketCtrlList[index];
socketInfo.m_active = true;
EpollSocket* epollSocket = m_socketCtrlList[index].m_socket;
if (!AssociateWithEpoll(epollSocket)) {
epollSocket->CloseSockId();
return;
}
epollSocket->Rework();
}
void EpollSocketServer::MarkSocketClosed(int index) {
ASSERT_TRUE(index >= 0 && index < m_socketCapacity);
ASSERT_TRUE(!IsNull(m_socketCtrlList[index].m_socket));
ASSERT_TRUE(m_socketCtrlList[index].m_active);
SocketCtrl& socketInfo = m_socketCtrlList[index];
socketInfo.m_active = false;
}
EpollSocketServer::SocketCtrl& EpollSocketServer::GetSocketCtrl(int index) {
return m_socketCtrlList[index];
}
void EpollSocketServer::AddSocketCtrl(int index, EpollSocket* socket) {
m_socketCtrlList[index].m_socket = socket;
m_socketCtrlList[index].m_active = false;
++m_socketCount;
}
void EpollSocketServer::RemoveSocketCtrl(int index) {
m_socketCtrlList[index].m_socket = nullptr;
m_socketCtrlList[index].m_active = false;
--m_socketCount;
}
int EpollSocketServer::GetEpollfd(int threadIndex) const {
return m_epollfdList[threadIndex];
}
struct epoll_event& EpollSocketServer::GetEpollEvent(int index) {
return m_epollEventList[index];
}
bool EpollSocketServer::AssociateWithEpoll(EpollSocket* socket) {
const SockId_t& sockId = socket->GetSockId();
const int socketIndex = socket->GetIndex();
const int threadIndex = GetThreadIndex(socketIndex);
struct epoll_event event;
event.data.ptr = socket;
event.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
const int ret = epoll_ctl(m_epollfdList[threadIndex], EPOLL_CTL_ADD, sockId, &event);
if (ret == -1) {
return false;
}
return true;
}
int EpollSocketServer::GetVacantIndex() const {
const int threadIndex = g_random.GetRangeInt(0, m_ioThreadNumber - 1);
const int startIndex = GetStartIndex(threadIndex);
for (int index = startIndex; index < m_socketCapacity; ++index) {
if (IsNull(m_socketCtrlList[index].m_socket)) {
return index;
}
}
for (int index = 0; index < startIndex; ++index) {
if (IsNull(m_socketCtrlList[index].m_socket)) {
return index;
}
}
ASSERT_TRUE(false);
return -1;
}
int EpollSocketServer::GetThreadIndex(int socketIndex) {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
return socketIndex / eachCount;
}
int EpollSocketServer::GetStartIndex(int threadIndex) const {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
return eachCount * threadIndex;
}
int EpollSocketServer::GetSocketCount(int threadIndex) const {
const int eachCount = (m_socketCapacity + m_ioThreadNumber - 1) / m_ioThreadNumber;
const int startIndex = eachCount * threadIndex;
const int restCount = m_socketCapacity - startIndex;
return restCount < eachCount ? restCount : eachCount;
}
EpollIoThread::EpollIoThread()
: m_socketServer(nullptr)
, m_index(0)
, m_epollfd(0)
, m_eventList(nullptr)
, m_socketCount(0)
, m_socketCtrlList(nullptr)
, m_stopDesired(false) {}
EpollIoThread::~EpollIoThread() {}
void EpollIoThread::Initialize(EpollSocketServer* socketServer, int index) {
m_socketServer = socketServer;
m_index = index;
const int startIndex = m_socketServer->GetStartIndex(m_index);
m_epollfd = m_socketServer->GetEpollfd(m_index);
m_eventList = &m_socketServer->GetEpollEvent(startIndex);
m_socketCount = m_socketServer->GetSocketCount(m_index);
m_socketCtrlList = &m_socketServer->GetSocketCtrl(startIndex);
m_stopDesired = false;
}
void EpollIoThread::Finalize() {
Stop();
}
void EpollIoThread::Stop() {
m_stopDesired = true;
Wait();
}
void EpollIoThread::Execute() {
while (!m_stopDesired) {
ProcessSockets();
ProcessEvents();
}
}
void EpollIoThread::ProcessSockets() {
for (int index = 0; index < m_socketCount; ++index) {
EpollSocketServer::SocketCtrl& socketCtrl = m_socketCtrlList[index];
if (IsNull(socketCtrl.m_socket)) {
continue;
}
if (!socketCtrl.m_active) {
continue;
}
socketCtrl.m_socket->Output();
}
}
void EpollIoThread::ProcessEvents() {
const int count = ::epoll_wait(m_epollfd, m_eventList, m_socketCount, 10);
if (0 == count) {
return;
}
else if (count < 0) {
const int error = GetLastError();
if (EINTR != error) {
::printf("Socket Warning: epoll wait, error[%d]. [%s:%d]\n", error, __FILE__, __LINE__);
}
return;
}
for (int index = 0; index < count; ++index) {
struct epoll_event& event = m_eventList[index];
EpollSocket* epollSocket = static_cast<EpollSocket*>(event.data.ptr);
if (event.events & EPOLLRDHUP) {
::printf("Socket Info: socket close. [%s:%d]\n", __FILE__, __LINE__);
epollSocket->Close();
continue;
}
if (event.events & EPOLLIN) {
epollSocket->Input();
}
if (event.events & EPOLLOUT) {
epollSocket->SetCanOutput(true);
}
}
}
EpollMaintenanceThread::EpollMaintenanceThread()
: m_socketServer(nullptr)
, m_interval(0)
, m_stopDesired(false) {}
EpollMaintenanceThread::~EpollMaintenanceThread() {}
void EpollMaintenanceThread::Init(EpollSocketServer* socketServer) {
ASSERT_TRUE(!IsNull(socketServer));
m_socketServer = socketServer;
m_interval = 0;
m_stopDesired = false;
}
void EpollMaintenanceThread::Finalize() {
Stop();
}
void EpollMaintenanceThread::Stop() {
m_stopDesired = true;
Wait();
}
void EpollMaintenanceThread::Execute() {
int32_t lastTime = NS_SHARE::GetTickMillisecond();
int32_t lastTickTime = lastTime;
while (!m_stopDesired) {
const int32_t curTime = NS_SHARE::GetTickMillisecond();
if (curTime - lastTime < 10) {
MilliSleep(1);
continue;
}
m_interval = curTime - lastTickTime;
lastTickTime = curTime;
ProcessSockets();
lastTime = curTime;
}
}
void EpollMaintenanceThread::ProcessSockets() {
const int socketCapacity = m_socketServer->GetSocketCapacity();
for (int index = 0; index < socketCapacity; ++index) {
EpollSocketServer::SocketCtrl& socketCtrl = m_socketServer->GetSocketCtrl(index);
if (IsNull(socketCtrl.m_socket)) {
continue;
}
if (socketCtrl.m_active) {
ProcessActiveSocket(socketCtrl.m_socket, index);
}
else {
ProcessClosedSocket(socketCtrl.m_socket, index);
}
}
}
void EpollMaintenanceThread::ProcessActiveSocket(EpollSocket* epollSocket, int index) {
if (epollSocket->IsClosed()) {
m_socketServer->MarkSocketClosed(index);
return;
}
epollSocket->Tick(m_interval);
}
void EpollMaintenanceThread::ProcessClosedSocket(EpollSocket* epollSocket, int index) {
if (epollSocket->IsActive()) {
m_socketServer->MarkSocketActive(index);
return;
}
epollSocket->Tick(m_interval);
if (!epollSocket->IsClosing()) {
m_socketServer->Lock();
if (epollSocket->IsClosing()) {
m_socketServer->Unlock();
return;
}
m_socketServer->RemoveSocketCtrl(index);
m_socketServer->Unlock();
epollSocket->OnDetached();
epollSocket->Destory();
}
}
DECL_NAMESPACE_MZ_NET_END
#endif // MZ_PLATFORM_LINUX
|
Move maintenance operations to a separate thread in epoll.
|
Move maintenance operations to a separate thread in epoll.
|
C++
|
mit
|
Metazion/Metazion,Metazion/Metazion
|
73536f2550ef1b3c2e891ec00f6c5319ec10fde5
|
NaoTHSoccer/Source/Cognition/Cognition.cpp
|
NaoTHSoccer/Source/Cognition/Cognition.cpp
|
/**
* @file Cognition.cpp
*
* @author <a href="mailto:[email protected]">Heinrich Mellmann</a>
* Implementation of the class Cognition
*/
#include "Cognition.h"
#include <PlatformInterface/Platform.h>
// tools
#include "Tools/Debug/Trace.h"
/////////////////////////////////////
// Modules
/////////////////////////////////////
// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"
#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"
// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"
#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"
#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"
#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"
#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"
#include "Modules/Modeling/CompassProvider/CompassProvider.h"
// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"
// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"
#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"
// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"
using namespace std;
Cognition::Cognition()
: ModuleManagerWithDebug("")
{
}
Cognition::~Cognition()
{
}
#define REGISTER_MODULE(module) \
std::cout << "[Cognition] Register " << #module << std::endl;\
registerModule<module>(std::string(#module))
void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
std::cout << "[Cognition] Cognition register start" << std::endl;
// register input module
ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
sensor->getModuleT()->init(platformInterface, platform);
/*
* to register a module use
* REGISTER_MODULE(ModuleClassName);
*
* Remark: to enable the module don't forget
* to set the value in modules.cfg
*/
// -- BEGIN REGISTER MODULES --
// infrastructure
REGISTER_MODULE(ButtonEventMonitor);
REGISTER_MODULE(WifiModeSetter);
REGISTER_MODULE(TeamCommReceiver);
REGISTER_MODULE(SimpleNetworkTimeProtocol);
REGISTER_MODULE(GameController);
REGISTER_MODULE(BatteryAlert);
REGISTER_MODULE(LEDSetter);
REGISTER_MODULE(UltraSoundControl);
REGISTER_MODULE(CameraDebug);
REGISTER_MODULE(CameraInfoSetter);
REGISTER_MODULE(AdaptiveAutoExposure);
REGISTER_MODULE(WhistleDetectorV1);
REGISTER_MODULE(WhistleDetectorV2);
// perception
REGISTER_MODULE(CameraMatrixFinder);
REGISTER_MODULE(KinematicChainProvider);
REGISTER_MODULE(ArtificialHorizonCalculator);
REGISTER_MODULE(BodyContourProvider);
REGISTER_MODULE(HistogramProvider);
REGISTER_MODULE(IntegralImageProvider);
REGISTER_MODULE(FieldColorClassifier);
REGISTER_MODULE(IntegralFieldDetector);
REGISTER_MODULE(ScanGridProvider);
REGISTER_MODULE(ScanGridEdgelDetector);
REGISTER_MODULE(ScanLineEdgelDetector);
REGISTER_MODULE(FieldDetector);
REGISTER_MODULE(LineGraphProvider);
REGISTER_MODULE(GoalFeatureDetector);
REGISTER_MODULE(GoalFeatureDetectorV2);
REGISTER_MODULE(GoalDetector);
REGISTER_MODULE(GoalDetectorV2);
REGISTER_MODULE(GoalCrossBarDetector);
REGISTER_MODULE(NoGreenObstacleDetector);
REGISTER_MODULE(RedBallDetector);
REGISTER_MODULE(CNNBallDetector);
REGISTER_MODULE(MultiPassBallDetector);
REGISTER_MODULE(FakeCameraMatrixFinder);
REGISTER_MODULE(FakeBallDetector);
REGISTER_MODULE(VirtualVisionProcessor);
REGISTER_MODULE(PerceptionsVisualizer);
REGISTER_MODULE(RansacLineDetector);
REGISTER_MODULE(RansacLineDetectorOnGraphs);
REGISTER_MODULE(LineAugmenter);
REGISTER_MODULE(CompassProvider);
// modeling
REGISTER_MODULE(BodyStateProvider);
REGISTER_MODULE(FieldCompass);
REGISTER_MODULE(UltraSoundObstacleDetector);
REGISTER_MODULE(UltrasonicDetector2020);
REGISTER_MODULE(TeamCommReceiveEmulator);
REGISTER_MODULE(TeamMessageStatisticsModule);
REGISTER_MODULE(TeamMessagePlayersStateModule);
REGISTER_MODULE(SoccerStrategyProvider);
REGISTER_MODULE(PotentialFieldProvider);
REGISTER_MODULE(SituationPriorProvider);
REGISTER_MODULE(GPS_SelfLocator);
REGISTER_MODULE(MonteCarloSelfLocator);
REGISTER_MODULE(OdometrySelfLocator);
REGISTER_MODULE(WholeGoalLocator);
REGISTER_MODULE(DummyActiveGoalLocator);
REGISTER_MODULE(MultiKalmanBallLocator);
REGISTER_MODULE(TeamBallLocatorMedian);
REGISTER_MODULE(TeamBallLocatorCanopyCluster);
REGISTER_MODULE(MultiUnifiedObstacleLocator);
/*
* BEGIN ROLE DECISIONS
*/
REGISTER_MODULE(RolesProvider);
// first set the position of the roles
REGISTER_MODULE(RoleDecisionPositionStatic);
REGISTER_MODULE(RoleDecisionPositionForce);
REGISTER_MODULE(RoleDecisionPositionPotentialField);
REGISTER_MODULE(RoleDecisionPositionFormation);
REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
// then decide which player should have which role
REGISTER_MODULE(RoleDecisionAssignmentStatic);
REGISTER_MODULE(RoleDecisionAssignmentDistance);
// finally, determine the dynamic role (striker, supporter, ...)
REGISTER_MODULE(RoleDecisionDynamic);
// old striker decisions
REGISTER_MODULE(SimpleRoleDecision);
REGISTER_MODULE(StableRoleDecision);
REGISTER_MODULE(CleanRoleDecision);
/*
* END ROLE DECISIONS
*/
REGISTER_MODULE(KickDirectionSimulator);
REGISTER_MODULE(Simulation);
REGISTER_MODULE(StaticDebugModelProvider);
// behavior
REGISTER_MODULE(BasicTestBehavior);
REGISTER_MODULE(XABSLBehaviorControl);
REGISTER_MODULE(PathPlanner2018);
REGISTER_MODULE(CameraMatrixCorrectorV3);
REGISTER_MODULE(TeamCommSender);
// debug
REGISTER_MODULE(GameLogger);
REGISTER_MODULE(Debug);
REGISTER_MODULE(FrameRateCheck);
REGISTER_MODULE(DebugExecutor);
// -- END REGISTER MODULES --
// register output module
ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
actuator->getModuleT()->init(platformInterface, platform);
// use the configuration in order to set whether a module is activated or not
const naoth::Configuration& config = Platform::getInstance().theConfiguration;
list<string>::const_iterator name = getExecutionList().begin();
for(;name != getExecutionList().end(); ++name)
{
bool active = false;
if(config.hasKey("modules", *name)) {
active = config.getBool("modules", *name);
}
if(active) {
std::cout << "[Cognition] activating module " << *name << std::endl;
}
setModuleEnabled(*name, active);
}//end for
// auto-generate the execution list
//calculateExecutionList();
std::cout << "[Cognition] register end" << std::endl;
stopwatch.start();
}//end init
void Cognition::call()
{
// BEGIN cognition frame rate measuring
stopwatch.stop();
stopwatch.start();
PLOT("Cognition.Cycle", stopwatch.lastValue);
// END cognition frame rate measuring
STOPWATCH_START("Cognition.Execute");
// execute all modules
list<AbstractModuleCreator*>::const_iterator iter;
for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
{
AbstractModuleCreator* module = *iter;
if (module != NULL && module->isEnabled())
{
std::string name(module->getModule()->getName());
GT_TRACE("executing " << name);
module->execute();
}
}
STOPWATCH_STOP("Cognition.Execute");
// HACK: reset all the debug stuff before executing the modules
STOPWATCH_START("Cognition.Debug.Init");
getDebugDrawings().reset();
getDebugImageDrawings().reset();
getDebugImageDrawingsTop().reset();
getDebugDrawings3D().reset();
STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
|
/**
* @file Cognition.cpp
*
* @author <a href="mailto:[email protected]">Heinrich Mellmann</a>
* Implementation of the class Cognition
*/
#include "Cognition.h"
#include <PlatformInterface/Platform.h>
// tools
#include "Tools/Debug/Trace.h"
/////////////////////////////////////
// Modules
/////////////////////////////////////
// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"
#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"
// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"
#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"
#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"
#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"
#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"
#include "Modules/Modeling/CompassProvider/CompassProvider.h"
// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"
// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"
#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"
// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"
using namespace std;
Cognition::Cognition()
: ModuleManagerWithDebug("")
{
}
Cognition::~Cognition()
{
}
#define REGISTER_MODULE(module) \
std::cout << "[Cognition] Register " << #module << std::endl;\
registerModule<module>(std::string(#module))
void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
std::cout << "[Cognition] Cognition register start" << std::endl;
// register input module
ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
sensor->getModuleT()->init(platformInterface, platform);
/*
* to register a module use
* REGISTER_MODULE(ModuleClassName);
*
* Remark: to enable the module don't forget
* to set the value in modules.cfg
*/
// -- BEGIN REGISTER MODULES --
// infrastructure
REGISTER_MODULE(ButtonEventMonitor);
REGISTER_MODULE(WifiModeSetter);
REGISTER_MODULE(TeamCommReceiver);
REGISTER_MODULE(SimpleNetworkTimeProtocol);
REGISTER_MODULE(GameController);
REGISTER_MODULE(BatteryAlert);
REGISTER_MODULE(LEDSetter);
REGISTER_MODULE(UltraSoundControl);
REGISTER_MODULE(CameraDebug);
REGISTER_MODULE(CameraInfoSetter);
REGISTER_MODULE(AdaptiveAutoExposure);
REGISTER_MODULE(WhistleDetectorV1);
REGISTER_MODULE(WhistleDetectorV2);
// perception
REGISTER_MODULE(CameraMatrixFinder);
REGISTER_MODULE(KinematicChainProvider);
REGISTER_MODULE(ArtificialHorizonCalculator);
REGISTER_MODULE(BodyContourProvider);
REGISTER_MODULE(HistogramProvider);
REGISTER_MODULE(FieldColorClassifier);
REGISTER_MODULE(IntegralImageProvider);
REGISTER_MODULE(IntegralFieldDetector);
REGISTER_MODULE(ScanGridProvider);
REGISTER_MODULE(ScanGridEdgelDetector);
REGISTER_MODULE(ScanLineEdgelDetector);
REGISTER_MODULE(FieldDetector);
REGISTER_MODULE(LineGraphProvider);
REGISTER_MODULE(GoalFeatureDetector);
REGISTER_MODULE(GoalFeatureDetectorV2);
REGISTER_MODULE(GoalDetector);
REGISTER_MODULE(GoalDetectorV2);
REGISTER_MODULE(GoalCrossBarDetector);
REGISTER_MODULE(NoGreenObstacleDetector);
REGISTER_MODULE(RedBallDetector);
REGISTER_MODULE(CNNBallDetector);
REGISTER_MODULE(MultiPassBallDetector);
REGISTER_MODULE(FakeCameraMatrixFinder);
REGISTER_MODULE(FakeBallDetector);
REGISTER_MODULE(VirtualVisionProcessor);
REGISTER_MODULE(PerceptionsVisualizer);
REGISTER_MODULE(RansacLineDetector);
REGISTER_MODULE(RansacLineDetectorOnGraphs);
REGISTER_MODULE(LineAugmenter);
REGISTER_MODULE(CompassProvider);
// modeling
REGISTER_MODULE(BodyStateProvider);
REGISTER_MODULE(FieldCompass);
REGISTER_MODULE(UltraSoundObstacleDetector);
REGISTER_MODULE(UltrasonicDetector2020);
REGISTER_MODULE(TeamCommReceiveEmulator);
REGISTER_MODULE(TeamMessageStatisticsModule);
REGISTER_MODULE(TeamMessagePlayersStateModule);
REGISTER_MODULE(SoccerStrategyProvider);
REGISTER_MODULE(PotentialFieldProvider);
REGISTER_MODULE(SituationPriorProvider);
REGISTER_MODULE(GPS_SelfLocator);
REGISTER_MODULE(MonteCarloSelfLocator);
REGISTER_MODULE(OdometrySelfLocator);
REGISTER_MODULE(WholeGoalLocator);
REGISTER_MODULE(DummyActiveGoalLocator);
REGISTER_MODULE(MultiKalmanBallLocator);
REGISTER_MODULE(TeamBallLocatorMedian);
REGISTER_MODULE(TeamBallLocatorCanopyCluster);
REGISTER_MODULE(MultiUnifiedObstacleLocator);
/*
* BEGIN ROLE DECISIONS
*/
REGISTER_MODULE(RolesProvider);
// first set the position of the roles
REGISTER_MODULE(RoleDecisionPositionStatic);
REGISTER_MODULE(RoleDecisionPositionForce);
REGISTER_MODULE(RoleDecisionPositionPotentialField);
REGISTER_MODULE(RoleDecisionPositionFormation);
REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
// then decide which player should have which role
REGISTER_MODULE(RoleDecisionAssignmentStatic);
REGISTER_MODULE(RoleDecisionAssignmentDistance);
// finally, determine the dynamic role (striker, supporter, ...)
REGISTER_MODULE(RoleDecisionDynamic);
// old striker decisions
REGISTER_MODULE(SimpleRoleDecision);
REGISTER_MODULE(StableRoleDecision);
REGISTER_MODULE(CleanRoleDecision);
/*
* END ROLE DECISIONS
*/
REGISTER_MODULE(KickDirectionSimulator);
REGISTER_MODULE(Simulation);
REGISTER_MODULE(StaticDebugModelProvider);
// behavior
REGISTER_MODULE(BasicTestBehavior);
REGISTER_MODULE(XABSLBehaviorControl);
REGISTER_MODULE(PathPlanner2018);
REGISTER_MODULE(CameraMatrixCorrectorV3);
REGISTER_MODULE(TeamCommSender);
// debug
REGISTER_MODULE(GameLogger);
REGISTER_MODULE(Debug);
REGISTER_MODULE(FrameRateCheck);
REGISTER_MODULE(DebugExecutor);
// -- END REGISTER MODULES --
// register output module
ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
actuator->getModuleT()->init(platformInterface, platform);
// use the configuration in order to set whether a module is activated or not
const naoth::Configuration& config = Platform::getInstance().theConfiguration;
list<string>::const_iterator name = getExecutionList().begin();
for(;name != getExecutionList().end(); ++name)
{
bool active = false;
if(config.hasKey("modules", *name)) {
active = config.getBool("modules", *name);
}
if(active) {
std::cout << "[Cognition] activating module " << *name << std::endl;
}
setModuleEnabled(*name, active);
}//end for
// auto-generate the execution list
//calculateExecutionList();
std::cout << "[Cognition] register end" << std::endl;
stopwatch.start();
}//end init
void Cognition::call()
{
// BEGIN cognition frame rate measuring
stopwatch.stop();
stopwatch.start();
PLOT("Cognition.Cycle", stopwatch.lastValue);
// END cognition frame rate measuring
STOPWATCH_START("Cognition.Execute");
// execute all modules
list<AbstractModuleCreator*>::const_iterator iter;
for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
{
AbstractModuleCreator* module = *iter;
if (module != NULL && module->isEnabled())
{
std::string name(module->getModule()->getName());
GT_TRACE("executing " << name);
module->execute();
}
}
STOPWATCH_STOP("Cognition.Execute");
// HACK: reset all the debug stuff before executing the modules
STOPWATCH_START("Cognition.Debug.Init");
getDebugDrawings().reset();
getDebugImageDrawings().reset();
getDebugImageDrawingsTop().reset();
getDebugDrawings3D().reset();
STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
|
change order of modules: IntegralImageProvider usues FieldColorPercept provided by FieldColorClassifier
|
bugfix: change order of modules: IntegralImageProvider usues FieldColorPercept provided by FieldColorClassifier
|
C++
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
fe156f4a271c5ccd9701a511699f6e6e1bb8c819
|
src/TopicUtils.cc
|
src/TopicUtils.cc
|
/*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string>
#include "ignition/transport/TopicUtils.hh"
using namespace ignition;
using namespace transport;
//////////////////////////////////////////////////
bool TopicUtils::IsValidTopic(const std::string &_topic)
{
return IsValidNamespace(_topic) && (_topic != "");
}
//////////////////////////////////////////////////
bool TopicUtils::IsValidNamespace(const std::string &_ns)
{
// The empty string or "/" are not valid.
if (_ns == "/")
return false;
if (_ns.find("~") != std::string::npos)
return false;
// If the topic name has a white space is not valid.
if (_ns.find(" ") != std::string::npos)
return false;
// It is not allowed to have two consecutive slashes.
if (_ns.find("//") != std::string::npos)
return false;
return true;
}
//////////////////////////////////////////////////
bool TopicUtils::GetScopedName(const std::string &_ns,
const std::string &_topic, std::string &_scoped)
{
// Sanity check, first things first.
if (!IsValidNamespace(_ns) || !IsValidTopic(_topic))
return false;
std::string ns = _ns;
std::string topic = _topic;
// If the namespace does not contain a trailing slash, append it.
if (!ns.empty() && ns.back() != '/')
ns.push_back('/');
// If the namespace does not start with slash, add it.
if (!ns.empty() && ns.front() != '/')
ns.insert(0, 1, '/');
// If the topic ends in "/", remove it.
if (!topic.empty() && topic.back() == '/')
topic.pop_back();
// If the topic does starts with '/' is considered an absolute topic and the
// namespace will not be prefixed.
if (!topic.empty() && topic.front() == '/')
_scoped = topic;
else
_scoped = ns + topic;
return true;
}
|
/*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string>
#include "ignition/transport/TopicUtils.hh"
using namespace ignition;
using namespace transport;
//////////////////////////////////////////////////
bool TopicUtils::IsValidTopic(const std::string &_topic)
{
return IsValidNamespace(_topic) && (_topic != "");
}
//////////////////////////////////////////////////
bool TopicUtils::IsValidNamespace(const std::string &_ns)
{
// The empty string or "/" are not valid.
if (_ns == "/")
return false;
if (_ns.find("~") != std::string::npos)
return false;
// If the topic name has a white space is not valid.
if (_ns.find(" ") != std::string::npos)
return false;
// It is not allowed to have two consecutive slashes.
if (_ns.find("//") != std::string::npos)
return false;
return true;
}
//////////////////////////////////////////////////
bool TopicUtils::GetScopedName(const std::string &_ns,
const std::string &_topic, std::string &_scoped)
{
// Sanity check, first things first.
if (!IsValidNamespace(_ns) || !IsValidTopic(_topic))
return false;
std::string ns = _ns;
std::string topic = _topic;
// If the namespace does not contain a trailing slash, append it.
if (ns.empty() || ns.back() != '/')
ns.push_back('/');
// If the namespace does not start with slash, add it.
if (ns.empty() || ns.front() != '/')
ns.insert(0, 1, '/');
// If the topic ends in "/", remove it.
if (!topic.empty() && topic.back() == '/')
topic.pop_back();
// If the topic does starts with '/' is considered an absolute topic and the
// namespace will not be prefixed.
if (!topic.empty() && topic.front() == '/')
_scoped = topic;
else
_scoped = ns + topic;
return true;
}
|
fix name scoping behavior, while still avoiding calling front() or back() on empty strings
|
fix name scoping behavior, while still avoiding calling front() or back() on empty strings
--HG--
branch : windows_fixes
|
C++
|
apache-2.0
|
j-rivero/ign-transport-git,j-rivero/ign-transport-git,j-rivero/ign-transport-git,j-rivero/ign-transport-git
|
c3614c5dca23c0e0ffbbb8b47750a1fe3971cb22
|
frontend/main.cpp
|
frontend/main.cpp
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libgen.h>
#include <dlfcn.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <stdexcept>
#include <tclap/CmdLine.h>
#include <mapredo/settings.h>
#include <mapredo/engine.h>
#include <mapredo/base.h>
#include <mapredo/plugin_loader.h>
#include <mapredo/directory.h>
static double time_since (const std::chrono::high_resolution_clock::time_point& time)
{
auto duration = std::chrono::duration_cast<std::chrono::duration<double>>
(std::chrono::high_resolution_clock::now() - time);
return duration.count();
}
static void reduce (const std::string& plugin_file,
const std::string& work_dir,
const std::string& subdir,
const bool verbose,
const int parallel,
const int max_files)
{
if (verbose)
{
std::cerr << "Using working directory " << work_dir << "\n";
std::cerr << "Using " << parallel << " threads,"
<< " with HW concurrency at "
<< std::thread::hardware_concurrency()
<< "\n";
}
plugin_loader plugin (plugin_file);
auto& mapreducer (plugin.get());
engine mapred_engine (work_dir, subdir, parallel, 0, max_files);
auto start_time = std::chrono::high_resolution_clock::now();
mapred_engine.reduce (mapreducer, plugin);
if (verbose)
{
std::cerr << "Merging finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
}
static void run (const std::string& plugin_file,
const std::string& work_dir,
const std::string& subdir,
const bool verbose,
const size_t buffer_size,
const int parallel,
const int max_files,
const bool map_only)
{
plugin_loader plugin (plugin_file);
auto& mapreducer (plugin.get());
engine mapred_engine (work_dir, subdir, parallel, buffer_size, max_files);
size_t buf_size = 0x2000;
std::unique_ptr<char[]> buf (new char[buf_size]);
size_t start = 0, end = 0;
size_t i;
ssize_t bytes;
std::string line;
bool first = true;
std::chrono::high_resolution_clock::time_point start_time;
while ((bytes = read(STDIN_FILENO, buf.get() + end, buf_size - end)) > 0)
{
end += bytes;
if (first)
{
first = false;
// Skip any Windows style UTF-8 header
unsigned char u8header[] = {0xef, 0xbb, 0xbf};
if (end - start >= 3 && memcmp(buf.get() + start, u8header, 3) == 0)
{
start += 3;
}
start_time = std::chrono::high_resolution_clock::now();
mapred_engine.enable_sorters (mapreducer.type(),
false);
if (verbose)
{
std::cerr << "Using working directory " << work_dir << "\n";
std::cerr << "Maximum buffer size is " << buffer_size
<< " bytes.\nUsing " << parallel << " threads,"
<< " with HW concurrency at "
<< std::thread::hardware_concurrency()
<< "\n";
}
}
for (i = start; i < end; i++)
{
if (buf[i] == '\n')
{
if (i == start || buf[i-1] != '\r')
{
buf[i] = '\0';
mapreducer.map(buf.get() + start, i - start, mapred_engine);
}
else
{
buf[i-1] = '\0';
mapreducer.map (buf.get() + start, i - start - 1,
mapred_engine);
}
start = i + 1;
}
}
if (start < i)
{
if (start == 0)
{
buf_size *= 2; // double line buffer
char* nbuf = new char[buf_size];
memcpy (nbuf, buf.get(), end);
buf.reset (nbuf);
}
memmove (buf.get(), buf.get() + start, end - start);
end -= start;
start = 0;
}
else start = end = 0;
}
if (first) return; // no input
if (verbose)
{
std::cerr << "Sorting finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
if (!map_only)
{
mapred_engine.flush (mapreducer, plugin);
if (verbose)
{
std::cerr << "Merging finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
}
else mapred_engine.flush();
}
static std::string get_default_workdir()
{
return TMPDIR;
}
int
main (int argc, char* argv[])
{
int64_t buffer_size = 10 * 1024 * 1024;
int parallel = std::thread::hardware_concurrency();
int max_files = 20 * parallel;
int verbose = false;
int compression = true;
std::string subdir;
std::string work_dir = get_default_workdir();
bool map_only = false;
bool reduce_only = false;
bool keep_tmpfiles = false;
std::string plugin_path;
settings& config (settings::instance());
try
{
TCLAP::CmdLine cmd ("mapredo: Map-reduce engine for small/medium data",
' ', PACKAGE_VERSION);
TCLAP::ValueArg<std::string> subdirArg
("s", "subdir", "Subdirectory to use",
false, "", "string", cmd);
TCLAP::ValueArg<std::string> workdirArg
("d", "work-dir", "Working directory to use",
false, work_dir, "string", cmd);
TCLAP::ValueArg<std::string> bufferSizeArg
("b", "buffer-size", "Buffer size to use",
false, "10M", "size", cmd);
TCLAP::ValueArg<int> maxFilesArg
("f", "max-open-files", "Maximum number of open files",
false, max_files, "number", cmd);
TCLAP::ValueArg<int> threadsArg
("j", "threads", "Number of threads to use",
false, parallel, "threads", cmd);
TCLAP::SwitchArg verboseArg
("", "verbose", "Verbose output", cmd, false);
TCLAP::SwitchArg noCompressionArg
("", "no-compression", "Disable compression", cmd, false);
TCLAP::SwitchArg keepFilesArg
("", "keep-tmpfiles", "Keep the temporary files after completion",
cmd, false);
TCLAP::SwitchArg mapOnlyArg
("", "map-only", "Only perform the mapping stage", cmd, false);
TCLAP::SwitchArg reduceOnlyArg
("", "reduce-only", "Only perform the reduce stage", cmd, false);
TCLAP::UnlabeledValueArg<std::string> pluginArg
("plugin", "Plugin file to use", true, "", "plugin file", cmd);
cmd.parse (argc, argv);
subdir = subdirArg.getValue();
work_dir = workdirArg.getValue();
buffer_size = config.parse_size (bufferSizeArg.getValue());
max_files = maxFilesArg.getValue();
parallel = threadsArg.getValue();
verbose = verboseArg.getValue();
keep_tmpfiles = keepFilesArg.getValue();
map_only = mapOnlyArg.getValue();
reduce_only = reduceOnlyArg.getValue();
plugin_path = pluginArg.getValue();
if (!directory::exists(work_dir))
{
throw TCLAP::ArgException
("The working directory '" + work_dir + "' does not exist",
"work-dir");
}
if (max_files < 3)
{
throw TCLAP::ArgException
("Can not work with less than 3 files", "max-open-files");
}
if (reduce_only && map_only)
{
throw TCLAP::ArgException
("Options --map-only and --reduce-only are mutually exclusive",
"map_only");
}
if (map_only && subdir.empty())
{
throw TCLAP::ArgException
("Option --map-only cannot be used without --subdir",
"map-only");
}
if (reduce_only && subdir.empty())
{
throw TCLAP::ArgException
("Option --reduce-only cannot be used without --subdir",
"reduce-only");
}
}
catch (const TCLAP::ArgException& e)
{
std::cerr << "error: " << e.error() << " for " << e.argId()
<< std::endl;
return (1);
}
if (verbose) config.set_verbose();
if (compression) config.set_compressed();
if (keep_tmpfiles) config.set_keep_tmpfiles();
try
{
if (reduce_only)
{
reduce (plugin_path, work_dir, subdir, verbose, parallel,
max_files);
}
else
{
run (plugin_path, work_dir, subdir, verbose, buffer_size,
parallel, max_files, map_only);
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libgen.h>
#include <dlfcn.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <stdexcept>
#include <tclap/CmdLine.h>
#include <mapredo/settings.h>
#include <mapredo/engine.h>
#include <mapredo/base.h>
#include <mapredo/plugin_loader.h>
#include <mapredo/directory.h>
static double time_since (const std::chrono::high_resolution_clock::time_point& time)
{
auto duration = std::chrono::duration_cast<std::chrono::duration<double>>
(std::chrono::high_resolution_clock::now() - time);
return duration.count();
}
static void reduce (const std::string& plugin_file,
const std::string& work_dir,
const std::string& subdir,
const bool verbose,
const int parallel,
const int max_files)
{
if (verbose)
{
std::cerr << "Using working directory " << work_dir << "\n";
std::cerr << "Using " << parallel << " threads,"
<< " with HW concurrency at "
<< std::thread::hardware_concurrency()
<< "\n";
}
plugin_loader plugin (plugin_file);
auto& mapreducer (plugin.get());
engine mapred_engine (work_dir, subdir, parallel, 0, max_files);
auto start_time = std::chrono::high_resolution_clock::now();
mapred_engine.reduce (mapreducer, plugin);
if (verbose)
{
std::cerr << "Merging finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
}
static void run (const std::string& plugin_file,
const std::string& work_dir,
const std::string& subdir,
const bool verbose,
const size_t buffer_size,
const int parallel,
const int max_files,
const bool map_only)
{
plugin_loader plugin (plugin_file);
auto& mapreducer (plugin.get());
engine mapred_engine (work_dir, subdir, parallel, buffer_size, max_files);
size_t buf_size = 0x2000;
std::unique_ptr<char[]> buf (new char[buf_size]);
size_t start = 0, end = 0;
size_t i;
ssize_t bytes;
std::string line;
bool first = true;
std::chrono::high_resolution_clock::time_point start_time;
while ((bytes = read(STDIN_FILENO, buf.get() + end, buf_size - end)) > 0)
{
end += bytes;
if (first)
{
first = false;
// Skip any Windows style UTF-8 header
unsigned char u8header[] = {0xef, 0xbb, 0xbf};
if (end - start >= 3 && memcmp(buf.get() + start, u8header, 3) == 0)
{
start += 3;
}
start_time = std::chrono::high_resolution_clock::now();
mapred_engine.enable_sorters (mapreducer.type(),
false);
if (verbose)
{
std::cerr << "Using working directory " << work_dir << "\n";
std::cerr << "Maximum buffer size is " << buffer_size
<< " bytes.\nUsing " << parallel << " threads,"
<< " with HW concurrency at "
<< std::thread::hardware_concurrency()
<< "\n";
}
}
for (i = start; i < end; i++)
{
if (buf[i] == '\n')
{
if (i == start || buf[i-1] != '\r')
{
buf[i] = '\0';
mapreducer.map(buf.get() + start, i - start, mapred_engine);
}
else
{
buf[i-1] = '\0';
mapreducer.map (buf.get() + start, i - start - 1,
mapred_engine);
}
start = i + 1;
}
}
if (start < i)
{
if (start == 0)
{
buf_size *= 2; // double line buffer
char* nbuf = new char[buf_size];
memcpy (nbuf, buf.get(), end);
buf.reset (nbuf);
}
memmove (buf.get(), buf.get() + start, end - start);
end -= start;
start = 0;
}
else start = end = 0;
}
if (first) return; // no input
if (verbose)
{
std::cerr << "Sorting finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
if (!map_only)
{
mapred_engine.flush (mapreducer, plugin);
if (verbose)
{
std::cerr << "Merging finished in " << std::fixed
<< time_since (start_time) << "s\n";
}
}
else mapred_engine.flush();
}
static std::string get_default_workdir()
{
return TMPDIR;
}
int
main (int argc, char* argv[])
{
int64_t buffer_size = 10 * 1024 * 1024;
int parallel = std::thread::hardware_concurrency();
int max_files = 20 * parallel;
bool verbose = false;
bool compression = true;
std::string subdir;
std::string work_dir = get_default_workdir();
bool map_only = false;
bool reduce_only = false;
bool keep_tmpfiles = false;
std::string plugin_path;
settings& config (settings::instance());
try
{
TCLAP::CmdLine cmd ("mapredo: Map-reduce engine for small/medium data",
' ', PACKAGE_VERSION);
TCLAP::ValueArg<std::string> subdirArg
("s", "subdir", "Subdirectory to use",
false, "", "string", cmd);
TCLAP::ValueArg<std::string> workdirArg
("d", "work-dir", "Working directory to use",
false, work_dir, "string", cmd);
TCLAP::ValueArg<std::string> bufferSizeArg
("b", "buffer-size", "Buffer size to use",
false, "10M", "size", cmd);
TCLAP::ValueArg<int> maxFilesArg
("f", "max-open-files", "Maximum number of open files",
false, max_files, "number", cmd);
TCLAP::ValueArg<int> threadsArg
("j", "threads", "Number of threads to use",
false, parallel, "threads", cmd);
TCLAP::SwitchArg verboseArg
("", "verbose", "Verbose output", cmd, false);
TCLAP::SwitchArg noCompressionArg
("", "no-compression", "Disable compression", cmd, false);
TCLAP::SwitchArg keepFilesArg
("", "keep-tmpfiles", "Keep the temporary files after completion",
cmd, false);
TCLAP::SwitchArg mapOnlyArg
("", "map-only", "Only perform the mapping stage", cmd, false);
TCLAP::SwitchArg reduceOnlyArg
("", "reduce-only", "Only perform the reduce stage", cmd, false);
TCLAP::UnlabeledValueArg<std::string> pluginArg
("plugin", "Plugin file to use", true, "", "plugin file", cmd);
cmd.parse (argc, argv);
subdir = subdirArg.getValue();
work_dir = workdirArg.getValue();
buffer_size = config.parse_size (bufferSizeArg.getValue());
max_files = maxFilesArg.getValue();
parallel = threadsArg.getValue();
verbose = verboseArg.getValue();
keep_tmpfiles = keepFilesArg.getValue();
map_only = mapOnlyArg.getValue();
reduce_only = reduceOnlyArg.getValue();
plugin_path = pluginArg.getValue();
if (!directory::exists(work_dir))
{
throw TCLAP::ArgException
("The working directory '" + work_dir + "' does not exist",
"work-dir");
}
if (max_files < 3)
{
throw TCLAP::ArgException
("Can not work with less than 3 files", "max-open-files");
}
if (reduce_only && map_only)
{
throw TCLAP::ArgException
("Options --map-only and --reduce-only are mutually exclusive",
"map_only");
}
if (map_only && subdir.empty())
{
throw TCLAP::ArgException
("Option --map-only cannot be used without --subdir",
"map-only");
}
if (reduce_only && subdir.empty())
{
throw TCLAP::ArgException
("Option --reduce-only cannot be used without --subdir",
"reduce-only");
}
}
catch (const TCLAP::ArgException& e)
{
std::cerr << "error: " << e.error() << " for " << e.argId()
<< std::endl;
return (1);
}
if (verbose) config.set_verbose();
if (compression) config.set_compressed();
if (keep_tmpfiles) config.set_keep_tmpfiles();
try
{
if (reduce_only)
{
reduce (plugin_path, work_dir, subdir, verbose, parallel,
max_files);
}
else
{
run (plugin_path, work_dir, subdir, verbose, buffer_size,
parallel, max_files, map_only);
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
|
Update type for flags
|
Update type for flags
|
C++
|
lgpl-2.1
|
Hextremist/mapredo,Hextremist/mapredo
|
6c7e6a2d408335b1130f8fccae70c6194c53e708
|
frontend/main.cpp
|
frontend/main.cpp
|
#include <initializer_list>
#include <cstdio>
#include <string>
#include <stdarg.h>
#include <HuffmanArchive.h>
#include <HuffmanDearchive.h>
/*int test_deflate(FILE* input, FILE* output) {
printf("deflate\n");
return 0;
}
int test_inflate(FILE* input, FILE* output) {
printf("inflate\n");
return 0;
}*/
#define BACKEND_DEFLATE archive
#define BACKEND_INFLATE dearchive
bool verbose = false;
size_t eprintf(const char* fmt, ...) {
if (verbose) {
va_list vp;
va_start(vp, fmt);
vprintf(fmt, vp);
}
}
bool outputTree = false;
void usage(char* name) {
printf("Usage:\n"
"%s <x|p> [-v|--verbose] [-i <input file>] [-o <output file>]\n"
"First argument without a leading dash must be x (extract) or p (pack)\n",
name);
exit(0);
}
int main(int argc, char** argv) {
char* name = argv[0];
char action = 'n';
std::string inputFilename;
std::string outputFilename;
argc--; argv++;
while (argc) {
std::string arg = argv[0];
eprintf("Got commandline arg '%s'\n", argv[0]);
if (arg == "-v" || arg == "--verbose") {
verbose = true;
} else if (arg == "-o" || arg == "--output") {
outputFilename = argv[1];
argc--; argv++;
} else if (arg == "-i" || arg == "--input") {
inputFilename = argv[1];
argc--; argv++;
} else if (arg == "-t" || arg == "--tree") {
outputTree = true;
} else {
if (action == 'n' && arg != "x" && arg != "p") {
usage(name);
} else if (action == 'n' && (arg == "x" || arg == "p")) {
action = arg[0];
}
}
argc--; argv++;
}
eprintf("Input from: ");
FILE* input;
if (inputFilename.empty()) {
eprintf("stdin\n");
input = stdin;
} else {
eprintf("file '%s'\n", inputFilename.c_str());
input = fopen(inputFilename.c_str(), "rb");
}
eprintf("Output to: ");
FILE* output;
if (outputFilename.empty()) {
eprintf("stdout\n");
output = stdout;
} else {
eprintf("file '%s'\n", outputFilename.c_str());
output = fopen(outputFilename.c_str(), "wb");
}
if (action == 'p') {
eprintf("Beginning deflate\n");
return BACKEND_DEFLATE(input, output);
} else if (action == 'x') {
eprintf("Beginning inflate\n");
return BACKEND_INFLATE(input, output);
}
}
|
#include <initializer_list>
#include <cstdio>
#include <string>
#include <stdarg.h>
#include <HuffmanArchive.h>
#include <HuffmanDearchive.h>
/*int test_deflate(FILE* input, FILE* output) {
printf("deflate\n");
return 0;
}
int test_inflate(FILE* input, FILE* output) {
printf("inflate\n");
return 0;
}*/
#define BACKEND_DEFLATE archive
#define BACKEND_INFLATE dearchive
bool verbose = false;
size_t eprintf(const char* fmt, ...) {
if (verbose) {
va_list vp;
va_start(vp, fmt);
vprintf(fmt, vp);
}
}
bool outputTree = false;
void usage(char* name) {
printf("Usage:\n"
"%s <x|p> [-v|--verbose] [-t|--tree] [-i <input file>] [-o <output file>]\n"
"First argument without a leading dash must be x (extract) or p (pack)\n",
name);
exit(0);
}
int main(int argc, char** argv) {
char* name = argv[0];
char action = 'n';
std::string inputFilename;
std::string outputFilename;
argc--; argv++;
while (argc) {
std::string arg = argv[0];
eprintf("Got commandline arg '%s'\n", argv[0]);
if (arg == "-v" || arg == "--verbose") {
verbose = true;
} else if (arg == "-o" || arg == "--output") {
outputFilename = argv[1];
argc--; argv++;
} else if (arg == "-i" || arg == "--input") {
inputFilename = argv[1];
argc--; argv++;
} else if (arg == "-t" || arg == "--tree") {
outputTree = true;
} else {
if (action == 'n' && arg != "x" && arg != "p") {
usage(name);
} else if (action == 'n' && (arg == "x" || arg == "p")) {
action = arg[0];
}
}
argc--; argv++;
}
eprintf("Input from: ");
FILE* input;
if (inputFilename.empty()) {
eprintf("stdin\n");
input = stdin;
} else {
eprintf("file '%s'\n", inputFilename.c_str());
input = fopen(inputFilename.c_str(), "rb");
}
eprintf("Output to: ");
FILE* output;
if (outputFilename.empty()) {
eprintf("stdout\n");
output = stdout;
} else {
eprintf("file '%s'\n", outputFilename.c_str());
output = fopen(outputFilename.c_str(), "wb");
}
if (action == 'p') {
eprintf("Beginning deflate\n");
return BACKEND_DEFLATE(input, output);
} else if (action == 'x') {
eprintf("Beginning inflate\n");
return BACKEND_INFLATE(input, output);
}
}
|
add usage decl for tree stats
|
add usage decl for tree stats
|
C++
|
mit
|
volkfm98/Huffman,volkfm98/Huffman
|
b255669497470352ea9db24d1f46b8f9b0432269
|
source/QXmppArchiveIq.cpp
|
source/QXmppArchiveIq.cpp
|
/*
* Copyright (C) 2010 Bolloré telecom
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppArchiveIq.h"
#include "QXmppUtils.h"
#include <QDebug>
#include <QDomElement>
static const char *ns_archive = "urn:xmpp:archive";
static QString dateToString(const QDateTime &dt)
{
return dt.toUTC().toString(Qt::ISODate) + ".000000Z";
}
static QDateTime stringToDate(const QString &str)
{
QDateTime dt = QDateTime::fromString(str, Qt::ISODate);
dt.setTimeSpec(Qt::UTC);
return dt;
}
bool QXmppArchiveChatIq::isArchiveChatIq( QDomElement &element )
{
QDomElement chatElement = element.firstChildElement("chat");
return !chatElement.attribute("with").isEmpty();
//return (chatElement.namespaceURI() == ns_archive);
}
QXmppArchiveChat QXmppArchiveChatIq::getChat() const
{
return m_chat;
}
void QXmppArchiveChatIq::parse( QDomElement &element )
{
QDomElement chatElement = element.firstChildElement("chat");
m_chat.subject = chatElement.attribute("subject");
m_chat.start = stringToDate(chatElement.attribute("start"));
m_chat.version = chatElement.attribute("version").toInt();
m_chat.with = chatElement.attribute("with");
QDomElement child = chatElement.firstChildElement();
while (!child.isNull())
{
if ((child.tagName() == "from") || (child.tagName() == "to"))
{
QXmppArchiveMessage message;
message.datetime = m_chat.start.addSecs(child.attribute("secs").toInt());
message.body = child.firstChildElement("body").text();
message.local = (child.tagName() == "to");
m_chat.messages << message;
}
child = child.nextSiblingElement();
}
}
QXmppArchiveListIq::QXmppArchiveListIq()
: QXmppIq(QXmppIq::Get), m_max(0)
{
}
QList<QXmppArchiveChat> QXmppArchiveListIq::getChats() const
{
return m_chats;
}
int QXmppArchiveListIq::getMax() const
{
return m_max;
}
void QXmppArchiveListIq::setMax(int max)
{
m_max = max;
}
QString QXmppArchiveListIq::getWith() const
{
return m_with;
}
void QXmppArchiveListIq::setWith( const QString &with )
{
m_with = with;
}
QDateTime QXmppArchiveListIq::getStart() const
{
return m_start;
}
void QXmppArchiveListIq::setStart( const QDateTime &start )
{
m_start = start;
}
QDateTime QXmppArchiveListIq::getEnd() const
{
return m_end;
}
void QXmppArchiveListIq::setEnd( const QDateTime &end )
{
m_end = end;
}
bool QXmppArchiveListIq::isArchiveListIq( QDomElement &element )
{
QDomElement listElement = element.firstChildElement("list");
return (listElement.namespaceURI() == ns_archive);
}
void QXmppArchiveListIq::parse( QDomElement &element )
{
QDomElement listElement = element.firstChildElement("list");
m_with = element.attribute("with");
QDomElement child = listElement.firstChildElement();
while (!child.isNull())
{
if (child.tagName() == "chat")
{
QXmppArchiveChat chat;
chat.with = child.attribute("with");
chat.start = stringToDate(child.attribute("start"));
m_chats << chat;
}
child = child.nextSiblingElement();
}
}
void QXmppArchiveListIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("list");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
if (!m_with.isEmpty())
helperToXmlAddAttribute(writer, "with", m_with);
if (m_start.isValid())
helperToXmlAddAttribute(writer, "start", dateToString(m_start));
if (m_end.isValid())
helperToXmlAddAttribute(writer, "end", dateToString(m_start));
if (m_max > 0)
{
writer->writeStartElement("set");
helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm");
if (m_max > 0)
helperToXmlAddTextElement(writer, "max", QString::number(m_max));
writer->writeEndElement();
}
writer->writeEndElement();
}
bool QXmppArchivePrefIq::isArchivePrefIq( QDomElement &element )
{
QDomElement prefElement = element.firstChildElement("pref");
return (prefElement.namespaceURI() == ns_archive);
}
void QXmppArchivePrefIq::parse( QDomElement &element )
{
QDomElement queryElement = element.firstChildElement("pref");
//setId( element.attribute("id"));
}
void QXmppArchivePrefIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("pref");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
writer->writeEndElement();
}
QXmppArchiveRetrieveIq::QXmppArchiveRetrieveIq()
: QXmppIq(QXmppIq::Get), m_max(0)
{
}
int QXmppArchiveRetrieveIq::getMax() const
{
return m_max;
}
void QXmppArchiveRetrieveIq::setMax(int max)
{
m_max = max;
}
QDateTime QXmppArchiveRetrieveIq::getStart() const
{
return m_start;
}
void QXmppArchiveRetrieveIq::setStart( const QDateTime &start )
{
m_start = start;
}
QString QXmppArchiveRetrieveIq::getWith() const
{
return m_with;
}
void QXmppArchiveRetrieveIq::setWith( const QString &with )
{
m_with = with;
}
void QXmppArchiveRetrieveIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("retrieve");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
helperToXmlAddAttribute(writer, "with", m_with);
helperToXmlAddAttribute(writer, "start", dateToString(m_start));
if (m_max > 0)
{
writer->writeStartElement("set");
helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm");
if (m_max > 0)
helperToXmlAddTextElement(writer, "max", QString::number(m_max));
writer->writeEndElement();
}
writer->writeEndElement();
}
|
/*
* Copyright (C) 2010 Bolloré telecom
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppArchiveIq.h"
#include "QXmppUtils.h"
#include <QDebug>
#include <QDomElement>
static const char *ns_archive = "urn:xmpp:archive";
bool QXmppArchiveChatIq::isArchiveChatIq( QDomElement &element )
{
QDomElement chatElement = element.firstChildElement("chat");
return !chatElement.attribute("with").isEmpty();
//return (chatElement.namespaceURI() == ns_archive);
}
QXmppArchiveChat QXmppArchiveChatIq::getChat() const
{
return m_chat;
}
void QXmppArchiveChatIq::parse( QDomElement &element )
{
QDomElement chatElement = element.firstChildElement("chat");
m_chat.subject = chatElement.attribute("subject");
m_chat.start = datetimeFromString(chatElement.attribute("start"));
m_chat.version = chatElement.attribute("version").toInt();
m_chat.with = chatElement.attribute("with");
QDomElement child = chatElement.firstChildElement();
while (!child.isNull())
{
if ((child.tagName() == "from") || (child.tagName() == "to"))
{
QXmppArchiveMessage message;
message.datetime = m_chat.start.addSecs(child.attribute("secs").toInt());
message.body = child.firstChildElement("body").text();
message.local = (child.tagName() == "to");
m_chat.messages << message;
}
child = child.nextSiblingElement();
}
}
QXmppArchiveListIq::QXmppArchiveListIq()
: QXmppIq(QXmppIq::Get), m_max(0)
{
}
QList<QXmppArchiveChat> QXmppArchiveListIq::getChats() const
{
return m_chats;
}
int QXmppArchiveListIq::getMax() const
{
return m_max;
}
void QXmppArchiveListIq::setMax(int max)
{
m_max = max;
}
QString QXmppArchiveListIq::getWith() const
{
return m_with;
}
void QXmppArchiveListIq::setWith( const QString &with )
{
m_with = with;
}
QDateTime QXmppArchiveListIq::getStart() const
{
return m_start;
}
void QXmppArchiveListIq::setStart( const QDateTime &start )
{
m_start = start;
}
QDateTime QXmppArchiveListIq::getEnd() const
{
return m_end;
}
void QXmppArchiveListIq::setEnd( const QDateTime &end )
{
m_end = end;
}
bool QXmppArchiveListIq::isArchiveListIq( QDomElement &element )
{
QDomElement listElement = element.firstChildElement("list");
return (listElement.namespaceURI() == ns_archive);
}
void QXmppArchiveListIq::parse( QDomElement &element )
{
QDomElement listElement = element.firstChildElement("list");
m_with = element.attribute("with");
QDomElement child = listElement.firstChildElement();
while (!child.isNull())
{
if (child.tagName() == "chat")
{
QXmppArchiveChat chat;
chat.with = child.attribute("with");
chat.start = datetimeFromString(child.attribute("start"));
m_chats << chat;
}
child = child.nextSiblingElement();
}
}
void QXmppArchiveListIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("list");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
if (!m_with.isEmpty())
helperToXmlAddAttribute(writer, "with", m_with);
if (m_start.isValid())
helperToXmlAddAttribute(writer, "start", datetimeToString(m_start));
if (m_end.isValid())
helperToXmlAddAttribute(writer, "end", datetimeToString(m_start));
if (m_max > 0)
{
writer->writeStartElement("set");
helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm");
if (m_max > 0)
helperToXmlAddTextElement(writer, "max", QString::number(m_max));
writer->writeEndElement();
}
writer->writeEndElement();
}
bool QXmppArchivePrefIq::isArchivePrefIq( QDomElement &element )
{
QDomElement prefElement = element.firstChildElement("pref");
return (prefElement.namespaceURI() == ns_archive);
}
void QXmppArchivePrefIq::parse( QDomElement &element )
{
QDomElement queryElement = element.firstChildElement("pref");
//setId( element.attribute("id"));
}
void QXmppArchivePrefIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("pref");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
writer->writeEndElement();
}
QXmppArchiveRetrieveIq::QXmppArchiveRetrieveIq()
: QXmppIq(QXmppIq::Get), m_max(0)
{
}
int QXmppArchiveRetrieveIq::getMax() const
{
return m_max;
}
void QXmppArchiveRetrieveIq::setMax(int max)
{
m_max = max;
}
QDateTime QXmppArchiveRetrieveIq::getStart() const
{
return m_start;
}
void QXmppArchiveRetrieveIq::setStart( const QDateTime &start )
{
m_start = start;
}
QString QXmppArchiveRetrieveIq::getWith() const
{
return m_with;
}
void QXmppArchiveRetrieveIq::setWith( const QString &with )
{
m_with = with;
}
void QXmppArchiveRetrieveIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const
{
writer->writeStartElement("retrieve");
helperToXmlAddAttribute(writer, "xmlns", ns_archive);
helperToXmlAddAttribute(writer, "with", m_with);
helperToXmlAddAttribute(writer, "start", datetimeToString(m_start));
if (m_max > 0)
{
writer->writeStartElement("set");
helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm");
if (m_max > 0)
helperToXmlAddTextElement(writer, "max", QString::number(m_max));
writer->writeEndElement();
}
writer->writeEndElement();
}
|
use new datetimeTo/FromString functions
|
use new datetimeTo/FromString functions
|
C++
|
lgpl-2.1
|
LightZam/qxmpp,cccco/qxmpp,ycsoft/qxmpp,gotomypc/qxmpp,unisontech/qxmpp,pol51/QXMPP-CMake,projedi/qxmpp-ffmpeg,ycsoft/qxmpp,olesalscheider/qxmpp,cccco/qxmpp,LightZam/qxmpp,kollix/qxmpp,trulabs/qxmpp-old,Ilyatk/qxmpp,gotomypc/qxmpp,gamenet/qxmpp,KangLin/qxmpp,gamenet/qxmpp,LightZam/qxmpp,unisontech/qxmpp,Kaffeine/qxmpp,pol51/QXMPP-CMake,deepak899/qxmpp,kollix/qxmpp,deepak899/qxmpp,gamenet/qxmpp_old,KangLin/qxmpp,unisontech/qxmpp,trulabs/qxmpp-old,Kaffeine/qxmpp,pol51/QXMPP-CMake,gamenet/qxmpp_old,gotomypc/qxmpp,gamenet/qxmpp,ycsoft/qxmpp,olesalscheider/qxmpp,projedi/qxmpp-ffmpeg,Kaffeine/qxmpp,kollix/qxmpp,gamenet/qxmpp_old,olesalscheider/qxmpp,deepak899/qxmpp,Ilyatk/qxmpp,KangLin/qxmpp,Ilyatk/qxmpp,cccco/qxmpp,trulabs/qxmpp-old
|
c344c4732fa92ac3de8d03d703d8768363df8d81
|
Quad2/Libraries/Quad_Reciever/receiver.cpp
|
Quad2/Libraries/Quad_Reciever/receiver.cpp
|
/*
* receiver.cpp
*
* Created on: May 26, 2013
* Author: Ryler Hockenbury
*
* Library to read and process PPM input from stick
* NOTE: 6 channel AR6210 receiver from Spektrum
*
*/
#include <arduino.h>
#include "receiver.h"
#include "../Quad_Math/math.h"
#include "../Quad_Defines/globals.h"
#include "../Quad_LED/LED.h"
AR6210::AR6210()
{
channelStartTime = 0.0;
currentChannel = 0;
syncCounter = 0;
for(uint8_t channel = 0; channel < MAX_CHANNELS; channel++)
{
rawChannelValue[channel] = STICK_COMMAND_MID;
smoothChannelValue[channel] = STICK_COMMAND_MID;
if(channel == THROTTLE_CHANNEL) {
rawChannelValue[channel] = STICK_COMMAND_MIN;
smoothChannelValue[channel] = STICK_COMMAND_MIN;
}
// we need to set a safe value for aux1 and aux2
smoothFactor[channel] = 0.95;
scaleFactor[channel] = 0.0;
}
}
/*
* Initialize receiver interrupts
*/
void AR6210::init() {
vehicleStatus = vehicleStatus | RX_READY;
pinMode(PPM_PIN, INPUT);
attachInterrupt(0, handleReceiverInterruptHelper, RISING);
}
/*
* A workaround to force attachInterrupt to call a class method
*/
void handleReceiverInterruptHelper() {
receiver.readChannels();
}
/*
* Read receiver channels and synchronize
*/
void AR6210::readChannels() {
// could have rollover problem here
Serial.println("reading channels");
unsigned int currentTime = micros(); // maybe millis()??? /////
// test branch change 2
unsigned int channelWidth = currentTime - channelStartTime;
if(currentChannel == MAX_CHANNELS) { // in frame space
if(channelWidth < MIN_FRAME_WIDTH)
channelSync();
else
currentChannel = 0;
}
else {
if(channelWidth > MAX_CHANNEL_WIDTH || channelWidth < MIN_CHANNEL_WIDTH)
channelSync();
else {
rawChannelValue[currentChannel] = channelWidth;
//smoothChannelValue = smoothChannels();
currentChannel++;
}
}
channelStartTime = currentTime;
}
/*
* Force channel reader to synchronize with PPM pulses
*/
void AR6210::channelSync() {
Serial.println("resyncing");
currentChannel = MAX_CHANNELS;
syncCounter++;
}
/*
* Smooth and scale stick inputs
*/
float AR6210::smoothChannels() {
return filter::LPF( (float) rawChannelValue[currentChannel], smoothChannelValue[currentChannel],
smoothFactor[currentChannel]) / scaleFactor[currentChannel];
}
/*
* Process system setup stick commands
*/
void AR6210::processInitCommands(ITG3200 *gyro, ADXL345 *accel, HMC5883L *comp) {
// We will keep polling the stick commands until
// the operator initializes the sensors and motors.
Serial.println(SYSTEM_ONLINE);
while(!SYSTEM_ONLINE) {
//if(!SENSORS_ONLINE) { LED::LEDBlink(RED_LED_PIN, 1, 1000); }
//if(!MOTORS_ONLINE) { LED::LEDBlink(YELLOW_LED_PIN, 1, 1000); }
// Initialize the sensors when right stick is in bottom right position, and
// left stick is in bottom left position
// should disable interrupts
// hopefully should see these change with stick
Serial.println(rawChannelValue[THROTTLE_CHANNEL]);
Serial.println(rawChannelValue[ROLL_CHANNEL]);
Serial.println(rawChannelValue[PITCH_CHANNEL]);
Serial.println(rawChannelValue[YAW_CHANNEL]);
Serial.println(rawChannelValue[AUX1_CHANNEL]);
Serial.println(rawChannelValue[AUX2_CHANNEL]);
// change back to smooth
if(rawChannelValue[THROTTLE_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[YAW_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[PITCH_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[ROLL_CHANNEL] < STICK_MINCHECK) {
// initialize IMU
Serial.println("Initializing IMU");
//gyro->init();
//accel->init();
//comp->init();
Serial.println(SYSTEM_ONLINE);
// initialize current / voltage sensor
//if(SENSORS_ONLINE) { LED::turnLEDon(RED_LED_PIN); }
}
// arm motors
//if(smoothChannelValue[PITCH_CHANNEL] < STICK_MINCHECK && smoothChannelValue[ROLL_CHANNEL] < STICK_MINCHECK)
//{
// arm motors -> flash some LEDs to show craft is waiting for pilot
// arm the motors
// stop blinking yellow lED
// set motors to min value
//onGround = FALSE;
// }
}
}
/*
* Safely access shared stick command values
*/
void AR6210::getStickCommands(float stickCommands[MAX_CHANNELS]) {
uint8_t SaveSREG = SREG; // save interrupt flag
cli(); // disable interrupts
for(uint8_t channel = 0; channel < MAX_CHANNELS; channel++)
stickCommands[channel] = rawChannelValue[channel]; //smoothChannelValue[channel];
SREG = SaveSREG; // restore the interrupt flag
}
/*
* Convert a raw stick value to a flight angle
*/
float AR6210::mapStickCommandToAngle(float stickCommand) {
//The min.(max.) pulse length should map to -45(+45) degrees
return (0.09*stickCommand - 135.0);
}
/*
* Convert a raw stick value to a ON/OFF state
*/
bool AR6210::mapStickCommandToBool(float stickCommand) {
if(stickCommand < 1500)
return FALSE;
else
return TRUE;
}
/*
* Return the sync counter
*/
uint32_t AR6210::getSyncCounter() {
return syncCounter;
}
/*
* Set the smooth factor
*/
void AR6210::setSmoothFactor(float factor[MAX_CHANNELS]) {
for(int i = 0; i < MAX_CHANNELS; i++) {
smoothFactor[i] = factor[i];
}
}
/*
* Set the scale factor
*/
void AR6210::setScaleFactor(float factor[MAX_CHANNELS]) {
for(int i = 0; i < MAX_CHANNELS; i++) {
scaleFactor[i] = factor[i];
}
}
|
/*
* receiver.cpp
*
* Created on: May 26, 2013
* Author: Ryler Hockenbury
*
* Library to read and process PPM input from stick
* NOTE: 6 channel AR6210 receiver from Spektrum
*
*/
#include <arduino.h>
#include "receiver.h"
#include "../Quad_Math/math.h"
#include "../Quad_Defines/globals.h"
#include "../Quad_LED/LED.h"
AR6210::AR6210()
{
channelStartTime = 0.0;
currentChannel = 0;
syncCounter = 0;
for(uint8_t channel = 0; channel < MAX_CHANNELS; channel++)
{
rawChannelValue[channel] = STICK_COMMAND_MID;
smoothChannelValue[channel] = STICK_COMMAND_MID;
if(channel == THROTTLE_CHANNEL) {
rawChannelValue[channel] = STICK_COMMAND_MIN;
smoothChannelValue[channel] = STICK_COMMAND_MIN;
}
// we need to set a safe value for aux1 and aux2
smoothFactor[channel] = 0.95;
scaleFactor[channel] = 0.0;
}
}
/*
* Initialize receiver interrupts
*/
void AR6210::init() {
vehicleStatus = vehicleStatus | RX_READY;
pinMode(PPM_PIN, INPUT);
attachInterrupt(0, handleReceiverInterruptHelper, RISING);
}
/*
* A workaround to force attachInterrupt to call a class method
*/
void handleReceiverInterruptHelper() {
receiver.readChannels();
}
/*
* Read receiver channels and synchronize
*/
void AR6210::readChannels() {
// could have rollover problem here
Serial.println("reading channels");
unsigned int currentTime = millis(); //micros();
unsigned int channelWidth = currentTime - channelStartTime;
if(currentChannel == MAX_CHANNELS) { // should be in frame space
if(channelWidth < MIN_FRAME_WIDTH)
channelSync();
else
currentChannel = 0;
}
else {
if(channelWidth > MAX_CHANNEL_WIDTH || channelWidth < MIN_CHANNEL_WIDTH) // glitch filter
channelSync();
else {
rawChannelValue[currentChannel] = channelWidth;
//smoothChannelValue = smoothChannels();
currentChannel++;
}
}
channelStartTime = currentTime;
}
/*
* Force channel reader to synchronize with PPM pulses
*/
void AR6210::channelSync() {
Serial.println("resyncing");
currentChannel = MAX_CHANNELS;
syncCounter++;
}
/*
* Smooth and scale stick inputs
*/
float AR6210::smoothChannels() {
return filter::LPF( (float) rawChannelValue[currentChannel], smoothChannelValue[currentChannel],
smoothFactor[currentChannel]) / scaleFactor[currentChannel];
}
/*
* Process system setup stick commands
*/
void AR6210::processInitCommands(ITG3200 *gyro, ADXL345 *accel, HMC5883L *comp) {
// We will keep polling the stick commands until
// the operator initializes the sensors and motors.
Serial.println(SYSTEM_ONLINE);
while(!SYSTEM_ONLINE) {
//if(!SENSORS_ONLINE) { LED::LEDBlink(RED_LED_PIN, 1, 1000); }
//if(!MOTORS_ONLINE) { LED::LEDBlink(YELLOW_LED_PIN, 1, 1000); }
// Initialize the sensors when right stick is in bottom right position, and
// left stick is in bottom left position
// should disable interrupts
// hopefully should see these change with stick
Serial.println(rawChannelValue[THROTTLE_CHANNEL]);
Serial.println(rawChannelValue[ROLL_CHANNEL]);
Serial.println(rawChannelValue[PITCH_CHANNEL]);
Serial.println(rawChannelValue[YAW_CHANNEL]);
Serial.println(rawChannelValue[AUX1_CHANNEL]);
Serial.println(rawChannelValue[AUX2_CHANNEL]);
// change back to smooth
if(rawChannelValue[THROTTLE_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[YAW_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[PITCH_CHANNEL] < STICK_MINCHECK &&
rawChannelValue[ROLL_CHANNEL] < STICK_MINCHECK) {
// initialize IMU
Serial.println("Initializing IMU");
//gyro->init();
//accel->init();
//comp->init();
Serial.println(SYSTEM_ONLINE);
// initialize current / voltage sensor
//if(SENSORS_ONLINE) { LED::turnLEDon(RED_LED_PIN); }
}
// arm motors
//if(smoothChannelValue[PITCH_CHANNEL] < STICK_MINCHECK && smoothChannelValue[ROLL_CHANNEL] < STICK_MINCHECK)
//{
// arm motors -> flash some LEDs to show craft is waiting for pilot
// arm the motors
// stop blinking yellow lED
// set motors to min value
//onGround = FALSE;
// }
}
}
/*
* Safely access shared stick command values
*/
void AR6210::getStickCommands(float stickCommands[MAX_CHANNELS]) {
uint8_t SaveSREG = SREG; // save interrupt flag
cli(); // disable interrupts
for(uint8_t channel = 0; channel < MAX_CHANNELS; channel++)
stickCommands[channel] = rawChannelValue[channel]; //smoothChannelValue[channel];
SREG = SaveSREG; // restore the interrupt flag
}
/*
* Convert a raw stick value to a flight angle
*/
float AR6210::mapStickCommandToAngle(float stickCommand) {
//The min.(max.) pulse length should map to -45(+45) degrees
return (0.09*stickCommand - 135.0);
}
/*
* Convert a raw stick value to a ON/OFF state
*/
bool AR6210::mapStickCommandToBool(float stickCommand) {
if(stickCommand < 1500)
return FALSE;
else
return TRUE;
}
/*
* Return the sync counter
*/
uint32_t AR6210::getSyncCounter() {
return syncCounter;
}
/*
* Set the smooth factor
*/
void AR6210::setSmoothFactor(float factor[MAX_CHANNELS]) {
for(int i = 0; i < MAX_CHANNELS; i++) {
smoothFactor[i] = factor[i];
}
}
/*
* Set the scale factor
*/
void AR6210::setScaleFactor(float factor[MAX_CHANNELS]) {
for(int i = 0; i < MAX_CHANNELS; i++) {
scaleFactor[i] = factor[i];
}
}
|
change to millis
|
change to millis
|
C++
|
mit
|
rhockenbury/Quad2,rhockenbury/Quad2
|
9c8384163f42967045252d4491792a30b52bf066
|
doc/examples/benchmark.cpp
|
doc/examples/benchmark.cpp
|
#include <botan/botan.h>
#include <botan/benchmark.h>
#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
int main(int argc, char* argv[])
{
if(argc <= 2)
{
std::cout << "Usage: " << argv[0] << " ms <algo1> <algo2> ...\n";
return 1;
}
Botan::LibraryInitializer init;
Botan::AutoSeeded_RNG rng;
Botan::Default_Benchmark_Timer timer;
Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();
double ms = std::atof(argv[1]);
for(size_t i = 2; argv[i]; ++i)
{
std::string algo = argv[i];
std::map<std::string, double> results =
Botan::algorithm_benchmark(algo, ms, timer, rng, af);
std::cout << algo << ":\n";
for(std::map<std::string, double>::iterator r = results.begin();
r != results.end(); ++r)
{
std::cout << " " << r->first << ": " << r->second << " MiB/s\n";
}
std::cout << "\n";
}
}
|
#include <botan/botan.h>
#include <botan/benchmark.h>
#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
int main(int argc, char* argv[])
{
if(argc <= 2)
{
std::cout << "Usage: " << argv[0] << " seconds <algo1> <algo2> ...\n";
return 1;
}
Botan::LibraryInitializer init;
Botan::AutoSeeded_RNG rng;
Botan::Default_Benchmark_Timer timer;
Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();
double ms = 1000 * std::atof(argv[1]);
for(size_t i = 2; argv[i]; ++i)
{
std::string algo = argv[i];
std::map<std::string, double> results =
Botan::algorithm_benchmark(algo, ms, timer, rng, af);
std::cout << algo << ":\n";
for(std::map<std::string, double>::iterator r = results.begin();
r != results.end(); ++r)
{
std::cout << " " << r->first << ": " << r->second << " MiB/s\n";
}
std::cout << "\n";
}
}
|
Switch benchmark example command line arg from ms to seconds
|
Switch benchmark example command line arg from ms to seconds
|
C++
|
bsd-2-clause
|
randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan
|
5bc79fb3f1a837b4b4d2e2ebd4ff3eba674a9f84
|
vcl/source/helper/xconnection.cxx
|
vcl/source/helper/xconnection.cxx
|
/*************************************************************************
*
* $RCSfile: xconnection.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: pl $ $Date: 2001-02-01 14:08:05 $
*
* 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 <xconnection.hxx>
#include <svdata.hxx>
#include <salinst.hxx>
using namespace rtl;
using namespace osl;
using namespace vcl;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
DisplayConnection::DisplayConnection()
{
ImplSVData* pSVData = ImplGetSVData();
pSVData->mpDisplayConnection = this;
pSVData->mpDefInst->SetEventCallback( this, dispatchEvent );
pSVData->mpDefInst->SetErrorEventCallback( this, dispatchErrorEvent );
SalInstance::ConnectionIdentifierType eType;
int nBytes;
void* pBytes = pSVData->mpDefInst->GetConnectionIdentifier( eType, nBytes );
switch( eType )
{
case SalInstance::AsciiCString:
m_aAny <<= OUString::createFromAscii( (sal_Char*)pBytes );
break;
case SalInstance::Blob:
m_aAny <<= Sequence< sal_Int8 >( (sal_Int8*)pBytes, nBytes );
break;
}
}
DisplayConnection::~DisplayConnection()
{
ImplSVData* pSVData = ImplGetSVData();
pSVData->mpDisplayConnection = NULL;
pSVData->mpDefInst->SetEventCallback( NULL, NULL );
pSVData->mpDefInst->SetErrorEventCallback( NULL, NULL );
}
void SAL_CALL DisplayConnection::addEventHandler( const Any& window, const Reference< XEventHandler >& handler, sal_Int32 eventMask )
{
MutexGuard aGuard( m_aMutex );
m_aHandlers.push_back( handler );
}
void SAL_CALL DisplayConnection::removeEventHandler( const Any& window, const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aHandlers.remove( handler );
}
void SAL_CALL DisplayConnection::addErrorHandler( const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aErrorHandlers.push_back( handler );
}
void SAL_CALL DisplayConnection::removeErrorHandler( const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aErrorHandlers.remove( handler );
}
Any SAL_CALL DisplayConnection::getIdentifier()
{
return m_aAny;
}
bool DisplayConnection::dispatchEvent( void* pThis, void* pData, int nBytes )
{
DisplayConnection* This = (DisplayConnection*)pThis;
MutexGuard aGuard( This->m_aMutex );
Sequence< sal_Int8 > aSeq( (sal_Int8*)pData, nBytes );
Any aEvent;
aEvent <<= aSeq;
for( ::std::list< Reference< XEventHandler > >::const_iterator it = This->m_aHandlers.begin(); it != This->m_aHandlers.end(); ++it )
if( (*it)->handleEvent( aEvent ) )
return true;
return false;
}
bool DisplayConnection::dispatchErrorEvent( void* pThis, void* pData, int nBytes )
{
DisplayConnection* This = (DisplayConnection*)pThis;
MutexGuard aGuard( This->m_aMutex );
Sequence< sal_Int8 > aSeq( (sal_Int8*)pData, nBytes );
Any aEvent;
aEvent <<= aSeq;
for( ::std::list< Reference< XEventHandler > >::const_iterator it = This->m_aErrorHandlers.begin(); it != This->m_aErrorHandlers.end(); ++it )
if( (*it)->handleEvent( aEvent ) )
return true;
return false;
}
|
/*************************************************************************
*
* $RCSfile: xconnection.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2001-02-05 16:41:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#include <xconnection.hxx>
#include <svdata.hxx>
#include <salinst.hxx>
using namespace rtl;
using namespace osl;
using namespace vcl;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
DisplayConnection::DisplayConnection()
{
ImplSVData* pSVData = ImplGetSVData();
pSVData->mpDisplayConnection = this;
pSVData->mpDefInst->SetEventCallback( this, dispatchEvent );
pSVData->mpDefInst->SetErrorEventCallback( this, dispatchErrorEvent );
SalInstance::ConnectionIdentifierType eType;
int nBytes;
void* pBytes = pSVData->mpDefInst->GetConnectionIdentifier( eType, nBytes );
switch( eType )
{
case SalInstance::AsciiCString:
m_aAny <<= OUString::createFromAscii( (sal_Char*)pBytes );
break;
case SalInstance::Blob:
m_aAny <<= Sequence< sal_Int8 >( (sal_Int8*)pBytes, nBytes );
break;
}
}
DisplayConnection::~DisplayConnection()
{
ImplSVData* pSVData = ImplGetSVData();
pSVData->mpDisplayConnection = NULL;
pSVData->mpDefInst->SetEventCallback( NULL, NULL );
pSVData->mpDefInst->SetErrorEventCallback( NULL, NULL );
}
void SAL_CALL DisplayConnection::addEventHandler( const Any& window, const Reference< XEventHandler >& handler, sal_Int32 eventMask )
{
MutexGuard aGuard( m_aMutex );
m_aHandlers.push_back( handler );
}
void SAL_CALL DisplayConnection::removeEventHandler( const Any& window, const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aHandlers.remove( handler );
}
void SAL_CALL DisplayConnection::addErrorHandler( const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aErrorHandlers.push_back( handler );
}
void SAL_CALL DisplayConnection::removeErrorHandler( const Reference< XEventHandler >& handler )
{
MutexGuard aGuard( m_aMutex );
m_aErrorHandlers.remove( handler );
}
Any SAL_CALL DisplayConnection::getIdentifier()
{
return m_aAny;
}
bool DisplayConnection::dispatchEvent( void* pThis, void* pData, int nBytes )
{
DisplayConnection* This = (DisplayConnection*)pThis;
MutexGuard aGuard( This->m_aMutex );
Sequence< sal_Int8 > aSeq( (sal_Int8*)pData, nBytes );
Any aEvent;
aEvent <<= aSeq;
for( ::std::list< Reference< XEventHandler > >::const_iterator it = This->m_aHandlers.begin(); it != This->m_aHandlers.end(); ++it )
if( (*it)->handleEvent( aEvent ) )
return true;
return false;
}
bool DisplayConnection::dispatchErrorEvent( void* pThis, void* pData, int nBytes )
{
DisplayConnection* This = (DisplayConnection*)pThis;
MutexGuard aGuard( This->m_aMutex );
Sequence< sal_Int8 > aSeq( (sal_Int8*)pData, nBytes );
Any aEvent;
aEvent <<= aSeq;
for( ::std::list< Reference< XEventHandler > >::const_iterator it = This->m_aErrorHandlers.begin(); it != This->m_aErrorHandlers.end(); ++it )
if( (*it)->handleEvent( aEvent ) )
return true;
return false;
}
|
add include svsys.h
|
add include svsys.h
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
a987f84c713853e4691efd919aa0a4a1f58c30ae
|
platform/spark/modules/eGUI/D4D/low_level_drivers/LCD/lcd_hw_interface/spi_spark_8bit/d4dlcdhw_spi_spark_8b.cpp
|
platform/spark/modules/eGUI/D4D/low_level_drivers/LCD/lcd_hw_interface/spi_spark_8bit/d4dlcdhw_spi_spark_8b.cpp
|
/**************************************************************************
* Copyright 2015 by Elco Jacobs, BrewPi
* Copyright 2014 by Petr Gargulak. eGUI Community.
* Copyright 2009-2013 by Petr Gargulak. Freescale Semiconductor, Inc.
*
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License Version 3
* or later (the "LGPL").
*
* As a special exception, the copyright holders of the eGUI project give you
* permission to link the eGUI sources with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library.
* If you modify the eGUI sources, you may extend this exception
* to your version of the eGUI sources, but you are not obligated
* to do so. If you do not wish to do so, delete this
* exception statement from your 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.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
***************************************************************************//*!
*
* @file d4dlcdhw_spi_spark_8b.c
*
* @author Elco Jacobs
*
* @version 0.0.1.0
*
* @date Feb-2015
*
* @brief D4D driver - spi_8b hardware lcd driver for spark platform - source c file
*
******************************************************************************/
extern "C" {
#include "d4d.h" // include of all public items (types, function etc) of D4D driver
#include "common_files/d4d_lldapi.h" // include non public low level driver interface header file (types, function prototypes, enums etc. )
#include "common_files/d4d_private.h" // include the private header file that contains perprocessor macros as D4D_MK_STR
}
#include "application.h"
// identification string of driver - must be same as name D4DTCH_FUNCTIONS structure + "_ID"
// it is used for enable the code for compilation
#define d4dlcdhw_spi_spark_8b_ID 1
// compilation enable preprocessor condition
// the string d4dtch_spi_spark_8b_ID must be replaced by define created one line up
#if (D4D_MK_STR(D4D_LLD_LCD_HW) == d4dlcdhw_spi_spark_8b_ID)
// include of low level driver header file
// it will be included into whole project only in case that this driver is selected in main D4D configuration file
#include "low_level_drivers/LCD/lcd_hw_interface/spi_spark_8bit/d4dlcdhw_spi_spark_8b.h"
/******************************************************************************
* Macros
******************************************************************************/
#if D4D_COLOR_SYSTEM != D4D_COLOR_SYSTEM_RGB565
#error The eGUI low level driver "d4dlcdhw_spi_spark_8b" not supported selected type of D4D_COLOR_SYSTEM. To run this driver just select D4D_COLOR_SYSTEM_RGB565.
#endif
/******************************************************************************
* Internal function prototypes
******************************************************************************/
static unsigned char D4DLCDHW_Init_Spi_Spark_8b(void);
static unsigned char D4DLCDHW_DeInit_Spi_Spark_8b(void);
static void D4DLCDHW_SendDataWord_Spi_Spark_8b(unsigned short value);
static void D4DLCDHW_SendCmdWord_Spi_Spark_8b(unsigned short cmd);
static unsigned short D4DLCDHW_ReadDataWord_Spi_Spark_8b(void);
static unsigned short D4DLCDHW_ReadCmdWord_Spi_Spark_8b(void);
static unsigned char D4DLCDHW_PinCtl_Spi_Spark_8b(D4DLCDHW_PINS pinId, D4DHW_PIN_STATE setState);
static void D4DLCD_FlushBuffer_Spi_Spark_8b(D4DLCD_FLUSH_MODE mode);
static void D4DLCDHW_Delay_Spi_Spark_8b(unsigned short period);
/**************************************************************//*!
*
* Global variables
*
******************************************************************/
// the main structure that contains low level driver api functions
// the name of this structure is used for recognizing of configured low level driver of whole D4D
// so this name has to be used in main configuration header file of D4D driver to enable this driver
extern "C" const D4DLCDHW_FUNCTIONS d4dlcdhw_spi_spark_8b ={
D4DLCDHW_Init_Spi_Spark_8b,
D4DLCDHW_SendDataWord_Spi_Spark_8b,
D4DLCDHW_SendCmdWord_Spi_Spark_8b,
D4DLCDHW_ReadDataWord_Spi_Spark_8b,
D4DLCDHW_ReadCmdWord_Spi_Spark_8b,
D4DLCDHW_PinCtl_Spi_Spark_8b,
D4DLCD_FlushBuffer_Spi_Spark_8b,
D4DLCDHW_DeInit_Spi_Spark_8b,
};
/**************************************************************//*!
*
* Local variables
*
******************************************************************/
#define SCREEN_DATA_BUFFER_SIZE 320
static uint8_t tx_buffer[2][SCREEN_DATA_BUFFER_SIZE];
/**
* The index of the currently active buffer. This buffer is written to by calls to
*/
static int8_t active_buffer_idx = 0;
/**
* The byte offset in the active buffer where the next byte can be written to.
*/
static uint16_t active_buffer_offset = 0;
/**
* The buffer that is currently being read by DMA. When -1, no buffer is being read.
*/
static volatile int8_t dma_buffer_idx = -1;
/**
* Determines if there is data to send.
*/
inline uint16_t hasPendingDataToSend()
{
return active_buffer_offset;
}
/**
* Waits for the asynchronous transfer to complete.
*/
inline void waitForTransferToComplete()
{
while (dma_buffer_idx>=0);
}
/**
* Notification that the DMA transfer was complete.
*/
void transferComplete()
{
dma_buffer_idx = -1;
D4DLCD_DEASSERT_CS;
}
inline void scheduleTransfer(uint8_t* data, uint16_t length)
{
waitForTransferToComplete();
D4DLCD_ASSERT_CS;
#if 0 // DMA
SPI.transfer(data, NULL, length, transferComplete);
#else
while (length-->0) {
SPI.transfer(*data++);
}
transferComplete();
#endif
}
/**
* Ensures any pending data to send to the device is flushed asynchronously.
* To wait for the data to be flushed, call waitForTransferComplete().
*/
inline void flushData()
{
if (hasPendingDataToSend())
{
scheduleTransfer(tx_buffer[active_buffer_idx], active_buffer_offset);
active_buffer_idx++;
active_buffer_idx &= 0x1;
active_buffer_offset = 0;
if (active_buffer_idx==dma_buffer_idx)
waitForTransferToComplete();
}
}
/**************************************************************//*!
*
* Functions bodies
*
******************************************************************/
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_Init_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function is used for initialization of this low level driver
//
// PARAMETERS: none
//
// RETURNS: result: 1 - Success
// 0 - Failed
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_Init_Spi_Spark_8b(void) {
#ifdef D4DLCD_DISPLAY_MCU_USER_INIT
D4DLCD_DISPLAY_MCU_USER_INIT
#endif
D4DLCD_DEASSERT_CS;
D4DLCD_ASSERT_DC;
D4DLCD_INIT_CS;
D4DLCD_INIT_DC;
// Serial clock cycle is min 150ns from ILI93841 datasheet, which equals 6.7 MHz
// But touch screen driver (XPT2046) needs 200ns low, 200ns high.
// 1 /( 72 MHz / 29) = 403 ns. Prescaler of 32 gives a bit of margin.
SPI.setClockDivider(
#if PLATFORM_ID==0
SPI_CLOCK_DIV32
#elif PLATFORM_ID==6
SPI_CLOCK_DIV64
#else
#error Unknown platform
#endif
);
SPI.begin(D4DLCD_CS);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
D4DLCD_DEASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(5);
D4DLCD_ASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(20);
D4DLCD_DEASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(150);
return 1;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_DeInit_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function is used for deinitialization of this low level driver
//
// PARAMETERS: none
//
// RETURNS: result: 1 - Success
// 0 - Failed
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_DeInit_Spi_Spark_8b(void) {
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_SendDataWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function send the one 16 bit variable into LCD
//
// PARAMETERS: unsigned short value variable to send
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCDHW_SendDataWord_Spi_Spark_8b(unsigned short value) {
#if 1
tx_buffer[active_buffer_idx][active_buffer_offset++] = value;
if (active_buffer_offset>=SCREEN_DATA_BUFFER_SIZE)
{
flushData();
}
#else
D4DLCD_ASSERT_CS;
// Send data byte
SPI.transfer(value);
D4DLCD_DEASSERT_CS;
#endif
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_SendCmdWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function send the one 16 bit command into LCD
//
// PARAMETERS: unsigned short cmd command to send
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCDHW_SendCmdWord_Spi_Spark_8b(unsigned short cmd) {
flushData();
waitForTransferToComplete();
D4DLCD_ASSERT_DC; // DataCmd := 0
D4DLCD_ASSERT_CS;
// Send data byte
SPI.transfer(cmd);
D4DLCD_DEASSERT_CS;
D4DLCD_DEASSERT_DC; // DataCmd := 1
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_ReadDataWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function reads the one 16 bit variable from LCD (if this function is supported)
//
// PARAMETERS: none
//
// RETURNS: unsigned short - the readed value
//
//-----------------------------------------------------------------------------
static unsigned short D4DLCDHW_ReadDataWord_Spi_Spark_8b(void) {
/*D4DLCD_DEASSERT_DC;
D4DLCD_ASSERT_CS;
digitalWrite(_cs, LOW);
unsigned short r = SPI.transfer(0x00);
D4DLCD_DEASSERT_CS;
return r;*/
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_ReadCmdWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function reads the one 16 bit command from LCD (if this function is supported)
//
// PARAMETERS: none
//
// RETURNS: unsigned short - the readed value
//
//-----------------------------------------------------------------------------
static unsigned short D4DLCDHW_ReadCmdWord_Spi_Spark_8b(void) {
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_PinCtl_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: allows control GPIO pins for LCD control purposes
//
// PARAMETERS: D4DLCDHW_PINS pinId - Pin identification
// D4DHW_PIN_STATE setState - Pin action
// RETURNS: for Get action returns the pin value
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_PinCtl_Spi_Spark_8b(D4DLCDHW_PINS pinId, D4DHW_PIN_STATE setState) {
switch (pinId) {
case D4DLCD_RESET_PIN:
switch (setState) {
#if defined(D4DLCD_RESET)
case D4DHW_PIN_OUT:
OUTPUT(D4DLCD_RESET);
break;
case D4DHW_PIN_IN:
INPUT(D4DLCD_RESET);
break;
case D4DHW_PIN_SET_1:
D4DLCD_DEASSERT_RESET
break;
case D4DHW_PIN_SET_0:
D4DLCD_ASSERT_RESET;
break;
#endif
}
break;
case D4DLCD_BACKLIGHT_PIN:
switch (setState) {
#ifdef D4DLCD_BACKLIGHT
case D4DHW_PIN_OUT:
OUTPUT(D4DLCD_BACKLIGHT);
break;
case D4DHW_PIN_IN:
INPUT(D4DLCD_BACKLIGHT);
break;
case D4DHW_PIN_SET_1:
D4DLCD_DEASSERT_BACKLIGHT
break;
case D4DHW_PIN_SET_0:
D4DLCD_ASSERT_BACKLIGHT;
break;
#endif
}
break;
}
return 1;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCD_FlushBuffer_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: For buffered low level interfaces is used to inform
// driver the complete object is drawed and pending pixels should be flushed
//
// PARAMETERS: none
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCD_FlushBuffer_Spi_Spark_8b(D4DLCD_FLUSH_MODE mode) {
if (true || mode==D4DLCD_FLSH_SCR_END || mode==D4DLCD_FLSH_FORCE) {
flushData();
}
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_Delay_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: For do some small delays in ms
//
// PARAMETERS: period - count of ms
//
// RETURNS: none
//-----------------------------------------------------------------------------
/**************************************************************************/ /*!
* @brief For do some small delays in ms
* @param period - 1ms periods time
* @return none
* @note This function is just used to do some delays of eGUI (just for initialization purposes, not for run)
*******************************************************************************/
static void D4DLCDHW_Delay_Spi_Spark_8b(unsigned short period){
delay(period);
}
#endif //(D4D_MK_STR(D4D_LLD_LCD_HW) == d4dlcdhw_spi_8b_ID)
|
/**************************************************************************
* Copyright 2015 by Elco Jacobs, BrewPi
* Copyright 2014 by Petr Gargulak. eGUI Community.
* Copyright 2009-2013 by Petr Gargulak. Freescale Semiconductor, Inc.
*
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License Version 3
* or later (the "LGPL").
*
* As a special exception, the copyright holders of the eGUI project give you
* permission to link the eGUI sources with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library.
* If you modify the eGUI sources, you may extend this exception
* to your version of the eGUI sources, but you are not obligated
* to do so. If you do not wish to do so, delete this
* exception statement from your 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.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
***************************************************************************//*!
*
* @file d4dlcdhw_spi_spark_8b.c
*
* @author Elco Jacobs
*
* @version 0.0.1.0
*
* @date Feb-2015
*
* @brief D4D driver - spi_8b hardware lcd driver for spark platform - source c file
*
******************************************************************************/
extern "C" {
#include "d4d.h" // include of all public items (types, function etc) of D4D driver
#include "common_files/d4d_lldapi.h" // include non public low level driver interface header file (types, function prototypes, enums etc. )
#include "common_files/d4d_private.h" // include the private header file that contains perprocessor macros as D4D_MK_STR
}
#include "application.h"
// identification string of driver - must be same as name D4DTCH_FUNCTIONS structure + "_ID"
// it is used for enable the code for compilation
#define d4dlcdhw_spi_spark_8b_ID 1
// compilation enable preprocessor condition
// the string d4dtch_spi_spark_8b_ID must be replaced by define created one line up
#if (D4D_MK_STR(D4D_LLD_LCD_HW) == d4dlcdhw_spi_spark_8b_ID)
// include of low level driver header file
// it will be included into whole project only in case that this driver is selected in main D4D configuration file
#include "low_level_drivers/LCD/lcd_hw_interface/spi_spark_8bit/d4dlcdhw_spi_spark_8b.h"
/******************************************************************************
* Macros
******************************************************************************/
#if D4D_COLOR_SYSTEM != D4D_COLOR_SYSTEM_RGB565
#error The eGUI low level driver "d4dlcdhw_spi_spark_8b" not supported selected type of D4D_COLOR_SYSTEM. To run this driver just select D4D_COLOR_SYSTEM_RGB565.
#endif
/******************************************************************************
* Internal function prototypes
******************************************************************************/
static unsigned char D4DLCDHW_Init_Spi_Spark_8b(void);
static unsigned char D4DLCDHW_DeInit_Spi_Spark_8b(void);
static void D4DLCDHW_SendDataWord_Spi_Spark_8b(unsigned short value);
static void D4DLCDHW_SendCmdWord_Spi_Spark_8b(unsigned short cmd);
static unsigned short D4DLCDHW_ReadDataWord_Spi_Spark_8b(void);
static unsigned short D4DLCDHW_ReadCmdWord_Spi_Spark_8b(void);
static unsigned char D4DLCDHW_PinCtl_Spi_Spark_8b(D4DLCDHW_PINS pinId, D4DHW_PIN_STATE setState);
static void D4DLCD_FlushBuffer_Spi_Spark_8b(D4DLCD_FLUSH_MODE mode);
static void D4DLCDHW_Delay_Spi_Spark_8b(unsigned short period);
/**************************************************************//*!
*
* Global variables
*
******************************************************************/
// the main structure that contains low level driver api functions
// the name of this structure is used for recognizing of configured low level driver of whole D4D
// so this name has to be used in main configuration header file of D4D driver to enable this driver
extern "C" const D4DLCDHW_FUNCTIONS d4dlcdhw_spi_spark_8b ={
D4DLCDHW_Init_Spi_Spark_8b,
D4DLCDHW_SendDataWord_Spi_Spark_8b,
D4DLCDHW_SendCmdWord_Spi_Spark_8b,
D4DLCDHW_ReadDataWord_Spi_Spark_8b,
D4DLCDHW_ReadCmdWord_Spi_Spark_8b,
D4DLCDHW_PinCtl_Spi_Spark_8b,
D4DLCD_FlushBuffer_Spi_Spark_8b,
D4DLCDHW_DeInit_Spi_Spark_8b,
};
/**************************************************************//*!
*
* Local variables
*
******************************************************************/
#define SCREEN_DATA_BUFFER_SIZE 320
static uint8_t tx_buffer[2][SCREEN_DATA_BUFFER_SIZE];
/**
* The index of the currently active buffer. This buffer is written to by calls to
*/
static int8_t active_buffer_idx = 0;
/**
* The byte offset in the active buffer where the next byte can be written to.
*/
static uint16_t active_buffer_offset = 0;
/**
* The buffer that is currently being read by DMA. When -1, no buffer is being read.
*/
static volatile int8_t dma_buffer_idx = -1;
/**
* Determines if there is data to send.
*/
inline uint16_t hasPendingDataToSend()
{
return active_buffer_offset;
}
/**
* Waits for the asynchronous transfer to complete.
*/
inline void waitForTransferToComplete()
{
while (dma_buffer_idx>=0);
}
/**
* Notification that the DMA transfer was complete.
*/
void transferComplete()
{
dma_buffer_idx = -1;
D4DLCD_DEASSERT_CS;
}
inline void scheduleTransfer(uint8_t* data, uint16_t length)
{
waitForTransferToComplete();
D4DLCD_ASSERT_CS;
#if 1 // DMA
SPI.transfer(data, NULL, length, NULL);
transferComplete();
#else
while (length-->0) {
SPI.transfer(*data++);
}
transferComplete();
#endif
}
/**
* Ensures any pending data to send to the device is flushed asynchronously.
* To wait for the data to be flushed, call waitForTransferComplete().
*/
inline void flushData()
{
if (hasPendingDataToSend())
{
scheduleTransfer(tx_buffer[active_buffer_idx], active_buffer_offset);
active_buffer_idx++;
active_buffer_idx &= 0x1;
active_buffer_offset = 0;
if (active_buffer_idx==dma_buffer_idx)
waitForTransferToComplete();
}
}
/**************************************************************//*!
*
* Functions bodies
*
******************************************************************/
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_Init_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function is used for initialization of this low level driver
//
// PARAMETERS: none
//
// RETURNS: result: 1 - Success
// 0 - Failed
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_Init_Spi_Spark_8b(void) {
#ifdef D4DLCD_DISPLAY_MCU_USER_INIT
D4DLCD_DISPLAY_MCU_USER_INIT
#endif
D4DLCD_DEASSERT_CS;
D4DLCD_ASSERT_DC;
D4DLCD_INIT_CS;
D4DLCD_INIT_DC;
// Serial clock cycle is min 150ns from ILI93841 datasheet, which equals 6.7 MHz
// But touch screen driver (XPT2046) needs 200ns low, 200ns high.
// 1 /( 72 MHz / 29) = 403 ns. Prescaler of 32 gives a bit of margin.
SPI.setClockDivider(
#if PLATFORM_ID==0
SPI_CLOCK_DIV32
#elif PLATFORM_ID==6
SPI_CLOCK_DIV64
#else
#error Unknown platform
#endif
);
SPI.begin(D4DLCD_CS);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
D4DLCD_DEASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(5);
D4DLCD_ASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(20);
D4DLCD_DEASSERT_RESET;
D4DLCDHW_Delay_Spi_Spark_8b(150);
return 1;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_DeInit_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function is used for deinitialization of this low level driver
//
// PARAMETERS: none
//
// RETURNS: result: 1 - Success
// 0 - Failed
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_DeInit_Spi_Spark_8b(void) {
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_SendDataWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function send the one 16 bit variable into LCD
//
// PARAMETERS: unsigned short value variable to send
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCDHW_SendDataWord_Spi_Spark_8b(unsigned short value) {
#if 1
tx_buffer[active_buffer_idx][active_buffer_offset++] = value;
if (active_buffer_offset>=SCREEN_DATA_BUFFER_SIZE)
{
flushData();
}
#else
D4DLCD_ASSERT_CS;
// Send data byte
SPI.transfer(value);
D4DLCD_DEASSERT_CS;
#endif
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_SendCmdWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function send the one 16 bit command into LCD
//
// PARAMETERS: unsigned short cmd command to send
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCDHW_SendCmdWord_Spi_Spark_8b(unsigned short cmd) {
flushData();
waitForTransferToComplete();
D4DLCD_ASSERT_DC; // DataCmd := 0
D4DLCD_ASSERT_CS;
// Send data byte
SPI.transfer(cmd);
D4DLCD_DEASSERT_CS;
D4DLCD_DEASSERT_DC; // DataCmd := 1
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_ReadDataWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function reads the one 16 bit variable from LCD (if this function is supported)
//
// PARAMETERS: none
//
// RETURNS: unsigned short - the readed value
//
//-----------------------------------------------------------------------------
static unsigned short D4DLCDHW_ReadDataWord_Spi_Spark_8b(void) {
/*D4DLCD_DEASSERT_DC;
D4DLCD_ASSERT_CS;
digitalWrite(_cs, LOW);
unsigned short r = SPI.transfer(0x00);
D4DLCD_DEASSERT_CS;
return r;*/
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_ReadCmdWord_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: The function reads the one 16 bit command from LCD (if this function is supported)
//
// PARAMETERS: none
//
// RETURNS: unsigned short - the readed value
//
//-----------------------------------------------------------------------------
static unsigned short D4DLCDHW_ReadCmdWord_Spi_Spark_8b(void) {
return 0;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_PinCtl_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: allows control GPIO pins for LCD control purposes
//
// PARAMETERS: D4DLCDHW_PINS pinId - Pin identification
// D4DHW_PIN_STATE setState - Pin action
// RETURNS: for Get action returns the pin value
//-----------------------------------------------------------------------------
static unsigned char D4DLCDHW_PinCtl_Spi_Spark_8b(D4DLCDHW_PINS pinId, D4DHW_PIN_STATE setState) {
switch (pinId) {
case D4DLCD_RESET_PIN:
switch (setState) {
#if defined(D4DLCD_RESET)
case D4DHW_PIN_OUT:
OUTPUT(D4DLCD_RESET);
break;
case D4DHW_PIN_IN:
INPUT(D4DLCD_RESET);
break;
case D4DHW_PIN_SET_1:
D4DLCD_DEASSERT_RESET
break;
case D4DHW_PIN_SET_0:
D4DLCD_ASSERT_RESET;
break;
#endif
}
break;
case D4DLCD_BACKLIGHT_PIN:
switch (setState) {
#ifdef D4DLCD_BACKLIGHT
case D4DHW_PIN_OUT:
OUTPUT(D4DLCD_BACKLIGHT);
break;
case D4DHW_PIN_IN:
INPUT(D4DLCD_BACKLIGHT);
break;
case D4DHW_PIN_SET_1:
D4DLCD_DEASSERT_BACKLIGHT
break;
case D4DHW_PIN_SET_0:
D4DLCD_ASSERT_BACKLIGHT;
break;
#endif
}
break;
}
return 1;
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCD_FlushBuffer_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: For buffered low level interfaces is used to inform
// driver the complete object is drawed and pending pixels should be flushed
//
// PARAMETERS: none
//
// RETURNS: none
//-----------------------------------------------------------------------------
static void D4DLCD_FlushBuffer_Spi_Spark_8b(D4DLCD_FLUSH_MODE mode) {
if (true || mode==D4DLCD_FLSH_SCR_END || mode==D4DLCD_FLSH_FORCE) {
flushData();
}
}
//-----------------------------------------------------------------------------
// FUNCTION: D4DLCDHW_Delay_Spi_Spark_8b
// SCOPE: Low Level Driver API function
// DESCRIPTION: For do some small delays in ms
//
// PARAMETERS: period - count of ms
//
// RETURNS: none
//-----------------------------------------------------------------------------
/**************************************************************************/ /*!
* @brief For do some small delays in ms
* @param period - 1ms periods time
* @return none
* @note This function is just used to do some delays of eGUI (just for initialization purposes, not for run)
*******************************************************************************/
static void D4DLCDHW_Delay_Spi_Spark_8b(unsigned short period){
delay(period);
}
#endif //(D4D_MK_STR(D4D_LLD_LCD_HW) == d4dlcdhw_spi_8b_ID)
|
Test synchronous DMA transfer, without callback. Seems to work.
|
Test synchronous DMA transfer, without callback. Seems to work.
|
C++
|
agpl-3.0
|
glibersat/firmware,glibersat/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,glibersat/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,BrewPi/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware
|
9604151f66e946dbe3ea7737d13f9c8b72bed510
|
PHOS/AliPHOSQAVirtualCheckable.cxx
|
PHOS/AliPHOSQAVirtualCheckable.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Abstract Class for a QA checkable
//
//*-- Author : Yves Schutz (SUBATECH)
//////////////////////////////////////////////////////////////////////////////
// --- ROOT system ---
#include "TClass.h"
#include "TFolder.h"
#include "TROOT.h"
#include "TTree.h"
// --- Standard library ---
#include <iostream.h>
// --- AliRoot header files ---
#include "AliPHOSQAVirtualCheckable.h"
#include "AliPHOSQAChecker.h"
#include "AliPHOSQAAlarm.h"
#include "AliPHOSGetter.h"
#include "AliPHOS.h"
ClassImp(AliPHOSQAVirtualCheckable)
//____________________________________________________________________________
AliPHOSQAVirtualCheckable::AliPHOSQAVirtualCheckable(const char * name) : TNamed(name, name)
{
// ctor, creates the task(s)
fType = "" ;
fChange = kFALSE ;
// create a new folder that will hold the list of alarms
// the folder that contains the alarms for PHOS
fAlarms = (TFolder*)gROOT->FindObjectAny("Folders/Run/Conditions/QA/PHOS");
// make it the owner of the objects that it contains
fAlarms->SetOwner() ;
// add the alarms list to //Folders/Run/Conditions/QA/PHOS
TObjArray * alarms = new TObjArray() ; // deleted when fAlarms is deleted
alarms->SetName(name) ;
fAlarms->Add(alarms) ;
fChecker = 0 ;
}
//____________________________________________________________________________
AliPHOSQAVirtualCheckable::~AliPHOSQAVirtualCheckable()
{
// ctor
delete fAlarms ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::AddChecker(AliPHOSQAChecker * ch)
{
// Associates the checkable object with a task (that can be a list of tasks)
ch->AddCheckable(this) ;
if (fChecker)
fChecker->Add(ch) ;
else
fChecker = ch ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::Alarms() const
{
// Prints all the alarms
TObjArray * alarms = GetAlarms() ;
if (alarms->IsEmpty() )
cout << " No alarms raised for checkable " << GetName() << endl ;
else {
TIter next(alarms);
AliPHOSQAAlarm * alarm ;
while ( (alarm = (AliPHOSQAAlarm*)next()) )
alarm->Print() ;
}
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::CheckMe()
{
// All the attached checkers will check this checkable
fChecker->CheckIt(this) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::RaiseAlarm(const char * time, const char * checked, const char * checker, const char * message)
{
// Raise an alarm and store it in the appropriate folder : //Folders/Run/Conditions/QA/PHOS..
// cout << message ;
AliPHOSQAAlarm * alarm = new AliPHOSQAAlarm(time, checked, checker, message) ;
GetAlarms()->Add(alarm) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::RemoveChecker(AliPHOSQAChecker *ch)
{
// Remove the specified checker from the list of tasks
// and the present checkable from the list of checkables of the specified checker
fChecker->Remove(ch) ;
fChecker->GetListOfCheckables()->Remove(this) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::ResetAlarms()
{
// resets the list of alarms (delete the alarms from the list)
TObjArray * alarms = GetAlarms() ;
if (alarms->IsEmpty() )
cout << " No alarms raised for checkable " << GetName() << endl ;
else {
alarms->Delete() ;
cout << " Reset alarms for checkable " << GetName() << endl ;
}
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::Status() const
{
// Tells which checkers are attached to this checkable
TList * list = fChecker->GetListOfTasks();
if (list->IsEmpty() )
cout << "No checkers are in use for " << GetName() << endl ;
else {
cout << "The following checkers are in use for " << GetName() << endl ;
TIter next(list) ;
AliPHOSQAChecker * checker ;
while ( (checker = (AliPHOSQAChecker*)next() ) )
checker->Print() ;
}
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Abstract Class for a QA checkable
//
//*-- Author : Yves Schutz (SUBATECH)
//////////////////////////////////////////////////////////////////////////////
// --- ROOT system ---
#include "TClass.h"
#include "TFolder.h"
#include "TROOT.h"
#include "TTree.h"
// --- Standard library ---
#include <iostream.h>
// --- AliRoot header files ---
#include "AliPHOSQAVirtualCheckable.h"
#include "AliPHOSQAChecker.h"
#include "AliPHOSQAAlarm.h"
#include "AliPHOSGetter.h"
#include "AliPHOS.h"
ClassImp(AliPHOSQAVirtualCheckable)
//____________________________________________________________________________
AliPHOSQAVirtualCheckable::AliPHOSQAVirtualCheckable(const char * name) : TNamed(name, name)
{
// ctor, creates the task(s)
fType = "" ;
fChange = kFALSE ;
// create a new folder that will hold the list of alarms
// the folder that contains the alarms for PHOS
fAlarms = (TFolder*)gROOT->FindObjectAny("Folders/Run/Conditions/QA/PHOS");
// make it the owner of the objects that it contains
fAlarms->SetOwner() ;
// add the alarms list to //Folders/Run/Conditions/QA/PHOS
TObjArray * alarms = new TObjArray() ; // deleted when fAlarms is deleted
alarms->SetOwner() ;
alarms->SetName(name) ;
fAlarms->Add(alarms) ;
fChecker = 0 ;
}
//____________________________________________________________________________
AliPHOSQAVirtualCheckable::~AliPHOSQAVirtualCheckable()
{
// dtor
fAlarms->Clear() ;
delete fAlarms ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::AddChecker(AliPHOSQAChecker * ch)
{
// Associates the checkable object with a task (that can be a list of tasks)
ch->AddCheckable(this) ;
if (fChecker)
fChecker->Add(ch) ;
else
fChecker = ch ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::Alarms() const
{
// Prints all the alarms
TObjArray * alarms = GetAlarms() ;
if (alarms->IsEmpty() )
cout << " No alarms raised for checkable " << GetName() << endl ;
else {
TIter next(alarms);
AliPHOSQAAlarm * alarm ;
while ( (alarm = (AliPHOSQAAlarm*)next()) )
alarm->Print() ;
}
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::CheckMe()
{
// All the attached checkers will check this checkable
fChecker->CheckIt(this) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::RaiseAlarm(const char * time, const char * checked, const char * checker, const char * message)
{
// Raise an alarm and store it in the appropriate folder : //Folders/Run/Conditions/QA/PHOS..
// cout << message ;
AliPHOSQAAlarm * alarm = new AliPHOSQAAlarm(time, checked, checker, message) ;
GetAlarms()->Add(alarm) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::RemoveChecker(AliPHOSQAChecker *ch)
{
// Remove the specified checker from the list of tasks
// and the present checkable from the list of checkables of the specified checker
fChecker->Remove(ch) ;
fChecker->GetListOfCheckables()->Remove(this) ;
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::ResetAlarms()
{
// resets the list of alarms (delete the alarms from the list)
TObjArray * alarms = GetAlarms() ;
if (alarms->IsEmpty() )
cout << " No alarms raised for checkable " << GetName() << endl ;
else {
alarms->Delete() ;
cout << " Reset alarms for checkable " << GetName() << endl ;
}
}
//____________________________________________________________________________
void AliPHOSQAVirtualCheckable::Status() const
{
// Tells which checkers are attached to this checkable
TList * list = fChecker->GetListOfTasks();
if (list->IsEmpty() )
cout << "No checkers are in use for " << GetName() << endl ;
else {
cout << "The following checkers are in use for " << GetName() << endl ;
TIter next(list) ;
AliPHOSQAChecker * checker ;
while ( (checker = (AliPHOSQAChecker*)next() ) )
checker->Print() ;
}
}
|
Set ownership
|
Set ownership
|
C++
|
bsd-3-clause
|
ALICEHLT/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,coppedis/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,alisw/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,alisw/AliRoot,coppedis/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,shahor02/AliRoot
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.