text stringlengths 54 60.6k |
|---|
<commit_before>#include "TRCFileAdapter.h"
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
// Helper lambda to remove empty elements from token lists
auto eraseEmptyElements = [](std::vector<std::string>& list) {
std::vector<std::string>::iterator it = list.begin();
while (it != list.end()) {
if (it->empty())
it = list.erase(it);
else
++it;
}
};
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _delimitersRead);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// for marker labels we do not need three columns per marker.
// remove the blank ones used in TRC due to tabbing
eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine - 1};
auto row = nextLine();
while(!row.empty()) {
if (row.at(0).empty()) { //if no Frame# then ignore as empty elements
row = nextLine();
continue;
}
++line_num;
size_t expected{column_labels.size() * 3 + 2};
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
if (!row.at(c).empty())
row_vector[ind++] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
<commit_msg>Make sure to increment counter(ind) even when next string is empty, so that row_vector element corresponds to NaN.<commit_after>#include "TRCFileAdapter.h"
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
// Helper lambda to remove empty elements from token lists
auto eraseEmptyElements = [](std::vector<std::string>& list) {
std::vector<std::string>::iterator it = list.begin();
while (it != list.end()) {
if (it->empty())
it = list.erase(it);
else
++it;
}
};
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _delimitersRead);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// for marker labels we do not need three columns per marker.
// remove the blank ones used in TRC due to tabbing
eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine - 1};
auto row = nextLine();
while(!row.empty()) {
if (row.at(0).empty()) { //if no Frame# then ignore as empty elements
row = nextLine();
continue;
}
++line_num;
size_t expected{column_labels.size() * 3 + 2};
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
if (!row.at(c).empty())
row_vector[ind] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
++ind;
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2014, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_LU_PANEL_HPP
#define ELEM_LU_PANEL_HPP
#include ELEM_SCALE_INC
#include ELEM_SWAP_INC
#include ELEM_GERU_INC
namespace elem {
namespace lu {
template<typename F>
inline void
Panel( Matrix<F>& A, Matrix<Int>& p, Int pivotOffset=0 )
{
DEBUG_ONLY(CallStackEntry cse("lu::Panel"))
const Int m = A.Height();
const Int n = A.Width();
DEBUG_ONLY(
if( m < n )
LogicError("Must be a column panel");
)
p.Resize( n, 1 );
for( Int k=0; k<n; ++k )
{
auto alpha11 = ViewRange( A, k, k, k+1, k+1 );
auto a12 = ViewRange( A, k, k+1, k+1, n );
auto a21 = ViewRange( A, k+1, k, m, k+1 );
auto A22 = ViewRange( A, k+1, k+1, m, n );
// Find the index and value of the pivot candidate
auto pivot = VectorMax( ViewRange(A,k,k,m,k+1) );
const Int iPiv = pivot.index + k;
p.Set( k, 0, iPiv+pivotOffset );
// Swap the pivot row and current row
if( iPiv != k )
{
auto aCurRow = ViewRange( A, k, 0, k+1, n );
auto aPivRow = ViewRange( A, iPiv, 0, iPiv+1, n );
Swap( NORMAL, aCurRow, aPivRow );
}
// Now we can perform the update of the current panel
const F alpha = alpha11.Get(0,0);
if( alpha == F(0) )
throw SingularMatrixException();
const F alpha11Inv = F(1) / alpha;
Scale( alpha11Inv, a21 );
Geru( F(-1), a21, a12, A22 );
}
}
template<typename F>
inline void
Panel
( DistMatrix<F, STAR,STAR>& A,
DistMatrix<F, MC, STAR>& B,
DistMatrix<Int,STAR,STAR>& p,
Int pivotOffset=0 )
{
DEBUG_ONLY(
CallStackEntry cse("lu::Panel");
if( A.Grid() != p.Grid() || p.Grid() != B.Grid() )
LogicError("Matrices must be distributed over the same grid");
if( A.Width() != B.Width() )
LogicError("A and B must be the same width");
if( A.Height() != p.Height() || p.Width() != 1 )
LogicError("p must be a vector that conforms with A");
)
typedef Base<F> Real;
// For packing rows of data for pivoting
const Int n = A.Width();
const Int mB = B.Height();
const Int nB = B.Width();
std::vector<F> pivotBuffer( n );
for( Int k=0; k<n; ++k )
{
auto alpha11 = ViewRange( A, k, k, k+1, k+1 );
auto a12 = ViewRange( A, k, k+1, k+1, n );
auto a21 = ViewRange( A, k+1, k, n, k+1 );
auto A22 = ViewRange( A, k+1, k+1, n, n );
auto b1 = ViewRange( B, 0, k, mB, k+1 );
auto B2 = ViewRange( B, 0, k+1, mB, nB );
// Store the index/value of the local pivot candidate
ValueInt<Real> localPivot;
localPivot.value = FastAbs(alpha11.GetLocal(0,0));
localPivot.index = k;
for( Int i=0; i<a21.Height(); ++i )
{
const Real value = FastAbs(a21.GetLocal(i,0));
if( value > localPivot.value )
{
localPivot.value = value;
localPivot.index = k + i + 1;
}
}
for( Int iLoc=0; iLoc<B.LocalHeight(); ++iLoc )
{
const Real value = FastAbs(b1.GetLocal(iLoc,0));
if( value > localPivot.value )
{
localPivot.value = value;
localPivot.index = n + B.GlobalRow(iLoc);
}
}
// Compute and store the location of the new pivot
const ValueInt<Real> pivot =
mpi::AllReduce( localPivot, mpi::MaxLocOp<Real>(), B.ColComm() );
const Int iPiv = pivot.index;
p.SetLocal( k, 0, iPiv+pivotOffset );
// Perform the pivot within this panel
if( iPiv < n )
{
// Pack pivot into temporary
for( Int j=0; j<n; ++j )
pivotBuffer[j] = A.GetLocal( iPiv, j );
// Replace pivot with current
for( Int j=0; j<n; ++j )
A.SetLocal( iPiv, j, A.GetLocal(k,j) );
}
else
{
// The owning row of the pivot row packs it into the row buffer
// and then overwrites with the current row
const Int relIndex = iPiv - n;
const Int ownerRow = B.RowOwner(relIndex);
if( B.IsLocalRow(relIndex) )
{
const Int iLoc = B.LocalRow(relIndex);
for( Int j=0; j<n; ++j )
pivotBuffer[j] = B.GetLocal( iLoc, j );
for( Int j=0; j<n; ++j )
B.SetLocal( iLoc, j, A.GetLocal(k,j) );
}
// The owning row broadcasts within process columns
mpi::Broadcast( pivotBuffer.data(), n, ownerRow, B.ColComm() );
}
// Overwrite the current row with the pivot row
for( Int j=0; j<n; ++j )
A.SetLocal( k, j, pivotBuffer[j] );
// Now we can perform the update of the current panel
const F alpha = alpha11.GetLocal(0,0);
if( alpha == F(0) )
throw SingularMatrixException();
const F alpha11Inv = F(1) / alpha;
Scale( alpha11Inv, a21 );
Scale( alpha11Inv, b1 );
Geru( F(-1), a21.Matrix(), a12.Matrix(), A22.Matrix() );
Geru( F(-1), b1.Matrix(), a12.Matrix(), B2.Matrix() );
}
}
} // namespace lu
} // namespace elem
#endif // ifndef ELEM_LU_PANEL_HPP
<commit_msg>Converting panel LU factorization to VectorMaxAbs.<commit_after>/*
Copyright (c) 2009-2014, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_LU_PANEL_HPP
#define ELEM_LU_PANEL_HPP
#include ELEM_SCALE_INC
#include ELEM_SWAP_INC
#include ELEM_MAXABS_INC
#include ELEM_GERU_INC
namespace elem {
namespace lu {
template<typename F>
inline void
Panel( Matrix<F>& A, Matrix<Int>& p, Int pivotOffset=0 )
{
DEBUG_ONLY(CallStackEntry cse("lu::Panel"))
const Int m = A.Height();
const Int n = A.Width();
DEBUG_ONLY(
if( m < n )
LogicError("Must be a column panel");
)
p.Resize( n, 1 );
for( Int k=0; k<n; ++k )
{
auto alpha11 = ViewRange( A, k, k, k+1, k+1 );
auto a12 = ViewRange( A, k, k+1, k+1, n );
auto a21 = ViewRange( A, k+1, k, m, k+1 );
auto A22 = ViewRange( A, k+1, k+1, m, n );
// Find the index and value of the pivot candidate
auto pivot = VectorMaxAbs( ViewRange(A,k,k,m,k+1) );
const Int iPiv = pivot.index + k;
p.Set( k, 0, iPiv+pivotOffset );
// Swap the pivot row and current row
if( iPiv != k )
{
auto aCurRow = ViewRange( A, k, 0, k+1, n );
auto aPivRow = ViewRange( A, iPiv, 0, iPiv+1, n );
Swap( NORMAL, aCurRow, aPivRow );
}
// Now we can perform the update of the current panel
const F alpha = alpha11.Get(0,0);
if( alpha == F(0) )
throw SingularMatrixException();
const F alpha11Inv = F(1) / alpha;
Scale( alpha11Inv, a21 );
Geru( F(-1), a21, a12, A22 );
}
}
template<typename F>
inline void
Panel
( DistMatrix<F, STAR,STAR>& A,
DistMatrix<F, MC, STAR>& B,
DistMatrix<Int,STAR,STAR>& p,
Int pivotOffset=0 )
{
DEBUG_ONLY(
CallStackEntry cse("lu::Panel");
if( A.Grid() != p.Grid() || p.Grid() != B.Grid() )
LogicError("Matrices must be distributed over the same grid");
if( A.Width() != B.Width() )
LogicError("A and B must be the same width");
if( A.Height() != p.Height() || p.Width() != 1 )
LogicError("p must be a vector that conforms with A");
)
typedef Base<F> Real;
// For packing rows of data for pivoting
const Int n = A.Width();
const Int mB = B.Height();
const Int nB = B.Width();
std::vector<F> pivotBuffer( n );
for( Int k=0; k<n; ++k )
{
auto alpha11 = ViewRange( A, k, k, k+1, k+1 );
auto a12 = ViewRange( A, k, k+1, k+1, n );
auto a21 = ViewRange( A, k+1, k, n, k+1 );
auto A22 = ViewRange( A, k+1, k+1, n, n );
auto b1 = ViewRange( B, 0, k, mB, k+1 );
auto B2 = ViewRange( B, 0, k+1, mB, nB );
// Store the index/value of the local pivot candidate
ValueInt<Real> localPivot;
localPivot.value = FastAbs(alpha11.GetLocal(0,0));
localPivot.index = k;
for( Int i=0; i<a21.Height(); ++i )
{
const Real value = FastAbs(a21.GetLocal(i,0));
if( value > localPivot.value )
{
localPivot.value = value;
localPivot.index = k + i + 1;
}
}
for( Int iLoc=0; iLoc<B.LocalHeight(); ++iLoc )
{
const Real value = FastAbs(b1.GetLocal(iLoc,0));
if( value > localPivot.value )
{
localPivot.value = value;
localPivot.index = n + B.GlobalRow(iLoc);
}
}
// Compute and store the location of the new pivot
const ValueInt<Real> pivot =
mpi::AllReduce( localPivot, mpi::MaxLocOp<Real>(), B.ColComm() );
const Int iPiv = pivot.index;
p.SetLocal( k, 0, iPiv+pivotOffset );
// Perform the pivot within this panel
if( iPiv < n )
{
// Pack pivot into temporary
for( Int j=0; j<n; ++j )
pivotBuffer[j] = A.GetLocal( iPiv, j );
// Replace pivot with current
for( Int j=0; j<n; ++j )
A.SetLocal( iPiv, j, A.GetLocal(k,j) );
}
else
{
// The owning row of the pivot row packs it into the row buffer
// and then overwrites with the current row
const Int relIndex = iPiv - n;
const Int ownerRow = B.RowOwner(relIndex);
if( B.IsLocalRow(relIndex) )
{
const Int iLoc = B.LocalRow(relIndex);
for( Int j=0; j<n; ++j )
pivotBuffer[j] = B.GetLocal( iLoc, j );
for( Int j=0; j<n; ++j )
B.SetLocal( iLoc, j, A.GetLocal(k,j) );
}
// The owning row broadcasts within process columns
mpi::Broadcast( pivotBuffer.data(), n, ownerRow, B.ColComm() );
}
// Overwrite the current row with the pivot row
for( Int j=0; j<n; ++j )
A.SetLocal( k, j, pivotBuffer[j] );
// Now we can perform the update of the current panel
const F alpha = alpha11.GetLocal(0,0);
if( alpha == F(0) )
throw SingularMatrixException();
const F alpha11Inv = F(1) / alpha;
Scale( alpha11Inv, a21 );
Scale( alpha11Inv, b1 );
Geru( F(-1), a21.Matrix(), a12.Matrix(), A22.Matrix() );
Geru( F(-1), b1.Matrix(), a12.Matrix(), B2.Matrix() );
}
}
} // namespace lu
} // namespace elem
#endif // ifndef ELEM_LU_PANEL_HPP
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <array>
#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <vector>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>
namespace hadesmem
{
// TODO: Fix the name of this.
// TODO: Port the actual enumeration to a RelocationsList instead, and make this
// class instead for operating on a single base reloc block at a time.
class RelocationsDir
{
public:
explicit RelocationsDir(Process const& process, PeFile const& pe_file)
: process_(&process),
pe_file_(&pe_file),
base_(nullptr),
size_(0U),
invalid_(false),
data_()
{
NtHeaders const nt_headers(process, pe_file);
// TODO: Some sort of API to handle this common case.
DWORD const data_dir_va =
nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::BaseReloc);
size_ = nt_headers.GetDataDirectorySize(PeDataDir::BaseReloc);
if (!data_dir_va || !size_)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("PE file has no relocations directory."));
}
base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, data_dir_va));
if (!base_)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Relocations directory is invalid."));
}
// Cast to integer and back to avoid pointer overflow UB.
auto const relocs_end = reinterpret_cast<void const*>(
reinterpret_cast<std::uintptr_t>(base_) + size_);
auto const file_end =
static_cast<std::uint8_t*>(pe_file.GetBase()) + pe_file.GetSize();
// TODO: Also fix this for images? Or is it discarded?
// TODO: Fix this to handle files with 'virtual' relocs which will still be loaded by Windows.
// Sample: virtrelocXP.exe
if (pe_file.GetType() == hadesmem::PeFileType::Data &&
(relocs_end < base_ || relocs_end > file_end))
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Relocations directory is outside file."));
}
UpdateRead();
}
PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
{
return base_;
}
DWORD GetSize() const HADESMEM_DETAIL_NOEXCEPT
{
return size_;
}
bool IsInvalid() const HADESMEM_DETAIL_NOEXCEPT
{
return invalid_;
}
struct Reloc
{
BYTE type;
WORD offset;
};
struct RelocBlock
{
DWORD va;
DWORD size;
std::vector<Reloc> relocs;
};
void UpdateRead()
{
std::vector<RelocBlock> reloc_blocks;
void* current = base_;
void const* end = static_cast<std::uint8_t*>(base_) + size_;
do
{
auto const reloc_dir =
hadesmem::Read<IMAGE_BASE_RELOCATION>(*process_, current);
// TODO: Check whether this is even valid... Should this mark as invalid
// instead of simply skipping?
if (!reloc_dir.SizeOfBlock)
{
continue;
}
DWORD const num_relocs = static_cast<DWORD>(
(reloc_dir.SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD));
PWORD reloc_data = reinterpret_cast<PWORD>(
static_cast<IMAGE_BASE_RELOCATION*>(current) + 1);
void const* const reloc_data_end = reinterpret_cast<void const*>(
reinterpret_cast<std::uintptr_t>(reloc_data) + num_relocs);
if (reloc_data_end < reloc_data || reloc_data_end > end)
{
invalid_ = true;
break;
}
std::vector<Reloc> relocs;
auto const relocs_raw =
hadesmem::ReadVector<WORD>(*process_, reloc_data, num_relocs);
for (auto const reloc : relocs_raw)
{
BYTE const type = static_cast<BYTE>(reloc >> 12);
WORD const offset = reloc & 0x0FFF;
relocs.emplace_back(Reloc{type, offset});
}
reloc_blocks.emplace_back(RelocBlock{
reloc_dir.VirtualAddress, reloc_dir.SizeOfBlock, std::move(relocs)});
current = reloc_data + num_relocs;
} while (current < end);
data_ = reloc_blocks;
}
// TODO: Add setters and UpdateWrite.
std::vector<RelocBlock> GetRelocBlocks() const
{
return data_;
}
private:
Process const* process_;
PeFile const* pe_file_;
PBYTE base_;
DWORD size_;
bool invalid_;
std::vector<RelocBlock> data_;
};
inline bool operator==(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return !(lhs == rhs);
}
inline bool operator<(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, RelocationsDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, RelocationsDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
}
<commit_msg>* [RelocationsDir] Perf fix.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <array>
#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <vector>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>
namespace hadesmem
{
// TODO: Fix the name of this.
// TODO: Port the actual enumeration to a RelocationsList instead, and make this
// class instead for operating on a single base reloc block at a time.
class RelocationsDir
{
public:
explicit RelocationsDir(Process const& process, PeFile const& pe_file)
: process_(&process),
pe_file_(&pe_file),
base_(nullptr),
size_(0U),
invalid_(false),
data_()
{
NtHeaders const nt_headers(process, pe_file);
// TODO: Some sort of API to handle this common case.
DWORD const data_dir_va =
nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::BaseReloc);
size_ = nt_headers.GetDataDirectorySize(PeDataDir::BaseReloc);
if (!data_dir_va || !size_)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("PE file has no relocations directory."));
}
base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, data_dir_va));
if (!base_)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Relocations directory is invalid."));
}
// Cast to integer and back to avoid pointer overflow UB.
auto const relocs_end = reinterpret_cast<void const*>(
reinterpret_cast<std::uintptr_t>(base_) + size_);
auto const file_end =
static_cast<std::uint8_t*>(pe_file.GetBase()) + pe_file.GetSize();
// TODO: Also fix this for images? Or is it discarded?
// TODO: Fix this to handle files with 'virtual' relocs which will still be loaded by Windows.
// Sample: virtrelocXP.exe
if (pe_file.GetType() == hadesmem::PeFileType::Data &&
(relocs_end < base_ || relocs_end > file_end))
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Relocations directory is outside file."));
}
UpdateRead();
}
PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
{
return base_;
}
DWORD GetSize() const HADESMEM_DETAIL_NOEXCEPT
{
return size_;
}
bool IsInvalid() const HADESMEM_DETAIL_NOEXCEPT
{
return invalid_;
}
struct Reloc
{
BYTE type;
WORD offset;
};
struct RelocBlock
{
DWORD va;
DWORD size;
std::vector<Reloc> relocs;
};
void UpdateRead()
{
std::vector<RelocBlock> reloc_blocks;
void* current = base_;
void const* end = static_cast<std::uint8_t*>(base_) + size_;
do
{
auto const reloc_dir =
hadesmem::Read<IMAGE_BASE_RELOCATION>(*process_, current);
// TODO: Check whether this is even valid... Should this mark as invalid
// instead of simply skipping?
if (!reloc_dir.SizeOfBlock)
{
continue;
}
DWORD const num_relocs = static_cast<DWORD>(
(reloc_dir.SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD));
PWORD reloc_data = reinterpret_cast<PWORD>(
static_cast<IMAGE_BASE_RELOCATION*>(current) + 1);
void const* const reloc_data_end = reinterpret_cast<void const*>(
reinterpret_cast<std::uintptr_t>(reloc_data) + num_relocs);
if (reloc_data_end < reloc_data || reloc_data_end > end)
{
invalid_ = true;
break;
}
std::vector<Reloc> relocs;
auto const relocs_raw =
hadesmem::ReadVector<WORD>(*process_, reloc_data, num_relocs);
for (auto const reloc : relocs_raw)
{
BYTE const type = static_cast<BYTE>(reloc >> 12);
WORD const offset = reloc & 0x0FFF;
relocs.emplace_back(Reloc{type, offset});
}
reloc_blocks.emplace_back(RelocBlock{
reloc_dir.VirtualAddress, reloc_dir.SizeOfBlock, std::move(relocs)});
current = reloc_data + num_relocs;
} while (current < end);
data_ = std::move(reloc_blocks);
}
// TODO: Add setters and UpdateWrite.
std::vector<RelocBlock> GetRelocBlocks() const
{
return data_;
}
private:
Process const* process_;
PeFile const* pe_file_;
PBYTE base_;
DWORD size_;
bool invalid_;
std::vector<RelocBlock> data_;
};
inline bool operator==(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return !(lhs == rhs);
}
inline bool operator<(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(RelocationsDir const& lhs, RelocationsDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, RelocationsDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, RelocationsDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
}
<|endoftext|> |
<commit_before>/**
\file integral.hh
**/
#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM1_INTEGRAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM1_INTEGRAL_HH
// dune-common
#include <dune/common/dynmatrix.hh>
//// dune-fem
//#include <dune/fem/quadrature/cachingquadrature.hh>
// dune-stuff
#include <dune/stuff/common/vector.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteFunctional {
namespace Local {
namespace Codim1 {
template <class LocalEvaluationImp>
class Integral
{
public:
typedef LocalEvaluationImp LocalEvaluationType;
typedef Integral<LocalEvaluationType> ThisType;
typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
Integral(const LocalEvaluationType localEvaluation)
: localEvaluation_(localEvaluation)
{
}
//! copy constructor
Integral(const ThisType& other)
: localEvaluation_(other.localEvaluation())
{
}
LocalEvaluationType localEvaluation() const
{
return localEvaluation_;
}
unsigned int numTmpObjectsRequired() const
{
return 1;
}
template <class LocalTestBaseFunctionSetType, class IntersectionType, class LocalVectorType>
void applyLocal(const LocalTestBaseFunctionSetType localTestBaseFunctionSet, const IntersectionType& intersection,
LocalVectorType& localVector, std::vector<LocalVectorType>& tmpLocalVectors) const
{
assert(false && "Implement me?");
// // some types
// typedef typename LocalTestBaseFunctionSetType::DiscreteFunctionSpaceType
// DiscreteFunctionSpaceType;
// typedef typename DiscreteFunctionSpaceType::GridViewType
// GridViewType;
// typedef Dune::QuadratureRules< double, IntersectionType::mydimension >
// FaceQuadratureRules;
// typedef Dune::QuadratureRule< double, IntersectionType::mydimension >
// FaceQuadratureType;
// typedef typename IntersectionType::LocalCoordinate
// LocalCoordinateType;
// // some stuff
// const unsigned int size = localTestBaseFunctionSet.size();
// const unsigned int quadratureOrder = localEvaluation_.order() + localTestBaseFunctionSet.order();
// const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule( intersection.type(), 2*quadratureOrder+1
// );
// // make sure target vector is big enough
// assert( localVector.size() >= size );
// // clear target vector
// Dune::Stuff::Common::Vector::clear( localVector );
// // check tmp local vectors
// if( tmpLocalVectors.size() < 1 )
// {
// tmpLocalVectors.resize( 1,
// LocalVectorType(
// localTestBaseFunctionSet.baseFunctionSet().space().map().maxLocalSize(),
// RangeFieldType( 0.0 ) ) );
// }
// // do loop over all quadrature points
// const typename FaceQuadratureType::const_iterator quadratureEnd = faceQuadrature.end();
// for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin(); quadPoint !=
// quadratureEnd; ++quadPoint )
// {
// // local coordinate
// const LocalCoordinateType x = quadPoint->position();
// // integration factors
// const double integrationFactor = intersection.geometry().integrationElement( x );
// const double quadratureWeight = quadPoint->weight();
// // evaluate the local evaluation
// localEvaluation_.evaluateLocal( localTestBaseFunctionSet, intersection, x, tmpLocalVectors[0] );
// // compute integral
// for( unsigned int i = 0; i < size; ++i )
// {
// localVector[i] += tmpLocalVectors[0][i] * integrationFactor * quadratureWeight;
// }
// } // done loop over all quadrature points
} // end method applyLocal
private:
//! assignment operator
ThisType& operator=(const ThisType& other);
const LocalEvaluationType localEvaluation_;
}; // end class Integral
// template< class InducingOperatorImp, class InducingDiscreteFunctionImp >
// class IntegralInduced
//{
// public:
// typedef InducingOperatorImp
// InducingOperatorType;
// typedef InducingDiscreteFunctionImp
// InducingDiscreteFunctionType;
// typedef IntegralInduced< InducingOperatorType, InducingDiscreteFunctionType >
// ThisType;
// typedef typename InducingDiscreteFunctionType::RangeFieldType
// RangeFieldType;
// typedef typename InducingDiscreteFunctionType::DomainType
// DomainType;
// IntegralInduced( const InducingOperatorType& inducingOperator,
// const InducingDiscreteFunctionType& inducingDiscreteFunction )
// : inducingOperator_( inducingOperator ),
// inducingDiscreteFunction_( inducingDiscreteFunction )
// {
// }
// //! copy constructor
// IntegralInduced( const ThisType& other )
// : inducingOperator_( other.inducingOperator() ),
// inducingDiscreteFunction_( other.inducingDiscreteFunction() )
// {
// }
// InducingOperatorType inducingOperator() const
// {
// return inducingOperator_;
// }
// InducingDiscreteFunctionType inducingDiscreteFunction() const
// {
// return inducingDiscreteFunction_;
// }
// unsigned int numTmpObjectsRequired() const
// {
// return 0;
// }
// template< class LocalTestBaseFunctionSetType, class LocalVectorType >
// void applyLocal( const LocalTestBaseFunctionSetType& localTestBaseFunctionSet,
// LocalVectorType& localVector,
// std::vector< LocalVectorType >& ) const
// {
// // some types
// typedef typename LocalTestBaseFunctionSetType::DiscreteFunctionSpaceType
// DiscreteFunctionSpaceType;
// typedef typename DiscreteFunctionSpaceType::GridPartType
// GridPartType;
// typedef Dune::CachingQuadrature< GridPartType, 0 >
// VolumeQuadratureType;
// typedef typename LocalTestBaseFunctionSetType::EntityType
// EntityType;
// typedef typename InducingDiscreteFunctionType::ConstLocalFunctionType
// InducingLocalFunctionType;
// typedef typename Dune::Detailed::Discretizations::BaseFunctionSet::Local::Wrapper< InducingLocalFunctionType >
// InducingBaseFunctionSetType;
// typedef Dune::DynamicMatrix< RangeFieldType >
// LocalMatrixType;
// const EntityType& entity = localTestBaseFunctionSet.entity();
// // wrap inducing local function
// const InducingLocalFunctionType inducingLocalFunction = inducingDiscreteFunction_.localFunction( entity );
// const InducingBaseFunctionSetType inducingBaseFunctionSet( inducingLocalFunction );
// // some stuff
// const unsigned int size = localTestBaseFunctionSet.size();
// const unsigned int quadratureOrder =
// inducingOperator_.localEvaluation().order() + inducingLocalFunction.order() + localTestBaseFunctionSet.order();
// const VolumeQuadratureType volumeQuadrature( entity, quadratureOrder );
// const unsigned int numberOfQuadraturePoints = volumeQuadrature.nop();
// // make sure target vector is big enough
// assert( localVector.size() >= size );
// // clear target vector
// Dune::HelperTools::Common::Vector::clear( localVector );
// // do loop over all quadrature points
// LocalMatrixType tmpMatrix( 1, size );
// for( unsigned int q = 0; q < numberOfQuadraturePoints; ++q )
// {
// // local coordinate
// const DomainType x = volumeQuadrature.point( q );
// // integration factors
// const double integrationFactor = entity.geometry().integrationElement( x );
// const double quadratureWeight = volumeQuadrature.weight( q );
// // evaluate the local evaluation
// inducingOperator_.localEvaluation().evaluateLocal( inducingBaseFunctionSet,
// localTestBaseFunctionSet,
// x,
// tmpMatrix );
// // compute integral
// for( unsigned int i = 0; i < size; ++i )
// {
// localVector[i] += tmpMatrix[0][i] * integrationFactor * quadratureWeight;
// }
// } // done loop over all quadrature points
// } // end method applyLocal
// private:
// //! assignment operator
// ThisType& operator=( const ThisType& );
// const InducingOperatorType inducingOperator_;
// const InducingDiscreteFunctionType inducingDiscreteFunction_;
//}; // end class IntegralInduced
} // end namespace Codim1
} // end namespace Local
} // end namespace DiscreteFunctional
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM0_INTEGRAL_HH
<commit_msg>[discretefunctional.local.codim1.integral] implemented Boundary<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM1_INTEGRAL_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM1_INTEGRAL_HH
#include <dune/geometry/quadraturerules.hh>
#include <dune/stuff/common/vector.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
namespace DiscreteFunctional {
namespace Local {
namespace Codim1 {
namespace Integral {
template <class LocalEvaluationImp>
class Boundary
{
public:
typedef LocalEvaluationImp LocalEvaluationType;
typedef Boundary<LocalEvaluationType> ThisType;
typedef typename LocalEvaluationType::FunctionSpaceType FunctionSpaceType;
typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;
typedef typename FunctionSpaceType::DomainType DomainType;
typedef typename FunctionSpaceType::DomainFieldType DomainFieldType;
Boundary(const LocalEvaluationType& _localEvaluation)
: localEvaluation_(_localEvaluation)
{
}
const LocalEvaluationType& localEvaluation() const
{
return localEvaluation_;
}
unsigned int numTmpObjectsRequired() const
{
return 1;
}
template <class LocalTestBaseFunctionSetType, class IntersectionType, class LocalVectorType>
void applyLocal(const LocalTestBaseFunctionSetType localTestBaseFunctionSet, const IntersectionType& intersection,
LocalVectorType& localVector, std::vector<LocalVectorType>& tmpLocalVectors) const
{
// sanity checks
const unsigned int size = localTestBaseFunctionSet.size();
assert(localVector.size() >= size);
if (tmpLocalVectors.size() < numTmpObjectsRequired())
tmpLocalVectors.resize(
numTmpObjectsRequired(),
LocalVectorType(localTestBaseFunctionSet.baseFunctionSet().space().map().maxLocalSize(), RangeFieldType(0)));
// quadrature
const unsigned int quadratureOrder = localEvaluation_.order() + localTestBaseFunctionSet.order();
typedef Dune::QuadratureRules<DomainFieldType, IntersectionType::mydimension> FaceQuadratureRules;
typedef Dune::QuadratureRule<DomainFieldType, IntersectionType::mydimension> FaceQuadratureType;
const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), 2 * quadratureOrder + 1);
// loop over all quadrature points
for (typename FaceQuadratureType::const_iterator quadPoint = faceQuadrature.begin();
quadPoint != faceQuadrature.end();
++quadPoint) {
// coordinates
const typename IntersectionType::LocalCoordinate xIntersection = quadPoint->position();
const DomainType xEntity = intersection.geometryInInside().global(xIntersection);
// integration factors
const double integrationFactor = intersection.geometry().integrationElement(xIntersection);
const double quadratureWeight = quadPoint->weight();
// clear target matrix
Dune::Stuff::Common::clear(tmpLocalVectors[0]);
// evaluate the local operation
localEvaluation_.evaluateLocal(localTestBaseFunctionSet, xEntity, tmpLocalVectors[0]);
// compute integral
for (unsigned int i = 0; i < size; ++i)
localVector[i] += tmpLocalVectors[0][i] * integrationFactor * quadratureWeight;
} // loop over all quadrature points
} // void apply(...)
private:
Boundary(const ThisType&);
ThisType& operator=(const ThisType&);
const LocalEvaluationType& localEvaluation_;
}; // class Boundary
} // namespace Integral
} // namespace Codim1
} // namespace Local
} // namespace DiscreteFunctional
} // namespace Discretizations
} // namespace Detailed
} // namespace Dune
#endif // end DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONAL_LOCAL_CODIM0_INTEGRAL_HH
<|endoftext|> |
<commit_before>/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h> // For multithreading
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include "crypto.h"
#define write cwrite
#define read cread
#include "serverCommands.cpp"
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int sock; /* Socket. I think */
userDB *users; /* Pointer to global users object */
//session_type *sessions; // pointer to global sessions object
// CryptoPP::SecByteBlock session_key;
// string username;
};
//HashMap of usernames to a tuple of user info or user object containing {username, pin, balance}
std::string advanceCommand(const std::string& line, int &index);
void advanceSpaces(const std::string &line, int &index);
void error(const char *msg);
void* consoleThread(void *threadid);
void* socketThread(void* arg);
int main(int argc, char *argv[]) {
if (argc != 2) { // Test for correct number of arguments
std::cerr << "Usage: " << argv[0] << " <Server Port>" << std::endl;
exit(1);
}
// socket initialization
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
std::cerr << "Usage: ATMserver <Port>" << std::endl;
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// assign socket to port number
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("ERROR on binding");
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
pthread_t thread;
thread_info args;
userDB* users = new userDB();
init_bank(users);
args.users = users;
pthread_create(&thread, NULL, consoleThread, &args);
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
error("ERROR on accept");
continue;
}
pthread_t thread;
// thread_info args;
args.sock = newsockfd;
// pid = fork();
pthread_create(&thread, NULL, socketThread, &args);
// close(newsockfd);
// int threadNum* ++;
} /* end of while */
close(newsockfd);
close(sockfd);
//create 2 threads, one for I/O another for incomming connections
return 0;
}
//
void error(const char *msg) {
std::cerr << msg <<std::endl;
// exit(1);
}
// Read input until we read a space, then for each character add it to the command string
std::string advanceCommand(const std::string& line, int &index) {
std::string command = "";
if (index >= line.length()) return command;
for(; line[index] != ' ' && line[index] != '\0' && index < line.length(); index++) {
command += line[index];
}
if (index != line.length()) {
advanceSpaces(line, index);
}
return command;
}
// Skip any number of spaces
void advanceSpaces(const std::string &line, int &index) {
for(; line[index] == ' ' && index < line.length(); index++);
}
std::string genSessionKey(std::string username) {
int secret = rand() % 1000 + 1;
std::stringstream ss;
ss << std::setfill('0') << std::setw(4) << secret;
return username + '_' + ss.str();
}
std::string parseCommands(char buffer[], userDB* users, std::string& sessionKey, int& sentNumber) {
int index = 0;
bool loggedIn = false;
std::string input(buffer);
userInfo *thisUser;
std::string sendStr;
int cliNumber = atoi(advanceCommand(input, index).c_str());
sentNumber ++;
if (cliNumber != sentNumber) {
return "not the message I was expecting";
}
sentNumber ++;
if (sessionKey.length() != 0) {
std::string cliSeshKey = advanceCommand(input, index);
int pos = sessionKey.find('_');
std::string someUser = sessionKey.substr(0, pos);
thisUser = users->findUser(someUser);
if (thisUser == NULL) {
return "session Key has been tampered with";
}
else {
loggedIn = thisUser->isLoggedIn();
}
// checks if user is trying to logout
if (cliSeshKey.compare("logout") == 0 && loggedIn) {
sessionKey = "";
// std::cout << "atm connection ~ : " << "user logged out" << std::endl;
thisUser->logout();
return "logged_out";
}
// checks to see if client's session key equals clients session key
if (sessionKey.compare(cliSeshKey) != 0) return "session key has been tampered with";
}
// std::cout << "session key: " << sessionKey << std::endl;
std::string command = advanceCommand(input, index);
// std::cout << "balance: " << (command.compare("balance") == 0) << " " << loggedIn << std::endl;
if (command.compare("login") == 0) {
std::string username = advanceCommand(input, index);
std::string pin = advanceCommand(input, index);
if (users->loginUser(username, pin)) {
// std::cout << username << " logged in!" << std::endl;
sessionKey = genSessionKey(username);
sendStr = "y " + sessionKey;
}
else {
sendStr = "n";
}
}
else if (command.compare("balance") == 0 && loggedIn) {
sendStr = thisUser->getBalance();
}
else if (command.compare("withdraw") == 0 && loggedIn) {
std::string amount = advanceCommand(input, index);
std::string takenOut = thisUser->withdraw(amount);
sendStr = "withdrew";
}
else if (command.compare("transfer") == 0 && loggedIn) {
std::string amount = advanceCommand(input, index);
std::string sendingTo = advanceCommand(input, index);
users->transfer(thisUser->getName(), sendingTo, amount);
sendStr = "transfered";
}
else if (command.compare("check") == 0 && loggedIn) {
std::string name = advanceCommand(input, index);
bool exists = users->userExists(name);
if (exists) sendStr = "y";
else sendStr = "n";
}
else if (command.compare("init") == 0) {
sendStr = "connected to bank";
}
else {
std::cout << "bad command" << std::endl;
sendStr = "error! bad command!";
}
std::stringstream ss;
ss << sentNumber;
return ss.str() + " " + sendStr;
}
void* socketThread(void* args) {
std::cout << std::endl;
struct thread_info *tinfo;
tinfo = (thread_info *) args;
int sock = tinfo->sock;
userDB *users = tinfo->users;
std::string sessionKey;
int sentNumber = 0;
bool logginIn = false;
while (1) {
int n;
char buffer[256];
char sendBuffer[256];
bzero(buffer,256);
bzero(sendBuffer,256);
n = read(sock,buffer,255);
if (n < 0) {
error("ERROR writing to socket");
close(sock);
break;
}
if (n == 0) {
std::cout << "atm connection ~ : " << "socket# " << sock << " disconnected" << std::endl;
if (sessionKey.length() != 0) {
int pos = sessionKey.find('_');
userInfo *thisUser;
std::string someUser = sessionKey.substr(0, pos);
thisUser = users->findUser(someUser);
thisUser->logout();
}
break;
}
if (std::string(buffer).compare("init") == 0) {
std::cout << "atm connection ~ : ";
std::cout << "socket# " << sock << " connected" << std::endl;
} else {
std::cout << "atm connection ~ : ";
std::cout << buffer << std::endl;
}
std::string send = parseCommands(buffer, users, sessionKey, sentNumber);
n = write(sock, send.c_str(), send.length());
if (send.compare("not the message I was expecting") == 0) {
close(sock);
break;
}
}
pthread_exit(NULL); // Ends the thread
return NULL;
}
void *consoleThread(void *args) {
struct thread_info *tinfo;
tinfo = (thread_info *) args;
userDB *users = tinfo->users;
// string that is printed to the console
std::string sendStr;
std::cout << ("bank ~ : ");
for(std::string line; getline(std::cin, line);) {
int index = 0;
std::string command = advanceCommand(line, index);
std::string username = advanceCommand(line, index);
if (command.compare("balance") != 0 && command.compare("deposit") != 0) {
sendStr = "Bank Commands: [deposit|balance] [username] <amount>";
}
else if (!users->userExists(username)) {
sendStr = "user \"" + username + "\" does not exist";
}
else if(command.compare("deposit") == 0) {
//deposit [username] [amount] Increase <username>’s balance by <amount>
std::string amount = advanceCommand(line, index);
int testNeg = atoi(amount.c_str());
bool isInt = true;
for (int i = 0; i < amount.length(); i++) {
if (!(amount[i] >= '0' && amount[i] <= '9')) {
isInt = false;
// std::cout << test[i] << " not a int!" << std::endl;
}
}
if (!isInt) {
sendStr = amount + " is not a number!!!";
}
else if (testNeg < 0) {
sendStr = "no negative deposits!!!";
} else {
sendStr = "deposited " + amount;
deposit(username, amount, users);
}
}
else if(command.compare("balance") == 0) {
//balance [username] Print the balance of <username>
sendStr = balance(username, users);
}
std::cout << sendStr << std::endl;
std::cout << ("bank ~ : ");
}
pthread_exit(NULL); // Ends the thread
}
<commit_msg>login fix<commit_after>/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h> // For multithreading
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include "crypto.h"
#define write cwrite
#define read cread
#include "serverCommands.cpp"
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int sock; /* Socket. I think */
userDB *users; /* Pointer to global users object */
//session_type *sessions; // pointer to global sessions object
// CryptoPP::SecByteBlock session_key;
// string username;
};
//HashMap of usernames to a tuple of user info or user object containing {username, pin, balance}
std::string advanceCommand(const std::string& line, int &index);
void advanceSpaces(const std::string &line, int &index);
void error(const char *msg);
void* consoleThread(void *threadid);
void* socketThread(void* arg);
int main(int argc, char *argv[]) {
if (argc != 2) { // Test for correct number of arguments
std::cerr << "Usage: " << argv[0] << " <Server Port>" << std::endl;
exit(1);
}
// socket initialization
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
std::cerr << "Usage: ATMserver <Port>" << std::endl;
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// assign socket to port number
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("ERROR on binding");
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
pthread_t thread;
thread_info args;
userDB* users = new userDB();
init_bank(users);
args.users = users;
pthread_create(&thread, NULL, consoleThread, &args);
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
error("ERROR on accept");
continue;
}
pthread_t thread;
// thread_info args;
args.sock = newsockfd;
// pid = fork();
pthread_create(&thread, NULL, socketThread, &args);
// close(newsockfd);
// int threadNum* ++;
} /* end of while */
close(newsockfd);
close(sockfd);
//create 2 threads, one for I/O another for incomming connections
return 0;
}
//
void error(const char *msg) {
std::cerr << msg <<std::endl;
// exit(1);
}
// Read input until we read a space, then for each character add it to the command string
std::string advanceCommand(const std::string& line, int &index) {
std::string command = "";
if (index >= line.length()) return command;
for(; line[index] != ' ' && line[index] != '\0' && index < line.length(); index++) {
command += line[index];
}
if (index != line.length()) {
advanceSpaces(line, index);
}
return command;
}
// Skip any number of spaces
void advanceSpaces(const std::string &line, int &index) {
for(; line[index] == ' ' && index < line.length(); index++);
}
std::string genSessionKey(std::string username) {
int secret = rand() % 1000 + 1;
std::stringstream ss;
ss << std::setfill('0') << std::setw(4) << secret;
return username + '_' + ss.str();
}
std::string parseCommands(char buffer[], userDB* users, std::string& sessionKey, int& sentNumber) {
int index = 0;
bool loggedIn = false;
std::string input(buffer);
userInfo *thisUser;
std::string sendStr;
int cliNumber = atoi(advanceCommand(input, index).c_str());
sentNumber ++;
if (cliNumber != sentNumber) {
return "not the message I was expecting";
}
sentNumber ++;
if (sessionKey.length() != 0) {
std::string cliSeshKey = advanceCommand(input, index);
int pos = sessionKey.find('_');
std::string someUser = sessionKey.substr(0, pos);
thisUser = users->findUser(someUser);
if (thisUser == NULL) {
return "session Key has been tampered with";
}
else {
loggedIn = thisUser->isLoggedIn();
}
// checks if user is trying to logout
if (cliSeshKey.compare("logout") == 0 && loggedIn) {
sessionKey = "";
// std::cout << "atm connection ~ : " << "user logged out" << std::endl;
thisUser->logout();
return "logged_out";
}
// checks to see if client's session key equals clients session key
if (sessionKey.compare(cliSeshKey) != 0) return "session key has been tampered with";
}
// std::cout << "session key: " << sessionKey << std::endl;
std::string command = advanceCommand(input, index);
// std::cout << "balance: " << (command.compare("balance") == 0) << " " << loggedIn << std::endl;
if (command.compare("login") == 0) {
std::string username = advanceCommand(input, index);
std::string pin = advanceCommand(input, index);
if (users->loginUser(username, pin)) {
// std::cout << username << " logged in!" << std::endl;
sessionKey = genSessionKey(username);
sendStr = "y " + sessionKey;
}
else {
sendStr = "n";
}
}
else if (command.compare("balance") == 0 && loggedIn) {
sendStr = thisUser->getBalance();
}
else if (command.compare("withdraw") == 0 && loggedIn) {
std::string amount = advanceCommand(input, index);
std::string takenOut = thisUser->withdraw(amount);
sendStr = "withdrew";
}
else if (command.compare("transfer") == 0 && loggedIn) {
std::string amount = advanceCommand(input, index);
std::string sendingTo = advanceCommand(input, index);
users->transfer(thisUser->getName(), sendingTo, amount);
sendStr = "transfered";
}
else if (command.compare("check") == 0 && loggedIn) {
std::string name = advanceCommand(input, index);
bool exists = users->userExists(name);
if (exists) sendStr = "y";
else sendStr = "n";
}
else if (command.compare("init") == 0) {
sendStr = "connected to bank";
}
else {
std::cout << "bad command" << std::endl;
sendStr = "error! bad command!";
}
std::stringstream ss;
ss << sentNumber;
return ss.str() + " " + sendStr;
}
void closeSocket(userDB* users, std::string sessionKey, int socket) {
if (sessionKey.length() != 0) {
int pos = sessionKey.find('_');
userInfo *thisUser;
std::string someUser = sessionKey.substr(0, pos);
thisUser = users->findUser(someUser);
thisUser->logout();
}
std::cout << "atm connection ~ : " << "socket# " << socket << " disconnected" << std::endl;
close(socket);
}
void* socketThread(void* args) {
std::cout << std::endl;
struct thread_info *tinfo;
tinfo = (thread_info *) args;
int sock = tinfo->sock;
userDB *users = tinfo->users;
std::string sessionKey;
int sentNumber = 0;
bool logginIn = false;
while (1) {
int n;
char buffer[256];
char sendBuffer[256];
bzero(buffer,256);
bzero(sendBuffer,256);
n = read(sock,buffer,255);
if (n < 0) {
error("ERROR writing to socket");
closeSocket(users, sessionKey, sock);
break;
}
if (n == 0) {
closeSocket(users, sessionKey, sock);
break;
}
if (std::string(buffer).compare("1 init") == 0) {
std::cout << "atm connection ~ : ";
std::cout << "socket# " << sock << " connected" << std::endl;
} else {
#ifdef _debug
std::cout << "atm connection ~ : ";
std::cout << buffer << std::endl;
#endif
}
std::string send = parseCommands(buffer, users, sessionKey, sentNumber);
n = write(sock, send.c_str(), send.length());
if (send.compare("not the message I was expecting") == 0) {
closeSocket(users, sessionKey, sock);
break;
}
}
pthread_exit(NULL); // Ends the thread
return NULL;
}
void *consoleThread(void *args) {
struct thread_info *tinfo;
tinfo = (thread_info *) args;
userDB *users = tinfo->users;
// string that is printed to the console
std::string sendStr;
std::cout << ("bank ~ : ");
for(std::string line; getline(std::cin, line);) {
int index = 0;
std::string command = advanceCommand(line, index);
std::string username = advanceCommand(line, index);
if (command.compare("balance") != 0 && command.compare("deposit") != 0) {
sendStr = "Bank Commands: [deposit|balance] [username] <amount>";
}
else if (!users->userExists(username)) {
sendStr = "user \"" + username + "\" does not exist";
}
else if(command.compare("deposit") == 0) {
//deposit [username] [amount] Increase <username>’s balance by <amount>
std::string amount = advanceCommand(line, index);
int testNeg = atoi(amount.c_str());
bool isInt = true;
for (int i = 0; i < amount.length(); i++) {
if (!(amount[i] >= '0' && amount[i] <= '9')) {
isInt = false;
// std::cout << test[i] << " not a int!" << std::endl;
}
}
if (!isInt) {
sendStr = amount + " is not a number!!!";
}
else if (testNeg < 0) {
sendStr = "no negative deposits!!!";
} else {
sendStr = "deposited " + amount;
deposit(username, amount, users);
}
}
else if(command.compare("balance") == 0) {
//balance [username] Print the balance of <username>
sendStr = balance(username, users);
}
std::cout << sendStr << std::endl;
std::cout << ("bank ~ : ");
}
pthread_exit(NULL); // Ends the thread
}
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
// handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
// velocity
if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity;
else impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
// clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON)
{
float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f);
m_vVelocity -= tangent * tangent_velocity * friction_velocity;
m_vVelocity -= binormal * binormal_velocity * friction_velocity;
}
}
if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1;
if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1;
}
}
}
m_vPosition += Vec3(m_vVelocity * ifps);
} while (time > EPSILON);
// current position
m_pObject->SetWorldTransform(Get_Body_Transform());
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/
/*
*/
void CActorBase::Update_Bounds()
{
float radius = m_pShape->GetRadius();
float hheight = m_pShape->GetHHeight();
m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f));
m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight);
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/*
*/
void CActorBase::SetIntersectionMask(int mask)
{
m_pShape->SetIntersectionMask(mask);
}
int CActorBase::GetIntersectionMask() const
{
return m_pShape->GetIntersectionMask();
}
/*
*/
void CActorBase::SetCollision(int c)
{
m_nCollision = c;
}
int CActorBase::GetCollision() const
{
return m_nCollision;
}
void CActorBase::SetCollisionMask(int mask)
{
m_pShape->SetCollisionMask(mask);
}
int CActorBase::GetCollisionMask() const
{
return m_pShape->GetCollisionMask();
}
/*
*/
void CActorBase::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CActorBase::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн
m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
// handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
// velocity
if (m_pStates[STATE_RUN]) impulse *= m_fMaxVelocity;
else impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
// clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
if (GetCollision())
{
// get collision
vec3 tangent, binormal;
const Vec3 *caps = m_pShape->GetCaps();
for (int i = 0; i < ACTOR_BASE_COLLISIONS; i++)
{
m_pDummy->SetTransform(Get_Body_Transform());
m_pShape->GetCollision(m_vecContacts, 0.0f);
if (m_vecContacts.Size() == 0) break;
float inum_contacts = 1.0f / CMathCore::Itof(m_vecContacts.Size());
for (int j = 0; j < m_vecContacts.Size(); j++)
{
const CShape::Contact &c = m_vecContacts[j];
vec3 normalCollision = c.normal;
if (is_frozen && c.depth < penetration_2)
{
m_vPosition += Vec3(z * (Max(c.depth - penetration, 0.0f) * inum_contacts * Dot(z, normalCollision)));
}
else
{
m_vPosition += Vec3(normalCollision * (Max(c.depth - penetration, 0.0f) * inum_contacts));
is_frozen = 0;
}
float normal_velocity = Dot(normalCollision, m_vVelocity);
if (normal_velocity < 0.0f)
{
m_vVelocity -= normalCollision * normal_velocity;
}
if (friction > EPSILON)
{
OrthoBasis(c.normal, tangent, binormal);
float tangent_velocity = Dot(tangent, m_vVelocity);
float binormal_velocity = Dot(binormal, m_vVelocity);
if (CMathCore::Abs(tangent_velocity) > EPSILON || CMathCore::Abs(binormal_velocity) > EPSILON)
{
float friction_velocity = Clamp(Max(-normal_velocity, 0.0f) * friction * CMathCore::RSqrt(tangent_velocity * tangent_velocity + binormal_velocity * binormal_velocity), -1.0f, 1.0f);
m_vVelocity -= tangent * tangent_velocity * friction_velocity;
m_vVelocity -= binormal * binormal_velocity * friction_velocity;
}
}
if (Dot(c.normal, m_vUp) > 0.5f && Dot(vec3(c.point - caps[0]), m_vUp) < 0.0f) m_nGround = 1;
if (Dot(c.normal, m_vUp) < -0.5f && Dot(vec3(c.point - caps[1]), m_vUp) > 0.0f) m_nCeiling = 1;
}
}
}
m_vPosition += Vec3(m_vVelocity * ifps);
} while (time > EPSILON);
// current position
m_pObject->SetWorldTransform(Get_Body_Transform());
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/
/*
*/
void CActorBase::Update_Bounds()
{
float radius = m_pShape->GetRadius();
float hheight = m_pShape->GetHHeight();
m_BoundBox.Set(vec3(-radius, -radius, 0.0f), vec3(radius, radius, (radius + hheight) * 2.0f));
m_BoundSphere.Set(vec3(0.0f, 0.0f, radius + hheight), radius + hheight);
m_WorldBoundBox.Set(m_BoundBox, Translate(m_vPosition));
m_WorldBoundSphere.Set(m_BoundSphere, Translate(m_vPosition));
}
/*
*/
void CActorBase::SetIntersectionMask(int mask)
{
m_pShape->SetIntersectionMask(mask);
}
int CActorBase::GetIntersectionMask() const
{
return m_pShape->GetIntersectionMask();
}
/*
*/
void CActorBase::SetCollision(int c)
{
m_nCollision = c;
}
int CActorBase::GetCollision() const
{
return m_nCollision;
}
void CActorBase::SetCollisionMask(int mask)
{
m_pShape->SetCollisionMask(mask);
}
int CActorBase::GetCollisionMask() const
{
return m_pShape->GetCollisionMask();
}
/*
*/
void CActorBase::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CActorBase::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}
void CActorBase::SetCollisionHeight(float height)
{
if (!Compare(m_pShape->GetHeight(), height))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
m_pShape->SetHeight(height);
}
Update_Bounds();
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id:
//
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/FORMAT/lineBasedFile.h>
#include <QtGui/QMenu>
#include <QtGui/QMouseEvent>
#include <QtGui/QKeyEvent>
#include <QtCore/QEvent>
#include <QtGui/QTextCursor>
#include <QtGui/QToolBar>
using namespace std;
namespace BALL
{
namespace VIEW
{
MyTextBrowser::MyTextBrowser(QWidget* parent, const char*)
: QTextBrowser(parent),
forward_(false),
backward_(false)
{
// connect(this, SIGNAL(backwardAvailable(bool)), this, SLOT(setBackwardAvailable(bool)));
// connect(this, SIGNAL(forwardAvailable(bool)), this, SLOT(setForwardAvailable(bool)));
}
/*
QMenu* MyTextBrowser::createMenu(const QPoint&)
{
QPopupMenu* cm = new QPopupMenu(this);
cm->insertItem("Home", this, SLOT(home()));
Index back = cm->insertItem("Back", this, SLOT(backward()));
cm->setItemEnabled(back, backward_);
Index forward = cm->insertItem("Forward", this, SLOT(forward()));
cm->setItemEnabled(forward, forward_);
cm->insertSeparator();
Index copy_a = cm->insertItem("Copy", this, SLOT(copy()));
cm->setItemEnabled(copy_a, hasSelectedText());
return cm;
}
void MyTextBrowser::setBackwardAvailable(bool b)
{
backward_ = b;
}
void MyTextBrowser::setForwardAvailable(bool b)
{
forward_ = b;
}
*/
HelpViewer::HelpViewer(QWidget *parent, const char *name)
: DockWidget(parent, name),
project_("BALLView"),
default_page_("index.html"),
browser_( new MyTextBrowser(this)),
whats_this_mode_(false),
ignore_event_(false),
whats_this_(true),
whats_action_(0)
{
Path p;
String dir = p.find( String("..")
+ FileSystem::PATH_SEPARATOR
+ "doc"
+ FileSystem::PATH_SEPARATOR
+ "BALLView"
+ FileSystem::PATH_SEPARATOR );
setBaseDirectory(dir);
hide();
setGuest(*browser_);
registerWidget(this);
browser_->setReadOnly(true);
}
HelpViewer::~HelpViewer()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "Destructing object " << this << " of class HelpViewer" << endl;
#endif
qApp->removeEventFilter(this);
}
void HelpViewer::initializeWidget(MainControl& main_control)
{
DockWidget::initializeWidget(main_control);
insertMenuEntry(MainControl::HELP, project_ + " Documentation", this, SLOT(showHelp()));
setIcon("help.png", true);
registerForHelpSystem(last_action_, "tips.html#help");
if (whats_this_)
{
whats_action_ = insertMenuEntry(MainControl::HELP, "Whats this?", this, SLOT(enterWhatsThisMode()));
registerForHelpSystem(whats_action_, "tips.html#help");
setMenuHint("Show help for clicked widget, exit this mode with right mouse button.");
}
qApp->installEventFilter(this);
}
void HelpViewer::showHelp()
{
showHelp(default_page_);
}
void HelpViewer::showHelp(const String& URL)
{
showHelp(URL, "");
}
void HelpViewer::showHelp(const String& org_url, String entry)
{
String url = org_url;
String fragment;
if (url.has('#'))
{
url = url.before("#");
fragment = org_url.after("#");
}
QUrl qurl = QUrl::fromLocalFile((base_dir_ + url).c_str());
if (fragment != "") qurl.setFragment(fragment.c_str());
browser_->setSource(qurl);
QTextCursor ct = browser_->textCursor();
if (!ct.atStart())
{
ct.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
browser_->setTextCursor(ct);
}
if (entry != "") browser_->find(entry.c_str(), QTextDocument::FindCaseSensitively);
if (!isVisible())
{
show();
setFloating(true);
showMaximized();
}
}
void HelpViewer::onNotify(Message *message)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "HelpViewer" << this << "onNotify " << message << std::endl;
#endif
if (RTTI::isKindOf<RegisterHelpSystemMessage>(*message))
{
RegisterHelpSystemMessage* msg = RTTI::castTo<RegisterHelpSystemMessage>(*message);
if (msg->isRegister())
{
registerForHelpSystem(msg->getObject(), msg->getURL());
}
else
{
unregisterForHelpSystem(msg->getObject());
}
return;
}
if (!RTTI::isKindOf<ShowHelpMessage>(*message)) return;
ShowHelpMessage* msg = RTTI::castTo<ShowHelpMessage>(*message);
bool classname = false;
String project = msg->getProject();
String url = msg->getURL();
if (project.hasSuffix(" class"))
{
classname = true;
project = project.before(" ");
}
if (project != project_) return;
if (classname)
{
showDocumentationFor(url, msg->getEntry());
return;
}
showHelp(url, msg->getEntry());
}
void HelpViewer::showDocumentationFor(const String& classname, const String& member)
{
if (classes_to_files_.size() == 0) collectClasses_();
String classn = classname;
if (!classes_to_files_.has(classn))
{
classn = String("T") + classn;
if (!classes_to_files_.has(classn)) return;
}
showHelp(classes_to_files_[classn], member);
}
void HelpViewer::collectClasses_()
{
classes_to_files_.clear();
Path p;
String dir = p.find( String("..")
+ FileSystem::PATH_SEPARATOR
+ "doc"
+ FileSystem::PATH_SEPARATOR );
try
{
LineBasedFile file(dir + "classes");
vector<String> fields;
while (file.readLine())
{
const String& line = file.getLine();
line.split(fields, " ");
classes_to_files_[fields[0]] = fields[1];
}
}
catch(...)
{
Log.error() << "Could not load the file \"classes\" to parse class list for documentation!"
<< std::endl;
}
}
void HelpViewer::setDefaultPage(const String& url)
{
default_page_ = url;
QUrl qurl = QUrl::fromLocalFile((base_dir_ + url).c_str());
browser_->setSource(qurl);
}
const String& HelpViewer::getDefaultPage() const
{
return default_page_;
}
const String& HelpViewer::getBaseDirectory() const
{
return base_dir_;
}
void HelpViewer::setBaseDirectory(const String& dir)
{
if (dir == "") return;
base_dir_ = dir;
QUrl qurl = QUrl::fromLocalFile((base_dir_ + default_page_).c_str());
browser_->setSource(qurl);
}
void HelpViewer::enterWhatsThisMode()
{
qApp->setOverrideCursor(Qt::WhatsThisCursor);
whats_this_mode_ = true;
}
void HelpViewer::exitWhatsThisMode()
{
if (!whats_this_mode_) return;
whats_this_mode_ = false;
qApp->restoreOverrideCursor();
}
bool HelpViewer::showDocumentationForObject()
{
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
if (widget == 0) return false;
/////////////////////////////////////////////
// show help for widget
/////////////////////////////////////////////
if (showHelpFor(widget))
{
exitWhatsThisMode();
return true;
}
/////////////////////////////////////////////
// show help for menu entry
/////////////////////////////////////////////
// catch block is needed on windows,
// otherwise we get a uncaught exception, no idea why
// maybe the library has a bug under windows
try
{
if (RTTI::isKindOf<QMenu>(*widget))
{
ignore_event_ = true;
// nothing happens if we dont have a docu entry
QAction* id = getMainControl()->getLastHighLightedMenuEntry();
if (docu_entries_.has(id))
{
showHelp(docu_entries_[id]);
exitWhatsThisMode();
return true;
}
}
}
catch(...)
{
}
return false;
}
bool HelpViewer::eventFilter(QObject*, QEvent* e)
{
/////////////////////////////////////////////
// Prevent opening a menu entry when obtaining whats this info for a menu entry
/////////////////////////////////////////////
if (ignore_event_)
{
if (e->type() == QEvent::MouseButtonRelease)
{
ignore_event_ = false;
getMainControl()->menuBar()->hide();
getMainControl()->menuBar()->show();
return true;
}
return false;
}
/////////////////////////////////////////////
// Show Documentation if F1 is pressed
/////////////////////////////////////////////
if (e->type() == QEvent::KeyPress)
{
QKeyEvent* ke = (QKeyEvent*) e;
if (ke->key() != Qt::Key_F1 ||
ke->modifiers() != Qt::NoModifier)
{
return false;
}
if (ke->key() == Qt::Key_Escape)
{
if (whats_this_mode_)
{
exitWhatsThisMode();
return true;
}
}
showDocumentationForObject();
return true;
}
/////////////////////////////////////////////
// now react only in whats this mode and if a mouse button is pressed
/////////////////////////////////////////////
if (!whats_this_mode_ ||
e->type() != QEvent::MouseButtonPress)
{
return false;
}
/////////////////////////////////////////////
// exit whats this mode with right mouse click
/////////////////////////////////////////////
QMouseEvent* me = (QMouseEvent*) e;
if (me->button() != Qt::LeftButton)
{
exitWhatsThisMode();
return true;
}
if (me->button() != Qt::LeftButton) return false;
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
QMenu* menu = 0;
QMenuBar* menu_bar = 0;
if (widget != 0)
{
menu = dynamic_cast<QMenu*>(widget);
menu_bar = dynamic_cast<QMenuBar*>(widget);
}
if (menu_bar != 0) return false;
bool shown_docu = showDocumentationForObject();
if (menu != 0)
{
if (shown_docu)
{
menu->hide();
}
else
{
return false;
}
}
return true;
}
void HelpViewer::registerForHelpSystem(const QObject* object, const String& docu_entry)
{
docu_entries_[object] = docu_entry;
}
void HelpViewer::unregisterForHelpSystem(const QObject* object)
{
docu_entries_.erase(object);
}
bool HelpViewer::showHelpFor(const QObject* object)
{
if (object == 0) return false;
HashMap<const QObject*, String>::Iterator to_find;
QObject* object2 = (QObject*) object;
QWidget* widget = dynamic_cast<QWidget*>(object2);
if (widget && widget->parent() != 0)
{
QToolBar* tb = dynamic_cast<QToolBar*>(widget->parent());
if (tb != 0)
{
QList<QAction *> acs = widget->actions();
if (acs.size() == 1)
{
to_find = docu_entries_.find(*acs.begin());
if (to_find != docu_entries_.end())
{
showHelp((*to_find).second);
return true;
}
}
}
}
while (object2 != 0)
{
to_find = docu_entries_.find(object2);
if (to_find != docu_entries_.end()) break;
object2 = object2->parent();
}
if (object2 == 0)
{
setStatusbarText("No documentation for this widget available!", true);
return false;
}
showHelp((*to_find).second);
return true;
}
bool HelpViewer::hasHelpFor(const QObject* object) const
{
return docu_entries_.has(object);
}
String HelpViewer::getHelpEntryFor(const QObject* widget) const
{
if (!docu_entries_.has(widget)) return false;
return docu_entries_[widget];
}
} // VIEW
} // namespace BALL
<commit_msg>Style fixes to helpViewer.<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id:
//
#include <BALL/VIEW/WIDGETS/helpViewer.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/FORMAT/lineBasedFile.h>
#include <QtGui/QMenu>
#include <QtGui/QMouseEvent>
#include <QtGui/QKeyEvent>
#include <QtCore/QEvent>
#include <QtGui/QTextCursor>
#include <QtGui/QToolBar>
using namespace std;
namespace BALL
{
namespace VIEW
{
MyTextBrowser::MyTextBrowser(QWidget* parent, const char*)
: QTextBrowser(parent),
forward_(false),
backward_(false)
{
// connect(this, SIGNAL(backwardAvailable(bool)), this, SLOT(setBackwardAvailable(bool)));
// connect(this, SIGNAL(forwardAvailable(bool)), this, SLOT(setForwardAvailable(bool)));
}
/*
QMenu* MyTextBrowser::createMenu(const QPoint&)
{
QPopupMenu* cm = new QPopupMenu(this);
cm->insertItem("Home", this, SLOT(home()));
Index back = cm->insertItem("Back", this, SLOT(backward()));
cm->setItemEnabled(back, backward_);
Index forward = cm->insertItem("Forward", this, SLOT(forward()));
cm->setItemEnabled(forward, forward_);
cm->insertSeparator();
Index copy_a = cm->insertItem("Copy", this, SLOT(copy()));
cm->setItemEnabled(copy_a, hasSelectedText());
return cm;
}
void MyTextBrowser::setBackwardAvailable(bool b)
{
backward_ = b;
}
void MyTextBrowser::setForwardAvailable(bool b)
{
forward_ = b;
}
*/
HelpViewer::HelpViewer(QWidget *parent, const char *name)
: DockWidget(parent, name),
project_("BALLView"),
default_page_("index.html"),
browser_( new MyTextBrowser(this)),
whats_this_mode_(false),
ignore_event_(false),
whats_this_(true),
whats_action_(0)
{
Path p;
String dir = p.find( String("..")
+ FileSystem::PATH_SEPARATOR
+ "doc"
+ FileSystem::PATH_SEPARATOR
+ "BALLView"
+ FileSystem::PATH_SEPARATOR );
setBaseDirectory(dir);
hide();
setGuest(*browser_);
registerWidget(this);
browser_->setReadOnly(true);
}
HelpViewer::~HelpViewer()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "Destructing object " << this << " of class HelpViewer" << endl;
#endif
qApp->removeEventFilter(this);
}
void HelpViewer::initializeWidget(MainControl& main_control)
{
DockWidget::initializeWidget(main_control);
insertMenuEntry(MainControl::HELP, project_ + " Documentation", this, SLOT(showHelp()));
setIcon("help.png", true);
registerForHelpSystem(last_action_, "tips.html#help");
if (whats_this_)
{
whats_action_ = insertMenuEntry(MainControl::HELP, "Whats this?", this, SLOT(enterWhatsThisMode()));
registerForHelpSystem(whats_action_, "tips.html#help");
setMenuHint("Show help for clicked widget, exit this mode with right mouse button.");
}
qApp->installEventFilter(this);
}
void HelpViewer::showHelp()
{
showHelp(default_page_);
}
void HelpViewer::showHelp(const String& URL)
{
showHelp(URL, "");
}
void HelpViewer::showHelp(const String& org_url, String entry)
{
String url = org_url;
String fragment;
if (url.has('#'))
{
url = url.before("#");
fragment = org_url.after("#");
}
QUrl qurl = QUrl::fromLocalFile((base_dir_ + url).c_str());
if (fragment != "") qurl.setFragment(fragment.c_str());
browser_->setSource(qurl);
QTextCursor ct = browser_->textCursor();
if (!ct.atStart())
{
ct.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
browser_->setTextCursor(ct);
}
if (entry != "") browser_->find(entry.c_str(), QTextDocument::FindCaseSensitively);
if (!isVisible())
{
show();
setFloating(true);
showMaximized();
}
}
void HelpViewer::onNotify(Message *message)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "HelpViewer" << this << "onNotify " << message << std::endl;
#endif
if (RTTI::isKindOf<RegisterHelpSystemMessage>(*message))
{
RegisterHelpSystemMessage* msg = RTTI::castTo<RegisterHelpSystemMessage>(*message);
if (msg->isRegister())
{
registerForHelpSystem(msg->getObject(), msg->getURL());
}
else
{
unregisterForHelpSystem(msg->getObject());
}
return;
}
if (!RTTI::isKindOf<ShowHelpMessage>(*message)) return;
ShowHelpMessage* msg = RTTI::castTo<ShowHelpMessage>(*message);
bool classname = false;
String project = msg->getProject();
String url = msg->getURL();
if (project.hasSuffix(" class"))
{
classname = true;
project = project.before(" ");
}
if (project != project_) return;
if (classname)
{
showDocumentationFor(url, msg->getEntry());
return;
}
showHelp(url, msg->getEntry());
}
void HelpViewer::showDocumentationFor(const String& classname, const String& member)
{
if (classes_to_files_.size() == 0) collectClasses_();
String classn = classname;
if (!classes_to_files_.has(classn))
{
classn = String("T") + classn;
if (!classes_to_files_.has(classn)) return;
}
showHelp(classes_to_files_[classn], member);
}
void HelpViewer::collectClasses_()
{
classes_to_files_.clear();
Path p;
String filename = p.find( String("..")
+ FileSystem::PATH_SEPARATOR
+ "doc"
+ FileSystem::PATH_SEPARATOR
+ "classes" );
if (filename == "")
{
Log.error() << "Could not load the file \"classes\" to parse class list for the documentation!"
<< std::endl;
return;
}
try
{
LineBasedFile file(filename);
vector<String> fields;
while (file.readLine())
{
const String& line = file.getLine();
line.split(fields, " ");
classes_to_files_[fields[0]] = fields[1];
}
}
catch(...)
{
Log.error() << "Could not parse the file \"classes\" containing the class list for the documentation!"
<< std::endl;
}
}
void HelpViewer::setDefaultPage(const String& url)
{
default_page_ = url;
QUrl qurl = QUrl::fromLocalFile((base_dir_ + url).c_str());
browser_->setSource(qurl);
}
const String& HelpViewer::getDefaultPage() const
{
return default_page_;
}
const String& HelpViewer::getBaseDirectory() const
{
return base_dir_;
}
void HelpViewer::setBaseDirectory(const String& dir)
{
if (dir == "") return;
base_dir_ = dir;
QUrl qurl = QUrl::fromLocalFile((base_dir_ + default_page_).c_str());
browser_->setSource(qurl);
}
void HelpViewer::enterWhatsThisMode()
{
qApp->setOverrideCursor(Qt::WhatsThisCursor);
whats_this_mode_ = true;
}
void HelpViewer::exitWhatsThisMode()
{
if (!whats_this_mode_) return;
whats_this_mode_ = false;
qApp->restoreOverrideCursor();
}
bool HelpViewer::showDocumentationForObject()
{
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
if (widget == 0) return false;
/////////////////////////////////////////////
// show help for widget
/////////////////////////////////////////////
if (showHelpFor(widget))
{
exitWhatsThisMode();
return true;
}
/////////////////////////////////////////////
// show help for menu entry
/////////////////////////////////////////////
// catch block is needed on windows,
// otherwise we get a uncaught exception, no idea why
// maybe the library has a bug under windows
try
{
if (RTTI::isKindOf<QMenu>(*widget))
{
ignore_event_ = true;
// nothing happens if we dont have a docu entry
QAction* id = getMainControl()->getLastHighLightedMenuEntry();
if (docu_entries_.has(id))
{
showHelp(docu_entries_[id]);
exitWhatsThisMode();
return true;
}
}
}
catch(...)
{
}
return false;
}
bool HelpViewer::eventFilter(QObject*, QEvent* e)
{
/////////////////////////////////////////////
// Prevent opening a menu entry when obtaining whats this info for a menu entry
/////////////////////////////////////////////
if (ignore_event_)
{
if (e->type() == QEvent::MouseButtonRelease)
{
ignore_event_ = false;
getMainControl()->menuBar()->hide();
getMainControl()->menuBar()->show();
return true;
}
return false;
}
/////////////////////////////////////////////
// Show Documentation if F1 is pressed
/////////////////////////////////////////////
if (e->type() == QEvent::KeyPress)
{
QKeyEvent* ke = (QKeyEvent*) e;
if (ke->key() != Qt::Key_F1 ||
ke->modifiers() != Qt::NoModifier)
{
return false;
}
if (ke->key() == Qt::Key_Escape)
{
if (whats_this_mode_)
{
exitWhatsThisMode();
return true;
}
}
showDocumentationForObject();
return true;
}
/////////////////////////////////////////////
// now react only in whats this mode and if a mouse button is pressed
/////////////////////////////////////////////
if (!whats_this_mode_ ||
e->type() != QEvent::MouseButtonPress)
{
return false;
}
/////////////////////////////////////////////
// exit whats this mode with right mouse click
/////////////////////////////////////////////
QMouseEvent* me = (QMouseEvent*) e;
if (me->button() != Qt::LeftButton)
{
exitWhatsThisMode();
return true;
}
if (me->button() != Qt::LeftButton) return false;
QPoint point = QCursor::pos();
QWidget* widget = qApp->widgetAt(point);
QMenu* menu = 0;
QMenuBar* menu_bar = 0;
if (widget != 0)
{
menu = dynamic_cast<QMenu*>(widget);
menu_bar = dynamic_cast<QMenuBar*>(widget);
}
if (menu_bar != 0) return false;
bool shown_docu = showDocumentationForObject();
if (menu != 0)
{
if (shown_docu)
{
menu->hide();
}
else
{
return false;
}
}
return true;
}
void HelpViewer::registerForHelpSystem(const QObject* object, const String& docu_entry)
{
docu_entries_[object] = docu_entry;
}
void HelpViewer::unregisterForHelpSystem(const QObject* object)
{
docu_entries_.erase(object);
}
bool HelpViewer::showHelpFor(const QObject* object)
{
if (object == 0) return false;
HashMap<const QObject*, String>::Iterator to_find;
QObject* object2 = (QObject*) object;
QWidget* widget = dynamic_cast<QWidget*>(object2);
if (widget && widget->parent() != 0)
{
QToolBar* tb = dynamic_cast<QToolBar*>(widget->parent());
if (tb != 0)
{
QList<QAction *> acs = widget->actions();
if (acs.size() == 1)
{
to_find = docu_entries_.find(*acs.begin());
if (to_find != docu_entries_.end())
{
showHelp((*to_find).second);
return true;
}
}
}
}
while (object2 != 0)
{
to_find = docu_entries_.find(object2);
if (to_find != docu_entries_.end()) break;
object2 = object2->parent();
}
if (object2 == 0)
{
setStatusbarText("No documentation for this widget available!", true);
return false;
}
showHelp((*to_find).second);
return true;
}
bool HelpViewer::hasHelpFor(const QObject* object) const
{
return docu_entries_.has(object);
}
String HelpViewer::getHelpEntryFor(const QObject* widget) const
{
if (!docu_entries_.has(widget)) return false;
return docu_entries_[widget];
}
} // VIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/HCoordinate.java rev. 1.17 (JTS-1.7)
*
**********************************************************************/
#include <geos/algorithm/HCoordinate.h>
#include <geos/algorithm/NotRepresentableException.h>
#include <geos/geom/Coordinate.h>
#include <geos/platform.h>
#include <memory>
#include <cmath> // for finite()
#include <iostream>
#include <iomanip>
// For MingW builds with __STRICT_ANSI__ (-ansi)
// See: http://geos.refractions.net/pipermail/geos-devel/2006-June/002342.html
#if defined(__MINGW32__)
extern "C" {
int __cdecl _finite (double);
#define finite(x) _finite(x)
}
#endif
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
// Define to make -ffloat-store be effective for this class
//#define STORE_INTERMEDIATE_COMPUTATION_VALUES 1
using namespace std;
using namespace geos::geom;
namespace geos {
namespace algorithm { // geos.algorithm
/*public static*/
void
HCoordinate::intersection(const Coordinate &p1, const Coordinate &p2,
const Coordinate &q1, const Coordinate &q2, Coordinate &ret)
{
#if GEOS_DEBUG
cerr << __FUNCTION__ << ":" << endl
<< setprecision(20)
<< " p1: " << p1 << endl
<< " p2: " << p2 << endl
<< " q1: " << q1 << endl
<< " q2: " << q2 << endl;
#endif
HCoordinate hc1p1(p1);
#if GEOS_DEBUG
cerr << "HCoordinate(p1): "
<< hc1p1 << endl;
#endif
HCoordinate hc1p2(p2);
#if GEOS_DEBUG
cerr << "HCoordinate(p2): "
<< hc1p2 << endl;
#endif
HCoordinate l1(hc1p1, hc1p2);
#if GEOS_DEBUG
cerr << "L1 - HCoordinate(HCp1, HCp2): "
<< l1 << endl;
#endif
HCoordinate hc2q1(q1);
#if GEOS_DEBUG
cerr << "HCoordinate(q1): "
<< hc2q1 << endl;
#endif
HCoordinate hc2q2(q2);
#if GEOS_DEBUG
cerr << "HCoordinate(q2): "
<< hc2q2 << endl;
#endif
HCoordinate l2(hc2q1, hc2q2);
#if GEOS_DEBUG
cerr << "L2 - HCoordinate(HCq1, HCq2): "
<< l2 << endl;
#endif
HCoordinate intHCoord(l1, l2);
#if GEOS_DEBUG
cerr << "HCoordinate(L1, L2): "
<< intHCoord << endl;
#endif
intHCoord.getCoordinate(ret);
}
/*public*/
HCoordinate::HCoordinate()
:
x(0.0),
y(0.0),
w(1.0)
{
}
/*public*/
HCoordinate::HCoordinate(long double _x, long double _y, long double _w)
:
x(_x),
y(_y),
w(_w)
{
}
/*public*/
HCoordinate::HCoordinate(const Coordinate& p)
:
x(p.x),
y(p.y),
w(1.0)
{
}
/*public*/
#ifndef STORE_INTERMEDIATE_COMPUTATION_VALUES
HCoordinate::HCoordinate(const HCoordinate &p1, const HCoordinate &p2)
:
x( p1.y*p2.w - p2.y*p1.w ),
y( p2.x*p1.w - p1.x*p2.w ),
w( p1.x*p2.y - p2.x*p1.y )
{
}
#else // def STORE_INTERMEDIATE_COMPUTATION_VALUES
HCoordinate::HCoordinate(const HCoordinate &p1, const HCoordinate &p2)
{
long double xf1 = p1.y*p2.w;
long double xf2 = p2.y*p1.w;
x = xf1 - xf2;
long double yf1 = p2.x*p1.w;
long double yf2 = p1.x*p2.w;
y = yf1 - yf2;
long double wf1 = p1.x*p2.y;
long double wf2 = p2.x*p1.y;
w = wf1 - wf2;
#if GEOS_DEBUG
cerr
<< " xf1: " << xf1 << endl
<< " xf2: " << xf2 << endl
<< " yf1: " << yf1 << endl
<< " yf2: " << yf2 << endl
<< " wf1: " << wf1 << endl
<< " wf2: " << wf2 << endl
<< " x: " << x << endl
<< " y: " << y << endl
<< " w: " << w << endl;
#endif // def GEOS_DEBUG
}
#endif // def STORE_INTERMEDIATE_COMPUTATION_VALUES
/*public*/
long double
HCoordinate::getX() const
{
long double a = x/w;
// finite() also checks for NaN
if ( ! finite(static_cast<double>(a)) )
{
throw NotRepresentableException();
}
return a;
}
/*public*/
long double
HCoordinate::getY() const
{
long double a = y/w;
// finite() also checks for NaN
if ( ! finite(static_cast<double>(a)) )
{
throw NotRepresentableException();
}
return a;
}
/*public*/
void
HCoordinate::getCoordinate(Coordinate &ret) const
{
ret = Coordinate(static_cast<double>(getX()), static_cast<double>(getY()));
}
std::ostream& operator<< (std::ostream& o, const HCoordinate& c)
{
return o << "(" << c.x << ", "
<< c.y << ") [w: " << c.w << "]";
}
} // namespace geos.algorithm
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.24 2006/06/27 15:59:36 strk
* * source/algorithm/HCoordinate.cpp: added support for MingW -ansi builds.
*
* Revision 1.23 2006/04/20 14:27:40 strk
* HCoordinate class changed to use long double types internally, in order to improve computation precision
*
* Revision 1.22 2006/04/20 11:11:57 strk
* source/algorithm/HCoordinate.cpp: added compile time define to force storage of intermediate computation values to variables (in order to make the -ffloat-store gcc switch effective). Disabled by default.
*
* Revision 1.21 2006/04/14 09:02:16 strk
* Hadded output operator and debugging prints for HCoordinate.
*
* Revision 1.20 2006/04/04 11:37:00 strk
* Port information + initialization lists in ctors
*
* Revision 1.19 2006/04/04 11:28:12 strk
* NotRepresentable condition detected using finite() from <cmath>
* rather then using FINITE() macro. Made ::intersection() body
* more readable.
*
* Revision 1.18 2006/03/21 11:12:23 strk
* Cleanups: headers inclusion and Log section
*
* Revision 1.17 2006/03/09 16:46:45 strk
* geos::geom namespace definition, first pass at headers split
**********************************************************************/
<commit_msg>Replaced finite function with std::numeric_limits (Ticket #162).<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/HCoordinate.java rev. 1.17 (JTS-1.7)
*
**********************************************************************/
#include <geos/algorithm/HCoordinate.h>
#include <geos/algorithm/NotRepresentableException.h>
#include <geos/geom/Coordinate.h>
#include <geos/platform.h>
#include <memory>
#include <cmath>
#include <limits>
#include <iostream>
#include <iomanip>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
// Define to make -ffloat-store be effective for this class
//#define STORE_INTERMEDIATE_COMPUTATION_VALUES 1
using namespace std;
using namespace geos::geom;
namespace geos {
namespace algorithm { // geos.algorithm
/*public static*/
void
HCoordinate::intersection(const Coordinate &p1, const Coordinate &p2,
const Coordinate &q1, const Coordinate &q2, Coordinate &ret)
{
#if GEOS_DEBUG
cerr << __FUNCTION__ << ":" << endl
<< setprecision(20)
<< " p1: " << p1 << endl
<< " p2: " << p2 << endl
<< " q1: " << q1 << endl
<< " q2: " << q2 << endl;
#endif
HCoordinate hc1p1(p1);
#if GEOS_DEBUG
cerr << "HCoordinate(p1): "
<< hc1p1 << endl;
#endif
HCoordinate hc1p2(p2);
#if GEOS_DEBUG
cerr << "HCoordinate(p2): "
<< hc1p2 << endl;
#endif
HCoordinate l1(hc1p1, hc1p2);
#if GEOS_DEBUG
cerr << "L1 - HCoordinate(HCp1, HCp2): "
<< l1 << endl;
#endif
HCoordinate hc2q1(q1);
#if GEOS_DEBUG
cerr << "HCoordinate(q1): "
<< hc2q1 << endl;
#endif
HCoordinate hc2q2(q2);
#if GEOS_DEBUG
cerr << "HCoordinate(q2): "
<< hc2q2 << endl;
#endif
HCoordinate l2(hc2q1, hc2q2);
#if GEOS_DEBUG
cerr << "L2 - HCoordinate(HCq1, HCq2): "
<< l2 << endl;
#endif
HCoordinate intHCoord(l1, l2);
#if GEOS_DEBUG
cerr << "HCoordinate(L1, L2): "
<< intHCoord << endl;
#endif
intHCoord.getCoordinate(ret);
}
/*public*/
HCoordinate::HCoordinate()
:
x(0.0),
y(0.0),
w(1.0)
{
}
/*public*/
HCoordinate::HCoordinate(long double _x, long double _y, long double _w)
:
x(_x),
y(_y),
w(_w)
{
}
/*public*/
HCoordinate::HCoordinate(const Coordinate& p)
:
x(p.x),
y(p.y),
w(1.0)
{
}
/*public*/
#ifndef STORE_INTERMEDIATE_COMPUTATION_VALUES
HCoordinate::HCoordinate(const HCoordinate &p1, const HCoordinate &p2)
:
x( p1.y*p2.w - p2.y*p1.w ),
y( p2.x*p1.w - p1.x*p2.w ),
w( p1.x*p2.y - p2.x*p1.y )
{
}
#else // def STORE_INTERMEDIATE_COMPUTATION_VALUES
HCoordinate::HCoordinate(const HCoordinate &p1, const HCoordinate &p2)
{
long double xf1 = p1.y*p2.w;
long double xf2 = p2.y*p1.w;
x = xf1 - xf2;
long double yf1 = p2.x*p1.w;
long double yf2 = p1.x*p2.w;
y = yf1 - yf2;
long double wf1 = p1.x*p2.y;
long double wf2 = p2.x*p1.y;
w = wf1 - wf2;
#if GEOS_DEBUG
cerr
<< " xf1: " << xf1 << endl
<< " xf2: " << xf2 << endl
<< " yf1: " << yf1 << endl
<< " yf2: " << yf2 << endl
<< " wf1: " << wf1 << endl
<< " wf2: " << wf2 << endl
<< " x: " << x << endl
<< " y: " << y << endl
<< " w: " << w << endl;
#endif // def GEOS_DEBUG
}
#endif // def STORE_INTERMEDIATE_COMPUTATION_VALUES
/*public*/
long double
HCoordinate::getX() const
{
long double a = x/w;
if (std::fabs(a) > std::numeric_limits<double>::max())
{
throw NotRepresentableException();
}
return a;
}
/*public*/
long double
HCoordinate::getY() const
{
long double a = y/w;
if (std::fabs(a) > std::numeric_limits<double>::max())
{
throw NotRepresentableException();
}
return a;
}
/*public*/
void
HCoordinate::getCoordinate(Coordinate &ret) const
{
ret = Coordinate(static_cast<double>(getX()), static_cast<double>(getY()));
}
std::ostream& operator<< (std::ostream& o, const HCoordinate& c)
{
return o << "(" << c.x << ", "
<< c.y << ") [w: " << c.w << "]";
}
} // namespace geos.algorithm
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.24 2006/06/27 15:59:36 strk
* * source/algorithm/HCoordinate.cpp: added support for MingW -ansi builds.
*
* Revision 1.23 2006/04/20 14:27:40 strk
* HCoordinate class changed to use long double types internally, in order to improve computation precision
*
* Revision 1.22 2006/04/20 11:11:57 strk
* source/algorithm/HCoordinate.cpp: added compile time define to force storage of intermediate computation values to variables (in order to make the -ffloat-store gcc switch effective). Disabled by default.
*
* Revision 1.21 2006/04/14 09:02:16 strk
* Hadded output operator and debugging prints for HCoordinate.
*
* Revision 1.20 2006/04/04 11:37:00 strk
* Port information + initialization lists in ctors
*
* Revision 1.19 2006/04/04 11:28:12 strk
* NotRepresentable condition detected using finite() from <cmath>
* rather then using FINITE() macro. Made ::intersection() body
* more readable.
*
* Revision 1.18 2006/03/21 11:12:23 strk
* Cleanups: headers inclusion and Log section
*
* Revision 1.17 2006/03/09 16:46:45 strk
* geos::geom namespace definition, first pass at headers split
**********************************************************************/
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2009 SlimDX Group
*
* 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 <windows.h>
#include <vcclr.h>
#include "../InternalHelpers.h"
#include "../Utilities.h"
#include "../DataStream.h"
#include "WaveStream.h"
using namespace System;
using namespace System::IO;
namespace SlimDX
{
namespace Multimedia
{
WaveStream::WaveStream( String^ path )
{
if( String::IsNullOrEmpty( path ) )
throw gcnew ArgumentNullException( "path" );
if( !File::Exists( path ) )
throw gcnew FileNotFoundException( "Could not find wave file", path );
pin_ptr<const wchar_t> pinnedPath = PtrToStringChars( path );
handle = mmioOpen( const_cast<LPWSTR>( reinterpret_cast<LPCWSTR>( pinnedPath ) ), NULL, MMIO_ALLOCBUF | MMIO_READ );
if( handle == NULL )
throw gcnew FileLoadException( "Could not open the file", path );
Init();
}
WaveStream::WaveStream( Stream^ stream )
{
InitStream( stream, 0 );
}
WaveStream::WaveStream( Stream^ stream, int length )
{
InitStream( stream, length );
}
void WaveStream::InitStream( Stream^ stream, int length )
{
if( stream == nullptr )
throw gcnew ArgumentNullException( "stream" );
DataStream^ ds = nullptr;
array<Byte>^ bytes = Utilities::ReadStream( stream, length, &ds );
if( bytes == nullptr )
{
Int64 size = ds->RemainingLength;
internalMemory = gcnew DataStream( size, true, false );
internalMemory->WriteRange( IntPtr( ds->SeekToEnd() ), size );
}
else
{
internalMemory = gcnew DataStream( bytes->LongLength, true, false );
internalMemory->Write( bytes, 0, bytes->Length );
}
MMIOINFO info;
ZeroMemory( &info, sizeof( info ) );
info.fccIOProc = FOURCC_MEM;
info.cchBuffer = bytes->Length;
info.pchBuffer = internalMemory->RawPointer;
handle = mmioOpen( NULL, &info, MMIO_ALLOCBUF | MMIO_READ );
if( handle == NULL )
throw gcnew InvalidDataException( "Invalid wave file." );
Init();
}
void WaveStream::Init()
{
MMCKINFO fileInfo;
MMCKINFO chunk;
PCMWAVEFORMAT pcmFormat;
if( mmioDescend( handle, &fileInfo, NULL, 0 ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
if( fileInfo.ckid != FOURCC_RIFF ||
fileInfo.fccType != mmioFOURCC( 'W', 'A', 'V', 'E' ) )
throw gcnew InvalidDataException( "Invalid wave file." );
chunk.ckid = mmioFOURCC( 'f', 'm', 't', ' ' );
if( mmioDescend( handle, &chunk, &fileInfo, MMIO_FINDCHUNK ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
if( chunk.cksize < static_cast<LONG>( sizeof( PCMWAVEFORMAT ) ) )
throw gcnew InvalidDataException( "Invalid wave file." );
if( mmioRead( handle, reinterpret_cast<HPSTR>( &pcmFormat ), sizeof( pcmFormat ) ) != sizeof( pcmFormat ) )
throw gcnew InvalidDataException( "Invalid wave file." );
if( pcmFormat.wf.wFormatTag == WAVE_FORMAT_PCM )
{
auto_array<WAVEFORMATEX> tempFormat( reinterpret_cast<WAVEFORMATEX*>( new BYTE[sizeof( WAVEFORMATEX )] ) );
memcpy( tempFormat.get(), &pcmFormat, sizeof( pcmFormat ) );
tempFormat->cbSize = 0;
format = WaveFormat::FromUnmanaged( *tempFormat.get() );
}
else
{
WORD extraBytes = 0;
if( mmioRead( handle, reinterpret_cast<CHAR*>( &extraBytes ), sizeof( WORD ) ) != sizeof( WORD ) )
throw gcnew InvalidDataException( "Invalid wave file." );
auto_array<WAVEFORMATEX> tempFormat( reinterpret_cast<WAVEFORMATEX*>( new BYTE[sizeof( WAVEFORMATEX ) + extraBytes] ) );
memcpy( tempFormat.get(), &pcmFormat, sizeof( pcmFormat ) );
tempFormat->cbSize = extraBytes;
if( mmioRead( handle, reinterpret_cast<CHAR*>( reinterpret_cast<BYTE*>( &tempFormat->cbSize ) + sizeof( WORD ) ), extraBytes ) != extraBytes )
throw gcnew InvalidDataException( "Invalid wave file." );
format = WaveFormatExtensible::FromBase( tempFormat.get() );
}
if( mmioAscend( handle, &chunk, 0 ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
chunk.ckid = mmioFOURCC( 'd', 'a', 't', 'a' );
if( mmioDescend( handle, &chunk, &fileInfo, MMIO_FINDCHUNK ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
dataOffset = mmioSeek( handle, 0, SEEK_CUR );
size = chunk.cksize;
if( dataOffset < 0 || size <= 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
}
WaveStream::~WaveStream()
{
Destruct();
GC::SuppressFinalize( this );
}
WaveStream::!WaveStream()
{
Destruct();
}
void WaveStream::Destruct()
{
if( handle != NULL )
{
mmioClose( handle, 0 );
handle = NULL;
}
if( internalMemory != nullptr )
{
delete internalMemory;
internalMemory = nullptr;
}
}
Int64 WaveStream::Seek( Int64 offset, SeekOrigin origin )
{
int targetPosition = static_cast<int>( offset );
int targetOrigin = SEEK_CUR;
if( origin == SeekOrigin::Begin )
{
targetOrigin = SEEK_SET;
targetPosition += dataOffset;
}
else if( origin == SeekOrigin::End )
{
targetOrigin = SEEK_END;
targetPosition = dataOffset;
}
int result = mmioSeek( handle, targetPosition, targetOrigin );
if( result < 0 )
throw gcnew InvalidOperationException("Cannot seek beyond the end of the stream.");
return result - dataOffset;
}
void WaveStream::Write( array<Byte>^ buffer, int offset, int count )
{
SLIMDX_UNREFERENCED_PARAMETER(buffer);
SLIMDX_UNREFERENCED_PARAMETER(offset);
SLIMDX_UNREFERENCED_PARAMETER(count);
throw gcnew NotSupportedException("WaveStream objects cannot be written to.");
}
int WaveStream::Read( array<Byte>^ buffer, int offset, int count )
{
Utilities::CheckArrayBounds( buffer, offset, count );
// truncate the count to the end of the stream
size_t actualCount = min( static_cast<size_t>( Length - Position ), static_cast<size_t>( count ) );
pin_ptr<Byte> pinnedBuffer = &buffer[0];
int read = mmioRead( handle, reinterpret_cast<HPSTR>( pinnedBuffer ), static_cast<LONG>( actualCount ) );
return read;
}
void WaveStream::Flush()
{
throw gcnew NotSupportedException("WaveStream objects cannot be flushed.");
}
void WaveStream::SetLength( Int64 value )
{
SLIMDX_UNREFERENCED_PARAMETER(value);
throw gcnew NotSupportedException("WaveStream objects cannot be resized.");
}
Int64 WaveStream::Position::get()
{
return mmioSeek( handle, 0, SEEK_CUR ) - dataOffset;
}
void WaveStream::Position::set( System::Int64 value )
{
Seek( value, System::IO::SeekOrigin::Begin );
}
Int64 WaveStream::Length::get()
{
return size;
}
}
}<commit_msg>Fixed issue 429: WaveStream(Stream) was broken.<commit_after>/*
* Copyright (c) 2007-2009 SlimDX Group
*
* 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 <windows.h>
#include <vcclr.h>
#include "../InternalHelpers.h"
#include "../Utilities.h"
#include "../DataStream.h"
#include "WaveStream.h"
using namespace System;
using namespace System::IO;
namespace SlimDX
{
namespace Multimedia
{
WaveStream::WaveStream( String^ path )
{
if( String::IsNullOrEmpty( path ) )
throw gcnew ArgumentNullException( "path" );
if( !File::Exists( path ) )
throw gcnew FileNotFoundException( "Could not find wave file", path );
pin_ptr<const wchar_t> pinnedPath = PtrToStringChars( path );
handle = mmioOpen( const_cast<LPWSTR>( reinterpret_cast<LPCWSTR>( pinnedPath ) ), NULL, MMIO_ALLOCBUF | MMIO_READ );
if( handle == NULL )
throw gcnew FileLoadException( "Could not open the file", path );
Init();
}
WaveStream::WaveStream( Stream^ stream )
{
InitStream( stream, 0 );
}
WaveStream::WaveStream( Stream^ stream, int length )
{
InitStream( stream, length );
}
void WaveStream::InitStream( Stream^ stream, int length )
{
if( stream == nullptr )
throw gcnew ArgumentNullException( "stream" );
DataStream^ ds = nullptr;
array<Byte>^ bytes = Utilities::ReadStream( stream, length, &ds );
if( bytes == nullptr )
{
Int64 size = ds->RemainingLength;
internalMemory = gcnew DataStream( size, true, true );
internalMemory->WriteRange( IntPtr( ds->SeekToEnd() ), size );
}
else
{
internalMemory = gcnew DataStream( bytes->LongLength, true, true );
internalMemory->Write( bytes, 0, bytes->Length );
}
MMIOINFO info;
ZeroMemory( &info, sizeof( info ) );
info.fccIOProc = FOURCC_MEM;
info.cchBuffer = bytes->Length;
info.pchBuffer = internalMemory->RawPointer;
handle = mmioOpen( NULL, &info, MMIO_ALLOCBUF | MMIO_READ );
if( handle == NULL )
throw gcnew InvalidDataException( "Invalid wave file." );
Init();
}
void WaveStream::Init()
{
MMCKINFO fileInfo;
MMCKINFO chunk;
PCMWAVEFORMAT pcmFormat;
if( mmioDescend( handle, &fileInfo, NULL, 0 ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
if( fileInfo.ckid != FOURCC_RIFF ||
fileInfo.fccType != mmioFOURCC( 'W', 'A', 'V', 'E' ) )
throw gcnew InvalidDataException( "Invalid wave file." );
chunk.ckid = mmioFOURCC( 'f', 'm', 't', ' ' );
if( mmioDescend( handle, &chunk, &fileInfo, MMIO_FINDCHUNK ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
if( chunk.cksize < static_cast<LONG>( sizeof( PCMWAVEFORMAT ) ) )
throw gcnew InvalidDataException( "Invalid wave file." );
if( mmioRead( handle, reinterpret_cast<HPSTR>( &pcmFormat ), sizeof( pcmFormat ) ) != sizeof( pcmFormat ) )
throw gcnew InvalidDataException( "Invalid wave file." );
if( pcmFormat.wf.wFormatTag == WAVE_FORMAT_PCM )
{
auto_array<WAVEFORMATEX> tempFormat( reinterpret_cast<WAVEFORMATEX*>( new BYTE[sizeof( WAVEFORMATEX )] ) );
memcpy( tempFormat.get(), &pcmFormat, sizeof( pcmFormat ) );
tempFormat->cbSize = 0;
format = WaveFormat::FromUnmanaged( *tempFormat.get() );
}
else
{
WORD extraBytes = 0;
if( mmioRead( handle, reinterpret_cast<CHAR*>( &extraBytes ), sizeof( WORD ) ) != sizeof( WORD ) )
throw gcnew InvalidDataException( "Invalid wave file." );
auto_array<WAVEFORMATEX> tempFormat( reinterpret_cast<WAVEFORMATEX*>( new BYTE[sizeof( WAVEFORMATEX ) + extraBytes] ) );
memcpy( tempFormat.get(), &pcmFormat, sizeof( pcmFormat ) );
tempFormat->cbSize = extraBytes;
if( mmioRead( handle, reinterpret_cast<CHAR*>( reinterpret_cast<BYTE*>( &tempFormat->cbSize ) + sizeof( WORD ) ), extraBytes ) != extraBytes )
throw gcnew InvalidDataException( "Invalid wave file." );
format = WaveFormatExtensible::FromBase( tempFormat.get() );
}
if( mmioAscend( handle, &chunk, 0 ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
chunk.ckid = mmioFOURCC( 'd', 'a', 't', 'a' );
if( mmioDescend( handle, &chunk, &fileInfo, MMIO_FINDCHUNK ) != 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
dataOffset = mmioSeek( handle, 0, SEEK_CUR );
size = chunk.cksize;
if( dataOffset < 0 || size <= 0 )
throw gcnew InvalidDataException( "Invalid wave file." );
}
WaveStream::~WaveStream()
{
Destruct();
GC::SuppressFinalize( this );
}
WaveStream::!WaveStream()
{
Destruct();
}
void WaveStream::Destruct()
{
if( handle != NULL )
{
mmioClose( handle, 0 );
handle = NULL;
}
if( internalMemory != nullptr )
{
delete internalMemory;
internalMemory = nullptr;
}
}
Int64 WaveStream::Seek( Int64 offset, SeekOrigin origin )
{
int targetPosition = static_cast<int>( offset );
int targetOrigin = SEEK_CUR;
if( origin == SeekOrigin::Begin )
{
targetOrigin = SEEK_SET;
targetPosition += dataOffset;
}
else if( origin == SeekOrigin::End )
{
targetOrigin = SEEK_END;
targetPosition = dataOffset;
}
int result = mmioSeek( handle, targetPosition, targetOrigin );
if( result < 0 )
throw gcnew InvalidOperationException("Cannot seek beyond the end of the stream.");
return result - dataOffset;
}
void WaveStream::Write( array<Byte>^ buffer, int offset, int count )
{
SLIMDX_UNREFERENCED_PARAMETER(buffer);
SLIMDX_UNREFERENCED_PARAMETER(offset);
SLIMDX_UNREFERENCED_PARAMETER(count);
throw gcnew NotSupportedException("WaveStream objects cannot be written to.");
}
int WaveStream::Read( array<Byte>^ buffer, int offset, int count )
{
Utilities::CheckArrayBounds( buffer, offset, count );
// truncate the count to the end of the stream
size_t actualCount = min( static_cast<size_t>( Length - Position ), static_cast<size_t>( count ) );
pin_ptr<Byte> pinnedBuffer = &buffer[0];
int read = mmioRead( handle, reinterpret_cast<HPSTR>( pinnedBuffer ), static_cast<LONG>( actualCount ) );
return read;
}
void WaveStream::Flush()
{
throw gcnew NotSupportedException("WaveStream objects cannot be flushed.");
}
void WaveStream::SetLength( Int64 value )
{
SLIMDX_UNREFERENCED_PARAMETER(value);
throw gcnew NotSupportedException("WaveStream objects cannot be resized.");
}
Int64 WaveStream::Position::get()
{
return mmioSeek( handle, 0, SEEK_CUR ) - dataOffset;
}
void WaveStream::Position::set( System::Int64 value )
{
Seek( value, System::IO::SeekOrigin::Begin );
}
Int64 WaveStream::Length::get()
{
return size;
}
}
}<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2016 ScyllaDB
*/
#include "prometheus.hh"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include "proto/metrics2.pb.h"
#include "scollectd_api.hh"
#include "scollectd-impl.hh"
#include "http/function_handlers.hh"
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/algorithm/string.hpp>
namespace prometheus {
namespace pm = io::prometheus::client;
/**
* Taken from an answer in stackoverflow:
* http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja
*/
static bool write_delimited_to(const google::protobuf::MessageLite& message,
google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
google::protobuf::io::CodedOutputStream output(rawOutput);
const int size = message.ByteSize();
output.WriteVarint32(size);
uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
if (buffer != nullptr) {
message.SerializeWithCachedSizesToArray(buffer);
} else {
message.SerializeWithCachedSizes(&output);
if (output.HadError()) {
return false;
}
}
return true;
}
static std::string safe_name(const sstring& name) {
auto rep = boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_");
boost::remove_erase_if(rep, boost::is_any_of("+()"));
return rep;
}
static sstring collectd_name(const scollectd::type_instance_id & id, uint32_t cpu) {
return safe_name(id.plugin());
}
static pm::Metric* add_label(pm::Metric* mt, const scollectd::type_instance_id & id, uint32_t cpu) {
auto label = mt->add_label();
label->set_name("shard");
label->set_value(std::to_string(cpu));
label = mt->add_label();
label->set_name("type");
label->set_value(id.type());
if (id.type_instance() != "") {
label = mt->add_label();
label->set_name("metric");
label->set_value(id.type_instance());
}
const sstring& host = scollectd::get_impl().host();
if (host != "") {
label = mt->add_label();
label->set_name("instance");
label->set_value(host);
}
return mt;
}
static void fill_metric(pm::MetricFamily& mf, const std::vector<scollectd::collectd_value>& vals,
const scollectd::type_instance_id & id, uint32_t cpu) {
for (const scollectd::collectd_value& c : vals) {
switch (c.type()) {
case scollectd::data_type::DERIVE:
add_label(mf.add_metric(), id, cpu)->mutable_counter()->set_value(c.i());
mf.set_type(pm::MetricType::COUNTER);
break;
case scollectd::data_type::GAUGE:
add_label(mf.add_metric(), id, cpu)->mutable_gauge()->set_value(c.d());
mf.set_type(pm::MetricType::GAUGE);
break;
default:
add_label(mf.add_metric(), id, cpu)->mutable_counter()->set_value(c.ui());
mf.set_type(pm::MetricType::COUNTER);
break;
}
}
}
future<> start(httpd::http_server_control& http_server, const config& ctx) {
return http_server.set_routes([&ctx](httpd::routes& r) {
httpd::future_handler_function f = [&ctx](std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
return do_with(std::vector<scollectd::value_map>(), [rep = std::move(rep), &ctx] (auto& vec) mutable {
vec.resize(smp::count);
return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) {
return smp::submit_to(cpu, [] {
return scollectd::get_value_map();
}).then([&vec, cpu] (auto res) {
vec[cpu] = res;
});
}).then([rep = std::move(rep), &vec, &ctx]() mutable {
uint32_t cpu = 0;
for (auto value: vec) {
for (auto i : value) {
pm::MetricFamily mtf;
std::string s;
google::protobuf::io::StringOutputStream os(&s);
mtf.set_name(ctx.prefix + "_" + collectd_name(i.first, cpu));
mtf.set_help(ctx.metric_help);
fill_metric(mtf, i.second, i.first, cpu);
if (mtf.metric_size() > 0) {
std::stringstream ss;
if (!write_delimited_to(mtf, &os)) {
seastar_logger.warn("Failed to write protobuf metrics");
}
rep->_content += s;
}
}
cpu++;
}
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
});
});
};
r.put(GET, "/metrics", new httpd::function_handler(f, "proto"));
});
}
}
<commit_msg>prometheus: use the metrics layer instead of the scollectd<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2016 ScyllaDB
*/
#include "prometheus.hh"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include "proto/metrics2.pb.h"
#include "scollectd_api.hh"
#include "scollectd-impl.hh"
#include "metrics_api.hh"
#include "http/function_handlers.hh"
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/algorithm/string.hpp>
using namespace seastar;
namespace prometheus {
namespace pm = io::prometheus::client;
/**
* Taken from an answer in stackoverflow:
* http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja
*/
static bool write_delimited_to(const google::protobuf::MessageLite& message,
google::protobuf::io::ZeroCopyOutputStream* rawOutput) {
google::protobuf::io::CodedOutputStream output(rawOutput);
const int size = message.ByteSize();
output.WriteVarint32(size);
uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);
if (buffer != nullptr) {
message.SerializeWithCachedSizesToArray(buffer);
} else {
message.SerializeWithCachedSizes(&output);
if (output.HadError()) {
return false;
}
}
return true;
}
static std::string safe_name(const sstring& name) {
auto rep = boost::replace_all_copy(boost::replace_all_copy(name, "-", "_"), " ", "_");
boost::remove_erase_if(rep, boost::is_any_of("+()"));
return rep;
}
static sstring collectd_name(const metrics::impl::metric_id & id, uint32_t cpu) {
return safe_name(id.group_name());
}
static pm::Metric* add_label(pm::Metric* mt, const metrics::impl::metric_id & id, uint32_t cpu) {
auto label = mt->add_label();
label->set_name("shard");
label->set_value(std::to_string(cpu));
label = mt->add_label();
label->set_name("type");
label->set_value(id.measurement());
if (id.sub_measurement() != "") {
label = mt->add_label();
label->set_name("metric");
label->set_value(id.sub_measurement());
}
const sstring& host = scollectd::get_impl().host();
if (host != "") {
label = mt->add_label();
label->set_name("instance");
label->set_value(host);
}
return mt;
}
static void fill_metric(pm::MetricFamily& mf, const metrics::impl::metric_value& c,
const metrics::impl::metric_id & id, uint32_t cpu) {
switch (c.type()) {
case scollectd::data_type::DERIVE:
add_label(mf.add_metric(), id, cpu)->mutable_counter()->set_value(c.i());
mf.set_type(pm::MetricType::COUNTER);
break;
case scollectd::data_type::GAUGE:
add_label(mf.add_metric(), id, cpu)->mutable_gauge()->set_value(c.d());
mf.set_type(pm::MetricType::GAUGE);
break;
default:
add_label(mf.add_metric(), id, cpu)->mutable_counter()->set_value(c.ui());
mf.set_type(pm::MetricType::COUNTER);
break;
}
}
future<> start(httpd::http_server_control& http_server, const config& ctx) {
return http_server.set_routes([&ctx](httpd::routes& r) {
httpd::future_handler_function f = [&ctx](std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
return do_with(std::vector<metrics::impl::values_copy>(), [rep = std::move(rep), &ctx] (auto& vec) mutable {
vec.resize(smp::count);
return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) {
return smp::submit_to(cpu, [] {
return metrics::impl::get_values();
}).then([&vec, cpu] (auto res) {
vec[cpu] = res;
});
}).then([rep = std::move(rep), &vec, &ctx]() mutable {
uint32_t cpu = 0;
for (auto value: vec) {
for (auto i : value) {
pm::MetricFamily mtf;
std::string s;
google::protobuf::io::StringOutputStream os(&s);
mtf.set_name(ctx.prefix + "_" + collectd_name(i.first, cpu));
mtf.set_help(ctx.metric_help);
fill_metric(mtf, i.second, i.first, cpu);
if (mtf.metric_size() > 0) {
std::stringstream ss;
if (!write_delimited_to(mtf, &os)) {
seastar_logger.warn("Failed to write protobuf metrics");
}
rep->_content += s;
}
}
cpu++;
}
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
});
});
};
r.put(GET, "/metrics", new httpd::function_handler(f, "proto"));
});
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix CI bug<commit_after><|endoftext|> |
<commit_before><commit_msg>Add const modifiers.<commit_after><|endoftext|> |
<commit_before>#ifndef HEAPS_H
#define HEAPS_H
#include"objects.hpp"
#include<cstring>
#include<utility>
#include<boost/shared_ptr.hpp>
class Generic;
class SharedVar;
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
class Semispace {
private:
void* mem;
void* allocpt;
void* lifoallocpt;
size_t prev_alloc;
size_t max;
public:
Semispace(size_t);
~Semispace();
void* alloc(size_t);
void dealloc(void*);
void* lifo_alloc(void);
void lifo_dealloc(void*);
void lifo_dealloc_abort(void*);
void resize(size_t);
bool can_fit(size_t) const;
size_t size(void) const { return max; };
size_t used(void) const {
return (size_t)(((char*) allocpt) - ((char*) mem)) +
(size_t)
((((char*) mem) + max) - ((char*) lifoallocpt));
};
void clone(boost::scoped_ptr<Semispace>&, Generic*&) const;
friend class Heap;
};
#endif //HEAPS_H
<commit_msg>inc/heaps.hpp: started Heap class, made Semispace inherit from boost::nocopyable<commit_after>#ifndef HEAPS_H
#define HEAPS_H
#include"objects.hpp"
#include<cstring>
#include<utility>
#include<boost/scoped_ptr.hpp>
#include<boost/noncopyable.hpp>
class Generic;
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
class Semispace : boost::nocopyable {
private:
void* mem;
void* allocpt;
void* lifoallocpt;
size_t prev_alloc;
size_t max;
public:
Semispace(size_t);
~Semispace();
void* alloc(size_t);
void dealloc(void*);
void* lifo_alloc(void);
void lifo_dealloc(void*);
void lifo_dealloc_abort(void*);
void resize(size_t);
bool can_fit(size_t) const;
size_t size(void) const { return max; };
size_t used(void) const {
return (size_t)(((char*) allocpt) - ((char*) mem)) +
(size_t)
((((char*) mem) + max) - ((char*) lifoallocpt));
};
void clone(boost::scoped_ptr<Semispace>&, Generic*&) const;
friend class Heap;
};
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
class Heap : boost::nocopyable {
private:
boost::scoped_ptr<Semispace> main;
void GC(void);
protected:
virtual Object::ref root_object(void) const =0;
public:
template<class T>
inline T* create(void) {
/*compile-time checking that T inherits from Generic*/
Generic* _create_template_must_be_Generic_ =
static_cast<Generic*>((T*) 0);
size_t sz = Object::round_up_to_alignment(sizeof(T));
if(!main->can_fit(sz)) GC();
void* pt = main->alloc(sz);
try {
new(pt) T();
return pt;
} catch(...) {
main->dealloc(pt);
throw;
}
}
template<class T>
inline T* create_variadic(size_t extra) {
/*TODO: consider splitting Generic hierarchy into two
hierarchies inheriting from Generic, one hierarchy for
non-variadic types, the other hierarchy for variadic
types.
*/
Generic* _create_variadic_template_must_be_Generic_ =
static_cast<Generic*>((T*) 0);
size_t sz = Object::round_up_to_alignment(sizeof(T))
+ Object::round_up_to_alignment(
extra * sizeof(Object::ref)
)
;
if(!main->can_fit(sz)) GC();
void* pt = main->alloc(sz);
try {
new(pt) T(extra);
return pt;
} catch(...) {
main->dealloc(pt);
throw;
}
}
};
#endif //HEAPS_H
<|endoftext|> |
<commit_before>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include<cstring>
#include"objects.hpp"
#include"generics.hpp"
#include"heaps.hpp"
#include"executors.hpp"
/*-----------------------------------------------------------------------------
Specialized broken heart tags
-----------------------------------------------------------------------------*/
/*The BrokenHeartFor classes are specialized for each
generic-derived class. They should *not* add any
storage.
*/
template<class T>
class BrokenHeartFor : public BrokenHeart {
private:
// disallowed
BrokenHeartFor<T>();
BrokenHeartFor<T>(BrokenHeartFor<T> const&);
public:
virtual size_t real_size(void) const {
return compute_size<T>();
}
explicit BrokenHeartFor<T>(Generic* x) : BrokenHeart(x) { }
};
template<class T>
class BrokenHeartForVariadic : public BrokenHeartVariadic {
private:
// disallowed
BrokenHeartForVariadic<T>();
BrokenHeartForVariadic<T>(BrokenHeartForVariadic<T> const&);
public:
virtual size_t real_size(void) const {
return compute_size_variadic<T>(sz);
}
BrokenHeartForVariadic<T>(Generic* x, size_t nsz)
: BrokenHeartVariadic(x, nsz) { }
};
/*-----------------------------------------------------------------------------
Base classes for Generic-derived objects
-----------------------------------------------------------------------------*/
template<class T>
class GenericDerived : public Generic {
protected:
GenericDerived<T>(void) { }
public:
virtual size_t real_size(void) const {
return compute_size<T>();
}
virtual Generic* clone(Semispace* nsp) const {
void* pt = nsp->alloc(real_size());
try {
new(pt) T(*static_cast<T const*>(this));
return (Generic*) pt;
} catch(...) {
nsp->dealloc(pt);
throw;
}
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
/*This class implements a variable-size object by informing the
memory system to reserve extra space.
Note that classes which derive from this should provide
a factory function!
*/
template<class T>
class GenericDerivedVariadic : public Generic {
GenericDerivedVariadic<T>(void); // disallowed!
protected:
/*number of extra Object::ref's*/
size_t sz;
/*used by the derived classes to get access to
the variadic data at the end of the object.
*/
inline Object::ref& index(size_t i) {
void* vp = this;
char* cp = (char*) vp;
cp = cp + sizeof(T);
Object::ref* op = (Object::ref*) cp;
return op[i];
}
explicit GenericDerivedVariadic<T>(size_t nsz) : sz(nsz) {
/*clear the extra references*/
for(size_t i; i < nsz; ++i) {
index(i) = Object::nil();
}
}
GenericDerivedVariadic<T>(GenericDerivedVariadic<T> const& o)
: sz(o.sz) {
for(size_t i; i < sz; ++i) {
index(i) = o.index(i);
}
}
public:
virtual size_t real_size(void) const {
return compute_size_variadic<T>(sz);
}
virtual Generic* clone(Semispace* nsp) const {
void* pt = nsp->alloc(real_size());
try {
new(pt) T(*static_cast<T const*>(this));
return (Generic*) pt;
} catch(...) {
nsp->dealloc(pt);
throw;
}
}
virtual void break_heart(Generic *to) {
Generic* gp = this;
size_t nsz = sz; //save this before dtoring!
gp->~Generic();
new((void*) gp) BrokenHeartForVariadic<T>(to, nsz);
}
};
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
void throw_HlError(char const*);
/*Usage:
Cons* cp = expect_type<Cons>(proc.stack().top(),
"Your mom expects a Cons cell on top"
);
*/
template<class T>
static inline T* expect_type(Object::ref x, char const* error) {
if(!is_a<Generic*>(x)) throw_HlError(error);
T* tmp = dynamic_cast<T*>(as_a<Generic*>(x));
if(!tmp) throw_HlError(error);
return tmp;
}
/*
* Cons cell
*/
class Cons : public GenericDerived<Cons> {
private:
Object::ref car_ref;
Object::ref cdr_ref;
public:
inline Object::ref car() { return car_ref; }
inline Object::ref cdr() { return cdr_ref; }
inline Object::ref scar(Object::ref x) { return car_ref = x; }
inline Object::ref scdr(Object::ref x) { return cdr_ref = x; }
Cons() : car_ref(Object::nil()), cdr_ref(Object::nil()) {}
/*
* Note that we *can't* safely construct any heap-based objects
* by, say, passing them any of their data. This is because the
* act of allocating space for these objects may start a garbage
* collection, which can move *other* objects. So any references
* passed into the constructor will be invalid; instead, the
* process must save the data to be put in the new object in a
* root location (such as the process stack) and after it is
* given the newly-constructed object, it must store the data
* straight from the root location.
*/
void traverse_references(GenericTraverser *gt) {
gt->traverse(car_ref);
gt->traverse(cdr_ref);
}
};
static inline Object::ref car(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'car expects a Cons cell")->car();
}
static inline Object::ref cdr(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'cdr expects a Cons cell")->cdr();
}
static inline Object::ref scar(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scar expects a true Cons cell")->scar(v);
}
static inline Object::ref scdr(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scdr expects a true Cons cell")->scdr(v);
}
/*-----------------------------------------------------------------------------
HlPid
-----------------------------------------------------------------------------*/
/*Represents a process that can
be sent messages to by this process
*/
class Process;
class HlPid : public GenericDerived<HlPid> {
public:
Process* process;
};
/*-----------------------------------------------------------------------------
Closures
-----------------------------------------------------------------------------*/
/*closure structures shouldn't be
modified after they are constructed
*/
class Closure : public GenericDerivedVariadic<Closure> {
private:
bytecode_t *body;
public:
Closure(size_t sz) : GenericDerivedVariadic<Closure>(sz) {}
Object::ref& operator[](size_t i) { return index(i); }
bytecode_t* code() { return body; }
static Closure* NewClosure(Heap & h, bytecode_t *body, size_t n);
};
class KClosure : public GenericDerivedVariadic<KClosure> {
private:
bytecode_t *body;
bool nonreusable;
public:
KClosure(size_t sz) : GenericDerivedVariadic<KClosure>(sz),
nonreusable(false) {}
bytecode_t* code() { return body; }
void codereset(bytecode_t *b) { body = b; }
void banreuse() { nonreusable = true; }
bool reusable() { return !nonreusable; }
static KClosure* NewKClosure(Heap & h, bytecode_t *body, size_t n);
};
#endif //TYPES_H
<commit_msg>inc/types.hpp: Regarding KClosure and Closure types<commit_after>#ifndef TYPES_H
#define TYPES_H
/*
Defines a set of types for use on the hl-side.
*/
#include<cstring>
#include"objects.hpp"
#include"generics.hpp"
#include"heaps.hpp"
#include"executors.hpp"
/*-----------------------------------------------------------------------------
Specialized broken heart tags
-----------------------------------------------------------------------------*/
/*The BrokenHeartFor classes are specialized for each
generic-derived class. They should *not* add any
storage.
*/
template<class T>
class BrokenHeartFor : public BrokenHeart {
private:
// disallowed
BrokenHeartFor<T>();
BrokenHeartFor<T>(BrokenHeartFor<T> const&);
public:
virtual size_t real_size(void) const {
return compute_size<T>();
}
explicit BrokenHeartFor<T>(Generic* x) : BrokenHeart(x) { }
};
template<class T>
class BrokenHeartForVariadic : public BrokenHeartVariadic {
private:
// disallowed
BrokenHeartForVariadic<T>();
BrokenHeartForVariadic<T>(BrokenHeartForVariadic<T> const&);
public:
virtual size_t real_size(void) const {
return compute_size_variadic<T>(sz);
}
BrokenHeartForVariadic<T>(Generic* x, size_t nsz)
: BrokenHeartVariadic(x, nsz) { }
};
/*-----------------------------------------------------------------------------
Base classes for Generic-derived objects
-----------------------------------------------------------------------------*/
template<class T>
class GenericDerived : public Generic {
protected:
GenericDerived<T>(void) { }
public:
virtual size_t real_size(void) const {
return compute_size<T>();
}
virtual Generic* clone(Semispace* nsp) const {
void* pt = nsp->alloc(real_size());
try {
new(pt) T(*static_cast<T const*>(this));
return (Generic*) pt;
} catch(...) {
nsp->dealloc(pt);
throw;
}
}
virtual void break_heart(Generic* to) {
Generic* gp = this;
gp->~Generic();
new((void*) gp) BrokenHeartFor<T>(to);
};
};
/*This class implements a variable-size object by informing the
memory system to reserve extra space.
Note that classes which derive from this should provide
a factory function!
*/
template<class T>
class GenericDerivedVariadic : public Generic {
GenericDerivedVariadic<T>(void); // disallowed!
protected:
/*number of extra Object::ref's*/
size_t sz;
/*used by the derived classes to get access to
the variadic data at the end of the object.
*/
inline Object::ref& index(size_t i) {
void* vp = this;
char* cp = (char*) vp;
cp = cp + sizeof(T);
Object::ref* op = (Object::ref*) cp;
return op[i];
}
explicit GenericDerivedVariadic<T>(size_t nsz) : sz(nsz) {
/*clear the extra references*/
for(size_t i; i < nsz; ++i) {
index(i) = Object::nil();
}
}
GenericDerivedVariadic<T>(GenericDerivedVariadic<T> const& o)
: sz(o.sz) {
for(size_t i; i < sz; ++i) {
index(i) = o.index(i);
}
}
public:
virtual size_t real_size(void) const {
return compute_size_variadic<T>(sz);
}
virtual Generic* clone(Semispace* nsp) const {
void* pt = nsp->alloc(real_size());
try {
new(pt) T(*static_cast<T const*>(this));
return (Generic*) pt;
} catch(...) {
nsp->dealloc(pt);
throw;
}
}
virtual void break_heart(Generic *to) {
Generic* gp = this;
size_t nsz = sz; //save this before dtoring!
gp->~Generic();
new((void*) gp) BrokenHeartForVariadic<T>(to, nsz);
}
};
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
void throw_HlError(char const*);
/*Usage:
Cons* cp = expect_type<Cons>(proc.stack().top(),
"Your mom expects a Cons cell on top"
);
*/
template<class T>
static inline T* expect_type(Object::ref x, char const* error) {
if(!is_a<Generic*>(x)) throw_HlError(error);
T* tmp = dynamic_cast<T*>(as_a<Generic*>(x));
if(!tmp) throw_HlError(error);
return tmp;
}
/*
* Cons cell
*/
class Cons : public GenericDerived<Cons> {
private:
Object::ref car_ref;
Object::ref cdr_ref;
public:
inline Object::ref car() { return car_ref; }
inline Object::ref cdr() { return cdr_ref; }
inline Object::ref scar(Object::ref x) { return car_ref = x; }
inline Object::ref scdr(Object::ref x) { return cdr_ref = x; }
Cons() : car_ref(Object::nil()), cdr_ref(Object::nil()) {}
/*
* Note that we *can't* safely construct any heap-based objects
* by, say, passing them any of their data. This is because the
* act of allocating space for these objects may start a garbage
* collection, which can move *other* objects. So any references
* passed into the constructor will be invalid; instead, the
* process must save the data to be put in the new object in a
* root location (such as the process stack) and after it is
* given the newly-constructed object, it must store the data
* straight from the root location.
*/
void traverse_references(GenericTraverser *gt) {
gt->traverse(car_ref);
gt->traverse(cdr_ref);
}
};
static inline Object::ref car(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'car expects a Cons cell")->car();
}
static inline Object::ref cdr(Object::ref x) {
if(!x) return x;
return expect_type<Cons>(x,"'cdr expects a Cons cell")->cdr();
}
static inline Object::ref scar(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scar expects a true Cons cell")->scar(v);
}
static inline Object::ref scdr(Object::ref c, Object::ref v) {
return expect_type<Cons>(c,"'scdr expects a true Cons cell")->scdr(v);
}
/*-----------------------------------------------------------------------------
HlPid
-----------------------------------------------------------------------------*/
/*Represents a process that can
be sent messages to by this process
*/
class Process;
class HlPid : public GenericDerived<HlPid> {
public:
Process* process;
};
/*-----------------------------------------------------------------------------
Closures
-----------------------------------------------------------------------------*/
/*closure structures shouldn't be
modified after they are constructed
*/
class Closure : public GenericDerivedVariadic<Closure> {
private:
bytecode_t *body;
public:
Closure(size_t sz) : GenericDerivedVariadic<Closure>(sz) {}
Object::ref& operator[](size_t i) { return index(i); }
bytecode_t* code() { return body; }
static Closure* NewClosure(Heap & h, bytecode_t *body, size_t n);
};
/*I suggest merging Closure and KClosure into one class, because
the broken heart system can't allow us to derive from a
GenericDerivedVariadic<>-derived base class without some serious
hacking.
Multiple inheritance is not safe because we cannot specify the
order in which base classes are put into the derived classes,
meaning that our memory system might expect a Generic but get
some other interface base.
Alternatively change GenericDerivedVariadic<> to accept an
optional second template parameter which defaults to
Generic, and have GenericDerivedVariadic<> derive from that.
However that will require making operator[] virtual, because
KClosures are longer than Closures and the operator[] will
have to take that into account.
*/
class KClosure : public GenericDerivedVariadic<KClosure> {
private:
bytecode_t *body;
bool nonreusable;
public:
KClosure(size_t sz) : GenericDerivedVariadic<KClosure>(sz),
nonreusable(false) {}
bytecode_t* code() { return body; }
void codereset(bytecode_t *b) { body = b; }
void banreuse() { nonreusable = true; }
bool reusable() { return !nonreusable; }
static KClosure* NewKClosure(Heap & h, bytecode_t *body, size_t n);
};
#endif //TYPES_H
<|endoftext|> |
<commit_before>
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "include/config.h"
#include "mds/MDCluster.h"
#include "mds/MDS.h"
#include "osd/OSD.h"
#include "client/Client.h"
#include "client/fuse.h"
#include "common/Timer.h"
#include "msg/FakeMessenger.h"
#define NUMMDS g_conf.num_mds
#define NUMOSD g_conf.num_osd
#define NUMCLIENT g_conf.num_client
class C_Test : public Context {
public:
void finish(int r) {
cout << "C_Test->finish(" << r << ")" << endl;
}
};
class C_Test2 : public Context {
public:
void finish(int r) {
cout << "C_Test2->finish(" << r << ")" << endl;
g_timer.add_event_after(2, new C_Test);
}
};
int main(int oargc, char **oargv) {
cerr << "fakefuse starting" << endl;
int argc;
char **argv;
parse_config_options(oargc, oargv,
argc, argv,
true);
MDCluster *mdc = new MDCluster(NUMMDS, NUMOSD);
// start messenger thread
fakemessenger_startthread();
//g_timer.add_event_after(5.0, new C_Test2);
//g_timer.add_event_after(10.0, new C_Test);
int mkfs = 0;
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "--fastmkfs") == 0) {
mkfs = MDS_MKFS_FAST;
argv[i] = 0;
argc--;
break;
}
if (strcmp(argv[i], "--fullmkfs") == 0) {
mkfs = MDS_MKFS_FULL;
argv[i] = 0;
argc--;
break;
}
}
// create osd
OSD *osd[NUMOSD];
for (int i=0; i<NUMOSD; i++) {
osd[i] = new OSD(i, new FakeMessenger(MSG_ADDR_OSD(i)));
osd[i]->init();
}
// create mds
MDS *mds[NUMMDS];
for (int i=0; i<NUMMDS; i++) {
mds[i] = new MDS(mdc, i, new FakeMessenger(MSG_ADDR_MDS(i)));
mds[i]->init();
}
// create client
Client *client[NUMCLIENT];
for (int i=0; i<NUMCLIENT; i++) {
client[i] = new Client(mdc, i, new FakeMessenger(MSG_ADDR_CLIENT(0)));
client[i]->init();
// start up fuse
// use my argc, argv (make sure you pass a mount point!)
cout << "starting fuse on pid " << getpid() << endl;
client[i]->mount(mkfs);
ceph_fuse_main(client[i], argc, argv);
client[i]->unmount();
cout << "fuse finished on pid " << getpid() << endl;
client[i]->shutdown();
}
// wait for it to finish
cout << "DONE -----" << endl;
fakemessenger_stopthread(); // blocks until messenger stops
// cleanup
for (int i=0; i<NUMMDS; i++) {
delete mds[i];
}
for (int i=0; i<NUMOSD; i++) {
delete osd[i];
}
for (int i=0; i<NUMCLIENT; i++) {
delete client[i];
}
delete mdc;
return 0;
}
<commit_msg>*** empty log message ***<commit_after>
#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;
#include "include/config.h"
#include "mds/MDCluster.h"
#include "mds/MDS.h"
#include "osd/OSD.h"
#include "client/Client.h"
#include "client/fuse.h"
#include "common/Timer.h"
#include "msg/FakeMessenger.h"
#define NUMMDS g_conf.num_mds
#define NUMOSD g_conf.num_osd
#define NUMCLIENT g_conf.num_client
class C_Test : public Context {
public:
void finish(int r) {
cout << "C_Test->finish(" << r << ")" << endl;
}
};
class C_Test2 : public Context {
public:
void finish(int r) {
cout << "C_Test2->finish(" << r << ")" << endl;
g_timer.add_event_after(2, new C_Test);
}
};
int main(int oargc, char **oargv) {
cerr << "fakefuse starting" << endl;
int argc;
char **argv;
parse_config_options(oargc, oargv,
argc, argv);
MDCluster *mdc = new MDCluster(NUMMDS, NUMOSD);
// start messenger thread
fakemessenger_startthread();
//g_timer.add_event_after(5.0, new C_Test2);
//g_timer.add_event_after(10.0, new C_Test);
int mkfs = 0;
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "--fastmkfs") == 0) {
mkfs = MDS_MKFS_FAST;
argv[i] = 0;
argc--;
break;
}
if (strcmp(argv[i], "--fullmkfs") == 0) {
mkfs = MDS_MKFS_FULL;
argv[i] = 0;
argc--;
break;
}
}
// create osd
OSD *osd[NUMOSD];
for (int i=0; i<NUMOSD; i++) {
osd[i] = new OSD(i, new FakeMessenger(MSG_ADDR_OSD(i)));
osd[i]->init();
}
// create mds
MDS *mds[NUMMDS];
for (int i=0; i<NUMMDS; i++) {
mds[i] = new MDS(mdc, i, new FakeMessenger(MSG_ADDR_MDS(i)));
mds[i]->init();
}
// create client
Client *client[NUMCLIENT];
for (int i=0; i<NUMCLIENT; i++) {
client[i] = new Client(mdc, i, new FakeMessenger(MSG_ADDR_CLIENT(0)));
client[i]->init();
// start up fuse
// use my argc, argv (make sure you pass a mount point!)
cout << "starting fuse on pid " << getpid() << endl;
client[i]->mount(mkfs);
ceph_fuse_main(client[i], argc, argv);
client[i]->unmount();
cout << "fuse finished on pid " << getpid() << endl;
client[i]->shutdown();
}
// wait for it to finish
cout << "DONE -----" << endl;
fakemessenger_stopthread(); // blocks until messenger stops
// cleanup
for (int i=0; i<NUMMDS; i++) {
delete mds[i];
}
for (int i=0; i<NUMOSD; i++) {
delete osd[i];
}
for (int i=0; i<NUMCLIENT; i++) {
delete client[i];
}
delete mdc;
return 0;
}
<|endoftext|> |
<commit_before>/*
cryptographyguiclient.cpp
Copyright (c) 2004 by Olivier Goffart <ogoffart@kde.org>
Copyright (c) 2007 by Charles Connell <charles@connells.org>
Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "cryptographyguiclient.h"
#include "cryptographyplugin.h"
#include "cryptographysettings.h"
#include <kopete/kopetemetacontact.h>
#include <kopete/kopetecontact.h>
#include <kopete/kopetecontactlist.h>
#include <kopete/kopetechatsession.h>
#include <kopete/ui/kopeteview.h>
#include <kopete/kopeteuiglobal.h>
#include <kopete/kopeteprotocol.h>
#include <kopete/kabcpersistence.h>
#include <kabc/addressee.h>
#include <kabc/addressbook.h>
#include "exportkeys.h"
#include <kaction.h>
#include <klocalizedstring.h>
#include <kaboutdata.h>
#include <kicon.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <QList>
#include <kactioncollection.h>
class CryptographyPlugin;
CryptographyGUIClient::CryptographyGUIClient ( Kopete::ChatSession *parent )
: QObject ( parent ) , KXMLGUIClient ( parent )
{
if ( !parent || parent->members().isEmpty() )
{
deleteLater(); //we refuse to build this client, it is based on wrong parametters
return;
}
KAboutData aboutData ( "kopete_cryptography", 0, ki18n ( "Cryptography" ) , "1.3.0" );
setComponentData ( KComponentData ( &aboutData ) );
setXMLFile ( "cryptographychatui.rc" );
QList<Kopete::Contact*> mb=parent->members();
bool wantEncrypt = false, wantSign = false, keysAvailable = false;
// if any contacts have previously been encrypted/signed to, enable that now
foreach ( Kopete::Contact *c , parent->members() )
{
Kopete::MetaContact *mc = c->metaContact();
if ( !mc )
{
deleteLater();
return;
}
if ( c->pluginData ( CryptographyPlugin::plugin(), "encrypt_messages" ) == "on" )
wantEncrypt = true;
if ( c->pluginData ( CryptographyPlugin::plugin(), "sign_messages" ) == "on" )
wantSign = true;
if ( ! ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() ) )
keysAvailable = true;
}
m_encAction = new KToggleAction ( KIcon ( "document-encrypt" ), i18nc ( "@action toggle action", "Encrypt Messages" ), this );
actionCollection()->addAction ( "encryptionToggle", m_encAction );
m_signAction = new KToggleAction ( KIcon ( "document-sign" ), i18nc ( "@action toggle action", "Sign Messages" ), this );
actionCollection()->addAction ( "signToggle", m_signAction );
m_exportAction = new KAction ( i18nc ( "@action toggle action", "Export Contacts' Keys to Address Book" ), this );
actionCollection()->addAction ( "export", m_exportAction );
m_encAction->setChecked ( wantEncrypt && keysAvailable );
m_signAction->setChecked ( wantSign );
slotEncryptToggled();
slotSignToggled();
connect ( m_encAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotEncryptToggled() ) );
connect ( m_signAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotSignToggled() ) );
connect ( m_exportAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotExport() ) );
}
CryptographyGUIClient::~CryptographyGUIClient()
{}
// set the pluginData to reflect new setting
void CryptographyGUIClient::slotSignToggled()
{
if ( m_signAction->isChecked() ) {
if ( CryptographySettings::privateKeyFingerprint().isEmpty() ) {
KMessageBox::sorry ( Kopete::UI::Global::mainWidget(),
i18nc ( "@info", "You have not selected a private key for yourself, so signing is not possible. Please select a private key in the Cryptography preferences dialog" ),
i18n ( "No Private Key" ) );
m_signAction->setChecked ( false );
}
}
static_cast<Kopete::ChatSession *> ( parent() )->members().first()->setPluginData
( CryptographyPlugin::plugin(), "sign_messages", m_signAction->isChecked() ? "on" : "off" );
}
void CryptographyGUIClient::slotEncryptToggled()
{
Kopete::ChatSession *csn = static_cast<Kopete::ChatSession *> ( parent() );
if ( m_encAction->isChecked() )
{
QStringList keyless;
QWidget *w = 0;
if ( csn->view() )
w = csn->view()->mainWidget();
foreach ( Kopete::Contact * c , csn->members() )
{
Kopete::MetaContact *mc = c->metaContact();
if ( !mc )
continue;
// if encrypting and we don't have a key, look in address book
if ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() )
{
// to grab the public key from KABC (this same code is in crytographyselectuserkey.cpp)
KABC::Addressee addressee = Kopete::KABCPersistence::self()->addressBook()->findByUid
( mc->metaContactId() );
if ( ! addressee.isEmpty() )
{
QStringList keys;
keys = CryptographyPlugin::getKabcKeys ( mc->metaContactId() );
// ask user if they want to use key found in address book
KABC::Addressee tempAddressee = Kopete::KABCPersistence::self()->
addressBook()->findByUid ( mc->metaContactId() );
mc->setPluginData ( CryptographyPlugin::plugin(), "gpgKey",
CryptographyPlugin::kabcKeySelector ( mc->displayName(), tempAddressee.assembledName(), keys, w ) );
}
}
if ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() )
keyless.append ( mc->displayName() );
}
// if encrypting and using unsupported protocols, warn user
QString protocol ( csn->protocol()->metaObject()->className() );
if ( ! CryptographyPlugin::supportedProtocols().contains ( protocol ) ) {
KMessageBox::information ( w, i18nc ( "@info", "This protocol may not work with messages that are encrypted. This is because encrypted messages are very long, and the server or peer may reject them due to their length. To avoid being signed off or your account being warned or temporarily suspended, turn off encryption." ),
i18n ( "Cryptography Unsupported Protocol" ),
"Warn about unsupported " + QString ( csn->protocol()->metaObject()->className() ) );
}
// we can't encrypt if we don't have every single key we need
if ( !keyless.isEmpty() )
{
KMessageBox::sorry ( w, i18ncp ( "@info", "You need to select a public key for %2 to send encrypted messages to that contact.", "You need to select a public key for the following meta-contacts to send encrypted messages to them:\n%2",
keyless.count(), keyless.join ( "\n" ) ),
i18np ( "Missing public key", "Missing public keys", keyless.count() ) );
m_encAction->setChecked ( false );
}
}
// finally, set the pluginData to reflect new settings
if ( csn->members().first() )
csn->members().first()->setPluginData ( CryptographyPlugin::plugin() , "encrypt_messages" ,
m_encAction->isChecked() ? "on" : "off" );
}
// put up dialog to allow user to choose which keys to export to address book
void CryptographyGUIClient::slotExport()
{
Kopete::ChatSession *csn = qobject_cast<Kopete::ChatSession *> ( parent() );
QList <Kopete::MetaContact*> mcs;
foreach ( Kopete::Contact* c, csn->members() )
mcs.append ( c->metaContact() );
ExportKeys dialog ( mcs, csn->view()->mainWidget() );
dialog.exec();
}
#include "cryptographyguiclient.moc"
<commit_msg>Proof-reading.<commit_after>/*
cryptographyguiclient.cpp
Copyright (c) 2004 by Olivier Goffart <ogoffart@kde.org>
Copyright (c) 2007 by Charles Connell <charles@connells.org>
Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "cryptographyguiclient.h"
#include "cryptographyplugin.h"
#include "cryptographysettings.h"
#include <kopete/kopetemetacontact.h>
#include <kopete/kopetecontact.h>
#include <kopete/kopetecontactlist.h>
#include <kopete/kopetechatsession.h>
#include <kopete/ui/kopeteview.h>
#include <kopete/kopeteuiglobal.h>
#include <kopete/kopeteprotocol.h>
#include <kopete/kabcpersistence.h>
#include <kabc/addressee.h>
#include <kabc/addressbook.h>
#include "exportkeys.h"
#include <kaction.h>
#include <klocalizedstring.h>
#include <kaboutdata.h>
#include <kicon.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <QList>
#include <kactioncollection.h>
class CryptographyPlugin;
CryptographyGUIClient::CryptographyGUIClient ( Kopete::ChatSession *parent )
: QObject ( parent ) , KXMLGUIClient ( parent )
{
if ( !parent || parent->members().isEmpty() )
{
deleteLater(); //we refuse to build this client, it is based on wrong parametters
return;
}
KAboutData aboutData ( "kopete_cryptography", 0, ki18n ( "Cryptography" ) , "1.3.0" );
setComponentData ( KComponentData ( &aboutData ) );
setXMLFile ( "cryptographychatui.rc" );
QList<Kopete::Contact*> mb=parent->members();
bool wantEncrypt = false, wantSign = false, keysAvailable = false;
// if any contacts have previously been encrypted/signed to, enable that now
foreach ( Kopete::Contact *c , parent->members() )
{
Kopete::MetaContact *mc = c->metaContact();
if ( !mc )
{
deleteLater();
return;
}
if ( c->pluginData ( CryptographyPlugin::plugin(), "encrypt_messages" ) == "on" )
wantEncrypt = true;
if ( c->pluginData ( CryptographyPlugin::plugin(), "sign_messages" ) == "on" )
wantSign = true;
if ( ! ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() ) )
keysAvailable = true;
}
m_encAction = new KToggleAction ( KIcon ( "document-encrypt" ), i18nc ( "@action toggle action", "Encrypt Messages" ), this );
actionCollection()->addAction ( "encryptionToggle", m_encAction );
m_signAction = new KToggleAction ( KIcon ( "document-sign" ), i18nc ( "@action toggle action", "Sign Messages" ), this );
actionCollection()->addAction ( "signToggle", m_signAction );
m_exportAction = new KAction ( i18nc ( "@action toggle action", "Export Contacts' Keys to Address Book" ), this );
actionCollection()->addAction ( "export", m_exportAction );
m_encAction->setChecked ( wantEncrypt && keysAvailable );
m_signAction->setChecked ( wantSign );
slotEncryptToggled();
slotSignToggled();
connect ( m_encAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotEncryptToggled() ) );
connect ( m_signAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotSignToggled() ) );
connect ( m_exportAction, SIGNAL ( triggered ( bool ) ), this, SLOT ( slotExport() ) );
}
CryptographyGUIClient::~CryptographyGUIClient()
{}
// set the pluginData to reflect new setting
void CryptographyGUIClient::slotSignToggled()
{
if ( m_signAction->isChecked() ) {
if ( CryptographySettings::privateKeyFingerprint().isEmpty() ) {
KMessageBox::sorry ( Kopete::UI::Global::mainWidget(),
i18nc ( "@info", "You have not selected a private key for yourself, so signing is not possible. Please select a private key in the Cryptography preferences dialog." ),
i18n ( "No Private Key" ) );
m_signAction->setChecked ( false );
}
}
static_cast<Kopete::ChatSession *> ( parent() )->members().first()->setPluginData
( CryptographyPlugin::plugin(), "sign_messages", m_signAction->isChecked() ? "on" : "off" );
}
void CryptographyGUIClient::slotEncryptToggled()
{
Kopete::ChatSession *csn = static_cast<Kopete::ChatSession *> ( parent() );
if ( m_encAction->isChecked() )
{
QStringList keyless;
QWidget *w = 0;
if ( csn->view() )
w = csn->view()->mainWidget();
foreach ( Kopete::Contact * c , csn->members() )
{
Kopete::MetaContact *mc = c->metaContact();
if ( !mc )
continue;
// if encrypting and we don't have a key, look in address book
if ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() )
{
// to grab the public key from KABC (this same code is in crytographyselectuserkey.cpp)
KABC::Addressee addressee = Kopete::KABCPersistence::self()->addressBook()->findByUid
( mc->metaContactId() );
if ( ! addressee.isEmpty() )
{
QStringList keys;
keys = CryptographyPlugin::getKabcKeys ( mc->metaContactId() );
// ask user if they want to use key found in address book
KABC::Addressee tempAddressee = Kopete::KABCPersistence::self()->
addressBook()->findByUid ( mc->metaContactId() );
mc->setPluginData ( CryptographyPlugin::plugin(), "gpgKey",
CryptographyPlugin::kabcKeySelector ( mc->displayName(), tempAddressee.assembledName(), keys, w ) );
}
}
if ( mc->pluginData ( CryptographyPlugin::plugin(), "gpgKey" ).isEmpty() )
keyless.append ( mc->displayName() );
}
// if encrypting and using unsupported protocols, warn user
QString protocol ( csn->protocol()->metaObject()->className() );
if ( ! CryptographyPlugin::supportedProtocols().contains ( protocol ) ) {
KMessageBox::information ( w, i18nc ( "@info", "This protocol may not work with messages that are encrypted. This is because encrypted messages are very long, and the server or peer may reject them due to their length. To avoid being signed off or your account being warned or temporarily suspended, turn off encryption." ),
i18n ( "Cryptography Unsupported Protocol" ),
"Warn about unsupported " + QString ( csn->protocol()->metaObject()->className() ) );
}
// we can't encrypt if we don't have every single key we need
if ( !keyless.isEmpty() )
{
KMessageBox::sorry ( w, i18ncp ( "@info", "You need to select a public key for %2 to send encrypted messages to that contact.", "You need to select a public key for the following meta-contacts to send encrypted messages to them:\n%2",
keyless.count(), keyless.join ( "\n" ) ),
i18np ( "Missing public key", "Missing public keys", keyless.count() ) );
m_encAction->setChecked ( false );
}
}
// finally, set the pluginData to reflect new settings
if ( csn->members().first() )
csn->members().first()->setPluginData ( CryptographyPlugin::plugin() , "encrypt_messages" ,
m_encAction->isChecked() ? "on" : "off" );
}
// put up dialog to allow user to choose which keys to export to address book
void CryptographyGUIClient::slotExport()
{
Kopete::ChatSession *csn = qobject_cast<Kopete::ChatSession *> ( parent() );
QList <Kopete::MetaContact*> mcs;
foreach ( Kopete::Contact* c, csn->members() )
mcs.append ( c->metaContact() );
ExportKeys dialog ( mcs, csn->view()->mainWidget() );
dialog.exec();
}
#include "cryptographyguiclient.moc"
<|endoftext|> |
<commit_before>#include "formdeviserclass.h"
#include "ui_formdeviserclass.h"
#include <QFileDialog>
#include <QTableWidgetItem>
#include <QSortFilterProxyModel>
#include <model/deviserclass.h>
#include <model/deviserpackage.h>
#include <model/deviserattribute.h>
#include <model/deviserlistofattribute.h>
#include <model/deviserconcrete.h>
#include <ui/attributesmodel.h>
#include <ui/loattributesmodel.h>
#include <ui/concretesmodel.h>
#include <util.h>
#include <set>
FormDeviserClass::FormDeviserClass(QWidget *parent)
: QWidget(parent)
, ui(new Ui::FormDeviserClass)
, mElement(NULL)
, mpAttributes(NULL)
, mpAttributesFilter(NULL)
, mpLoAttributes(NULL)
, mpLoAttributesFilter(NULL)
, mpConcretes(NULL)
, mpConcretesFilter(NULL)
, mbInitializing(true)
{
ui->setupUi(this);
}
FormDeviserClass::~FormDeviserClass()
{
delete ui;
}
void
FormDeviserClass::initializeFrom(DeviserClass* element)
{
mElement = element;
mbInitializing = true;
ui->txtBaseClass->clear();
ui->txtDeclaration->clear();
ui->txtImplementation->clear();
ui->txtListOfClassName->clear();
ui->txtListOfName->clear();
ui->txtMaxNumChildren->clear();
ui->txtMinNumChildren->clear();
ui->txtName->clear();
ui->txtTypeCode->clear();
ui->txtXMLElementName->clear();
ui->chkHasListOf->setChecked(false);
ui->ctrlListOf->setVisible(false);
ui->grpListOfAttributes->setVisible(false);
ui->chkRequiresAdditionalCode->setChecked(false);
ui->grpAdditional->setVisible(false);
ui->chkIsBaseClass->setChecked(false);
ui->grpInstantiations->setVisible(false);
ui->tblAttributes->setModel(NULL);
if (mpAttributesFilter != NULL)
mpAttributesFilter->deleteLater();
if (mpAttributes != NULL)
mpAttributes->deleteLater();
ui->tblLoAttributes->setModel(NULL);
if (mpLoAttributesFilter != NULL)
mpLoAttributesFilter->deleteLater();
if (mpLoAttributes != NULL)
mpLoAttributes->deleteLater();
ui->tblInstantiations->setModel(NULL);
if (mpConcretesFilter != NULL)
mpConcretesFilter->deleteLater();
if (mpConcretes!= NULL)
mpConcretes->deleteLater();
if (mElement != NULL)
{
ui->txtName->setText(element->getName());
ui->txtBaseClass->setText(element->getBaseClass());
ui->txtTypeCode->setText(element->getTypeCode());
ui->txtXMLElementName->setText(element->getElementName());
ui->chkHasListOf->setChecked(
element->hasListOf() ||
!element->getListOfAttributes().empty() ||
!element->getListOfName().isEmpty() ||
!element->getListOfClassName().isEmpty() ||
element->getMaxNumberChildren() != 0 ||
element->getMinNumberChildren() != 0
);
ui->ctrlListOf->setVisible(ui->chkHasListOf->isChecked());
ui->grpListOfAttributes->setVisible(ui->chkHasListOf->isChecked());
ui->txtListOfName->setText(element->getListOfName());
ui->txtListOfClassName->setText(element->getListOfClassName());
if (element->getMinNumberChildren() != 0)
ui->txtMinNumChildren->setText(QString::number(element->getMinNumberChildren()));
if (element->getMaxNumberChildren() != 0)
ui->txtMaxNumChildren->setText(QString::number(element->getMaxNumberChildren()));
ui->txtDeclaration->setText(element->getAdditionalDeclarations());
ui->txtImplementation->setText(element->getAdditionalDefinitions());
ui->chkRequiresAdditionalCode->setChecked(!element->getAdditionalDeclarations().isEmpty() || !element->getAdditionalDefinitions().isEmpty());
ui->grpAdditional->setVisible(ui->chkRequiresAdditionalCode->isChecked());
ui->chkIsBaseClass->setChecked(element->isBaseClass() || !element->getConcretes().empty() );
ui->grpInstantiations->setVisible(ui->chkIsBaseClass->isChecked());
mpAttributesFilter = new QSortFilterProxyModel(this);
mpAttributes = new AttributesModel(this, &element->getAttributes());
mpAttributesFilter->setSourceModel(mpAttributes);
ui->tblAttributes->setModel(mpAttributesFilter);
mpLoAttributesFilter = new QSortFilterProxyModel(this);
mpLoAttributes = new LoAttributesModel(this, &element->getListOfAttributes());
mpLoAttributesFilter->setSourceModel(mpLoAttributes);
ui->tblLoAttributes->setModel(mpLoAttributesFilter);
mpConcretesFilter = new QSortFilterProxyModel(this);
mpConcretes = new ConcretesModel(this, &element->getConcretes());
mpConcretesFilter->setSourceModel(mpConcretes);
ui->tblInstantiations->setModel(mpConcretesFilter);
}
mbInitializing = false;
}
void
FormDeviserClass::browseDefinitionClick()
{
if (mElement == NULL) return;
QString fileName = QFileDialog::getOpenFileName(this, "Select Implementation file", NULL, "C++ files (*.c, *.c++, *.cpp, *.cc, *.cxx);;All files (*.*)");
mElement->setAdditionalDefinitions(fileName);
ui->txtImplementation->setText(fileName);
}
void
FormDeviserClass::browseDeclarationClick()
{
if (mElement == NULL) return;
QString fileName = QFileDialog::getOpenFileName(this, "Select Declaration file", NULL, "Header files (*.h, *.h++, *.hpp, *.hh, *.hxx);;All files (*.*)");
mElement->setAdditionalDeclarations(fileName);
ui->txtDeclaration->setText(fileName);
}
void
FormDeviserClass::delConcrete()
{
const QModelIndexList& list = ui->tblInstantiations->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpConcretes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::delListOfAttribute()
{
const QModelIndexList& list = ui->tblLoAttributes->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpLoAttributes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::delAttribute()
{
const QModelIndexList& list = ui->tblAttributes->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpAttributes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::addListOfAttribute()
{
if (mElement == NULL) return;
mpLoAttributes->beginAdding();
mElement->createListOfAttribute();
mpLoAttributes->endAdding();
}
void
FormDeviserClass::addConcrete()
{
if (mElement == NULL) return;
mpConcretes->beginAdding();
mElement->createConcrete();
mpConcretes->endAdding();
}
void
FormDeviserClass::addAttribute()
{
if (mElement == NULL) return;
mpAttributes->beginAdding();
mElement->createAttribute();
mpAttributes->endAdding();
}
void
FormDeviserClass::xmlElementNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setElementName(ui->txtXMLElementName->text());
}
void
FormDeviserClass::typeCodeChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setTypeCode(ui->txtTypeCode->text());
}
void
FormDeviserClass::nameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setName(ui->txtName->text());
}
void
FormDeviserClass::minNoChildrenChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setMinNumberChildren(ui->txtMinNumChildren->text().toInt());
}
void
FormDeviserClass::maxNoChildrenChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setMaxNumberChildren(ui->txtMaxNumChildren->text().toInt());
}
void
FormDeviserClass::listOfNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setListOfName(ui->txtListOfName->text());
}
void
FormDeviserClass::listOfClassNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setListOfClassName(ui->txtListOfClassName->text());
}
void
FormDeviserClass::definitionChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setAdditionalDefinitions(ui->txtImplementation->text());
}
void
FormDeviserClass::declarationChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setAdditionalDeclarations(ui->txtDeclaration->text());
}
void
FormDeviserClass::baseClassChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setBaseClass(ui->txtBaseClass->text());
}
void
FormDeviserClass::requiresStateChanged(int)
{
ui->grpAdditional->setVisible(ui->chkRequiresAdditionalCode->isChecked());
}
void
FormDeviserClass::isBaseClassStateChanged(int)
{
if (mElement == NULL || mbInitializing) return;
mElement->setIsBaseClass(ui->chkIsBaseClass->isChecked());
ui->grpInstantiations->setVisible(ui->chkIsBaseClass->isChecked());
}
void
FormDeviserClass::hasListOfStateChanged(int)
{
if (mElement == NULL || mbInitializing) return;
mElement->setHasListOf(ui->chkHasListOf->isChecked());
ui->ctrlListOf->setVisible(ui->chkHasListOf->isChecked());
ui->grpListOfAttributes->setVisible(ui->chkHasListOf->isChecked());
}
void FormDeviserClass::defaultXmlElementName()
{
if (ui->txtName->text().isEmpty()) return;
ui->txtXMLElementName->setText(Util::lowerFirst(ui->txtName->text()));
}
void FormDeviserClass::defaultTypeCode()
{
if (ui->txtName->text().isEmpty()) return;
if (mElement == NULL || mElement->getParent() == NULL || mElement->getParent()->getName().isEmpty())
return;
ui->txtTypeCode->setText(QString("SBML_%1_%2")
.arg(mElement->getParent()->getName().toUpper())
.arg(ui->txtName->text().toUpper()));
}
void FormDeviserClass::defaultListOfName()
{
if (ui->txtName->text().isEmpty()) return;
ui->txtListOfName->setText(QString("listOf%1")
.arg(Util::upperFirst(Util::guessPlural(ui->txtName->text()))));
}
void FormDeviserClass::defaultBaseClass()
{
if (mElement == NULL || mElement->getParent() == NULL || mElement->getParent()->getLanguage().baseClass().isEmpty())
{
ui->txtBaseClass->setText("SBase");
return;
}
ui->txtBaseClass->setText(mElement->getParent()->getLanguage().baseClass());
}
void FormDeviserClass::defaultListOfClassName()
{
if (ui->txtName->text().isEmpty()) return;
ui->txtListOfClassName->setText(Util::upperFirst( QString("listOf%1")
.arg(Util::upperFirst(Util::guessPlural(ui->txtName->text())))));
}
<commit_msg>- ensure that default values are written out<commit_after>#include "formdeviserclass.h"
#include "ui_formdeviserclass.h"
#include <QFileDialog>
#include <QTableWidgetItem>
#include <QSortFilterProxyModel>
#include <model/deviserclass.h>
#include <model/deviserpackage.h>
#include <model/deviserattribute.h>
#include <model/deviserlistofattribute.h>
#include <model/deviserconcrete.h>
#include <ui/attributesmodel.h>
#include <ui/loattributesmodel.h>
#include <ui/concretesmodel.h>
#include <util.h>
#include <set>
FormDeviserClass::FormDeviserClass(QWidget *parent)
: QWidget(parent)
, ui(new Ui::FormDeviserClass)
, mElement(NULL)
, mpAttributes(NULL)
, mpAttributesFilter(NULL)
, mpLoAttributes(NULL)
, mpLoAttributesFilter(NULL)
, mpConcretes(NULL)
, mpConcretesFilter(NULL)
, mbInitializing(true)
{
ui->setupUi(this);
}
FormDeviserClass::~FormDeviserClass()
{
delete ui;
}
void
FormDeviserClass::initializeFrom(DeviserClass* element)
{
mElement = element;
mbInitializing = true;
ui->txtBaseClass->clear();
ui->txtDeclaration->clear();
ui->txtImplementation->clear();
ui->txtListOfClassName->clear();
ui->txtListOfName->clear();
ui->txtMaxNumChildren->clear();
ui->txtMinNumChildren->clear();
ui->txtName->clear();
ui->txtTypeCode->clear();
ui->txtXMLElementName->clear();
ui->chkHasListOf->setChecked(false);
ui->ctrlListOf->setVisible(false);
ui->grpListOfAttributes->setVisible(false);
ui->chkRequiresAdditionalCode->setChecked(false);
ui->grpAdditional->setVisible(false);
ui->chkIsBaseClass->setChecked(false);
ui->grpInstantiations->setVisible(false);
ui->tblAttributes->setModel(NULL);
if (mpAttributesFilter != NULL)
mpAttributesFilter->deleteLater();
if (mpAttributes != NULL)
mpAttributes->deleteLater();
ui->tblLoAttributes->setModel(NULL);
if (mpLoAttributesFilter != NULL)
mpLoAttributesFilter->deleteLater();
if (mpLoAttributes != NULL)
mpLoAttributes->deleteLater();
ui->tblInstantiations->setModel(NULL);
if (mpConcretesFilter != NULL)
mpConcretesFilter->deleteLater();
if (mpConcretes!= NULL)
mpConcretes->deleteLater();
if (mElement != NULL)
{
ui->txtName->setText(element->getName());
ui->txtBaseClass->setText(element->getBaseClass());
ui->txtTypeCode->setText(element->getTypeCode());
ui->txtXMLElementName->setText(element->getElementName());
ui->chkHasListOf->setChecked(
element->hasListOf() ||
!element->getListOfAttributes().empty() ||
!element->getListOfName().isEmpty() ||
!element->getListOfClassName().isEmpty() ||
element->getMaxNumberChildren() != 0 ||
element->getMinNumberChildren() != 0
);
ui->ctrlListOf->setVisible(ui->chkHasListOf->isChecked());
ui->grpListOfAttributes->setVisible(ui->chkHasListOf->isChecked());
ui->txtListOfName->setText(element->getListOfName());
ui->txtListOfClassName->setText(element->getListOfClassName());
if (element->getMinNumberChildren() != 0)
ui->txtMinNumChildren->setText(QString::number(element->getMinNumberChildren()));
if (element->getMaxNumberChildren() != 0)
ui->txtMaxNumChildren->setText(QString::number(element->getMaxNumberChildren()));
ui->txtDeclaration->setText(element->getAdditionalDeclarations());
ui->txtImplementation->setText(element->getAdditionalDefinitions());
ui->chkRequiresAdditionalCode->setChecked(!element->getAdditionalDeclarations().isEmpty() || !element->getAdditionalDefinitions().isEmpty());
ui->grpAdditional->setVisible(ui->chkRequiresAdditionalCode->isChecked());
ui->chkIsBaseClass->setChecked(element->isBaseClass() || !element->getConcretes().empty() );
ui->grpInstantiations->setVisible(ui->chkIsBaseClass->isChecked());
mpAttributesFilter = new QSortFilterProxyModel(this);
mpAttributes = new AttributesModel(this, &element->getAttributes());
mpAttributesFilter->setSourceModel(mpAttributes);
ui->tblAttributes->setModel(mpAttributesFilter);
mpLoAttributesFilter = new QSortFilterProxyModel(this);
mpLoAttributes = new LoAttributesModel(this, &element->getListOfAttributes());
mpLoAttributesFilter->setSourceModel(mpLoAttributes);
ui->tblLoAttributes->setModel(mpLoAttributesFilter);
mpConcretesFilter = new QSortFilterProxyModel(this);
mpConcretes = new ConcretesModel(this, &element->getConcretes());
mpConcretesFilter->setSourceModel(mpConcretes);
ui->tblInstantiations->setModel(mpConcretesFilter);
}
mbInitializing = false;
}
void
FormDeviserClass::browseDefinitionClick()
{
if (mElement == NULL) return;
QString fileName = QFileDialog::getOpenFileName(this, "Select Implementation file", NULL, "C++ files (*.c, *.c++, *.cpp, *.cc, *.cxx);;All files (*.*)");
mElement->setAdditionalDefinitions(fileName);
ui->txtImplementation->setText(fileName);
}
void
FormDeviserClass::browseDeclarationClick()
{
if (mElement == NULL) return;
QString fileName = QFileDialog::getOpenFileName(this, "Select Declaration file", NULL, "Header files (*.h, *.h++, *.hpp, *.hh, *.hxx);;All files (*.*)");
mElement->setAdditionalDeclarations(fileName);
ui->txtDeclaration->setText(fileName);
}
void
FormDeviserClass::delConcrete()
{
const QModelIndexList& list = ui->tblInstantiations->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpConcretes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::delListOfAttribute()
{
const QModelIndexList& list = ui->tblLoAttributes->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpLoAttributes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::delAttribute()
{
const QModelIndexList& list = ui->tblAttributes->selectionModel()->selectedIndexes();
if (list.count() == 0) return;
std::set<int> rows;
foreach(const QModelIndex& index, list)
{
rows.insert(index.row());
}
std::set<int>::reverse_iterator it = rows.rbegin();
while (it != rows.rend())
{
mpAttributes->removeAttribute(*it);
++it;
}
}
void
FormDeviserClass::addListOfAttribute()
{
if (mElement == NULL) return;
mpLoAttributes->beginAdding();
mElement->createListOfAttribute();
mpLoAttributes->endAdding();
}
void
FormDeviserClass::addConcrete()
{
if (mElement == NULL) return;
mpConcretes->beginAdding();
mElement->createConcrete();
mpConcretes->endAdding();
}
void
FormDeviserClass::addAttribute()
{
if (mElement == NULL) return;
mpAttributes->beginAdding();
mElement->createAttribute();
mpAttributes->endAdding();
}
void
FormDeviserClass::xmlElementNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setElementName(ui->txtXMLElementName->text());
}
void
FormDeviserClass::typeCodeChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setTypeCode(ui->txtTypeCode->text());
}
void
FormDeviserClass::nameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setName(ui->txtName->text());
}
void
FormDeviserClass::minNoChildrenChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setMinNumberChildren(ui->txtMinNumChildren->text().toInt());
}
void
FormDeviserClass::maxNoChildrenChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setMaxNumberChildren(ui->txtMaxNumChildren->text().toInt());
}
void
FormDeviserClass::listOfNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setListOfName(ui->txtListOfName->text());
}
void
FormDeviserClass::listOfClassNameChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setListOfClassName(ui->txtListOfClassName->text());
}
void
FormDeviserClass::definitionChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setAdditionalDefinitions(ui->txtImplementation->text());
}
void
FormDeviserClass::declarationChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setAdditionalDeclarations(ui->txtDeclaration->text());
}
void
FormDeviserClass::baseClassChanged(const QString&)
{
if (mElement == NULL || mbInitializing) return;
mElement->setBaseClass(ui->txtBaseClass->text());
}
void
FormDeviserClass::requiresStateChanged(int)
{
ui->grpAdditional->setVisible(ui->chkRequiresAdditionalCode->isChecked());
}
void
FormDeviserClass::isBaseClassStateChanged(int)
{
if (mElement == NULL || mbInitializing) return;
mElement->setIsBaseClass(ui->chkIsBaseClass->isChecked());
ui->grpInstantiations->setVisible(ui->chkIsBaseClass->isChecked());
}
void
FormDeviserClass::hasListOfStateChanged(int)
{
if (mElement == NULL || mbInitializing) return;
mElement->setHasListOf(ui->chkHasListOf->isChecked());
ui->ctrlListOf->setVisible(ui->chkHasListOf->isChecked());
ui->grpListOfAttributes->setVisible(ui->chkHasListOf->isChecked());
}
void FormDeviserClass::defaultXmlElementName()
{
if (ui->txtName->text().isEmpty()) return;
QString newXmlElementName = Util::lowerFirst(ui->txtName->text());
ui->txtXMLElementName->setText(newXmlElementName);
xmlElementNameChanged(newXmlElementName);
}
void FormDeviserClass::defaultTypeCode()
{
if (ui->txtName->text().isEmpty()) return;
if (mElement == NULL || mElement->getParent() == NULL || mElement->getParent()->getName().isEmpty())
return;
QString newTypeCode = QString("SBML_%1_%2")
.arg(mElement->getParent()->getName().toUpper())
.arg(ui->txtName->text().toUpper()) ;
ui->txtTypeCode->setText(newTypeCode);
typeCodeChanged(newTypeCode);
}
void FormDeviserClass::defaultListOfName()
{
if (ui->txtName->text().isEmpty()) return;
QString newListOfName = QString("listOf%1")
.arg(Util::upperFirst(Util::guessPlural(ui->txtName->text())));
ui->txtListOfName->setText(newListOfName);
listOfNameChanged(newListOfName);
}
void FormDeviserClass::defaultBaseClass()
{
QString newBaseClass;
if (mElement == NULL || mElement->getParent() == NULL || mElement->getParent()->getLanguage().baseClass().isEmpty())
{
newBaseClass = "SBase";
}
else
{
newBaseClass = mElement->getParent()->getLanguage().baseClass();
}
ui->txtBaseClass->setText(newBaseClass);
baseClassChanged(newBaseClass);
}
void FormDeviserClass::defaultListOfClassName()
{
if (ui->txtName->text().isEmpty()) return;
QString newListOfClassName = Util::upperFirst( QString("listOf%1")
.arg(Util::upperFirst(Util::guessPlural(ui->txtName->text()))));
ui->txtListOfClassName->setText(newListOfClassName);
listOfClassNameChanged(newListOfClassName);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 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/gl/vsync_provider.h"
#include "base/logging.h"
#include "base/time.h"
namespace {
// These constants define a reasonable range for a calculated refresh interval.
// Calculating refreshes out of this range will be considered a fatal error.
const int64 kMinVsyncIntervalUs = base::Time::kMicrosecondsPerSecond / 400;
const int64 kMaxVsyncIntervalUs = base::Time::kMicrosecondsPerSecond / 10;
} // namespace
namespace gfx {
VSyncProvider::VSyncProvider() {
}
VSyncProvider::~VSyncProvider() {
}
SyncControlVSyncProvider::SyncControlVSyncProvider()
: VSyncProvider(),
last_media_stream_counter_(0) {
// On platforms where we can't get an accurate reading on the refresh
// rate we fall back to the assumption that we're displaying 60 frames
// per second.
last_good_interval_ = base::TimeDelta::FromSeconds(1) / 60;
}
SyncControlVSyncProvider::~SyncControlVSyncProvider() {
}
void SyncControlVSyncProvider::GetVSyncParameters(
const UpdateVSyncCallback& callback) {
#if defined(OS_LINUX)
base::TimeTicks timebase;
// The actual clock used for the system time returned by glXGetSyncValuesOML
// is unspecified. In practice, the clock used is likely to be either
// CLOCK_REALTIME or CLOCK_MONOTONIC, so we compare the returned time to the
// current time according to both clocks, and assume that the returned time
// was produced by the clock whose current time is closest to it, subject
// to the restriction that the returned time must not be in the future
// (since it is the time of a vblank that has already occurred).
int64 system_time;
int64 media_stream_counter;
int64 swap_buffer_counter;
if (!GetSyncValues(&system_time,
&media_stream_counter,
&swap_buffer_counter))
return;
struct timespec real_time;
struct timespec monotonic_time;
clock_gettime(CLOCK_REALTIME, &real_time);
clock_gettime(CLOCK_MONOTONIC, &monotonic_time);
int64 real_time_in_microseconds =
real_time.tv_sec * base::Time::kMicrosecondsPerSecond +
real_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
int64 monotonic_time_in_microseconds =
monotonic_time.tv_sec * base::Time::kMicrosecondsPerSecond +
monotonic_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
// We need the time according to CLOCK_MONOTONIC, so if we've been given
// a time from CLOCK_REALTIME, we need to convert.
bool time_conversion_needed =
llabs(system_time - real_time_in_microseconds) <
llabs(system_time - monotonic_time_in_microseconds);
if (time_conversion_needed)
system_time += monotonic_time_in_microseconds - real_time_in_microseconds;
// Return if |system_time| is more than 1 frames in the future.
int64 interval_in_microseconds = last_good_interval_.InMicroseconds();
if (system_time > monotonic_time_in_microseconds + interval_in_microseconds)
return;
// If |system_time| is slightly in the future, adjust it to the previous
// frame and use the last frame counter to prevent issues in the callback.
if (system_time > monotonic_time_in_microseconds) {
system_time -= interval_in_microseconds;
media_stream_counter--;
}
timebase = base::TimeTicks::FromInternalValue(system_time);
int32 numerator, denominator;
if (GetMscRate(&numerator, &denominator)) {
last_good_interval_ =
base::TimeDelta::FromSeconds(denominator) / numerator;
} else if (!last_timebase_.is_null()) {
base::TimeDelta timebase_diff = timebase - last_timebase_;
uint64 counter_diff = media_stream_counter -
last_media_stream_counter_;
if (counter_diff > 0 && timebase > last_timebase_)
last_good_interval_ = timebase_diff / counter_diff;
}
if (last_good_interval_.InMicroseconds() < kMinVsyncIntervalUs ||
last_good_interval_.InMicroseconds() > kMaxVsyncIntervalUs) {
LOG(FATAL) << "Calculated bogus refresh interval of "
<< last_good_interval_.InMicroseconds() << " us. "
<< "Last time base of "
<< last_timebase_.ToInternalValue() << " us. "
<< "Current time base of "
<< timebase.ToInternalValue() << " us. "
<< "Last media stream count of "
<< last_media_stream_counter_ << ". "
<< "Current media stream count of "
<< media_stream_counter << ".";
}
last_timebase_ = timebase;
last_media_stream_counter_ = media_stream_counter;
callback.Run(timebase, last_good_interval_);
#endif // defined(OS_LINUX)
}
} // namespace gfx
<commit_msg>CrOS: Sanitize driver values from GLX_OML_sync_control<commit_after>// Copyright (c) 2013 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/gl/vsync_provider.h"
#include "base/logging.h"
#include "base/time.h"
namespace {
// These constants define a reasonable range for a calculated refresh interval.
// Calculating refreshes out of this range will be considered a fatal error.
const int64 kMinVsyncIntervalUs = base::Time::kMicrosecondsPerSecond / 400;
const int64 kMaxVsyncIntervalUs = base::Time::kMicrosecondsPerSecond / 10;
} // namespace
namespace gfx {
VSyncProvider::VSyncProvider() {
}
VSyncProvider::~VSyncProvider() {
}
SyncControlVSyncProvider::SyncControlVSyncProvider()
: VSyncProvider(),
last_media_stream_counter_(0) {
// On platforms where we can't get an accurate reading on the refresh
// rate we fall back to the assumption that we're displaying 60 frames
// per second.
last_good_interval_ = base::TimeDelta::FromSeconds(1) / 60;
}
SyncControlVSyncProvider::~SyncControlVSyncProvider() {
}
void SyncControlVSyncProvider::GetVSyncParameters(
const UpdateVSyncCallback& callback) {
#if defined(OS_LINUX)
base::TimeTicks timebase;
// The actual clock used for the system time returned by glXGetSyncValuesOML
// is unspecified. In practice, the clock used is likely to be either
// CLOCK_REALTIME or CLOCK_MONOTONIC, so we compare the returned time to the
// current time according to both clocks, and assume that the returned time
// was produced by the clock whose current time is closest to it, subject
// to the restriction that the returned time must not be in the future
// (since it is the time of a vblank that has already occurred).
int64 system_time;
int64 media_stream_counter;
int64 swap_buffer_counter;
if (!GetSyncValues(&system_time,
&media_stream_counter,
&swap_buffer_counter))
return;
struct timespec real_time;
struct timespec monotonic_time;
clock_gettime(CLOCK_REALTIME, &real_time);
clock_gettime(CLOCK_MONOTONIC, &monotonic_time);
int64 real_time_in_microseconds =
real_time.tv_sec * base::Time::kMicrosecondsPerSecond +
real_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
int64 monotonic_time_in_microseconds =
monotonic_time.tv_sec * base::Time::kMicrosecondsPerSecond +
monotonic_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
// We need the time according to CLOCK_MONOTONIC, so if we've been given
// a time from CLOCK_REALTIME, we need to convert.
bool time_conversion_needed =
llabs(system_time - real_time_in_microseconds) <
llabs(system_time - monotonic_time_in_microseconds);
if (time_conversion_needed)
system_time += monotonic_time_in_microseconds - real_time_in_microseconds;
// Return if |system_time| is more than 1 frames in the future.
int64 interval_in_microseconds = last_good_interval_.InMicroseconds();
if (system_time > monotonic_time_in_microseconds + interval_in_microseconds)
return;
// If |system_time| is slightly in the future, adjust it to the previous
// frame and use the last frame counter to prevent issues in the callback.
if (system_time > monotonic_time_in_microseconds) {
system_time -= interval_in_microseconds;
media_stream_counter--;
}
if (monotonic_time_in_microseconds - system_time >
base::Time::kMicrosecondsPerSecond)
return;
timebase = base::TimeTicks::FromInternalValue(system_time);
int32 numerator, denominator;
base::TimeDelta new_interval;
if (GetMscRate(&numerator, &denominator)) {
new_interval =
base::TimeDelta::FromSeconds(denominator) / numerator;
} else if (!last_timebase_.is_null()) {
base::TimeDelta timebase_diff = timebase - last_timebase_;
uint64 counter_diff = media_stream_counter -
last_media_stream_counter_;
if (counter_diff > 0 && timebase > last_timebase_)
new_interval = timebase_diff / counter_diff;
}
if (new_interval.InMicroseconds() < kMinVsyncIntervalUs ||
new_interval.InMicroseconds() > kMaxVsyncIntervalUs) {
LOG(ERROR) << "Calculated bogus refresh interval of "
<< new_interval.InMicroseconds() << " us. "
<< "Last time base of "
<< last_timebase_.ToInternalValue() << " us. "
<< "Current time base of "
<< timebase.ToInternalValue() << " us. "
<< "Last media stream count of "
<< last_media_stream_counter_ << ". "
<< "Current media stream count of "
<< media_stream_counter << ".";
} else {
last_good_interval_ = new_interval;
}
last_timebase_ = timebase;
last_media_stream_counter_ = media_stream_counter;
callback.Run(timebase, last_good_interval_);
#endif // defined(OS_LINUX)
}
} // namespace gfx
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $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 "waylandcompositor.h"
#include "waylandsurface.h"
#include "waylandsurfaceitem.h"
#include <QGuiApplication>
#include <QTimer>
#include <QPainter>
#include <QMouseEvent>
#include <QQmlContext>
#include <QQuickItem>
#include <QQuickView>
class QmlCompositor : public QQuickView, public WaylandCompositor
{
Q_OBJECT
public:
QmlCompositor()
: WaylandCompositor(this)
{
enableSubSurfaceExtension();
setSource(QUrl(QLatin1String("qrc:qml/QmlCompositor/main.qml")));
setResizeMode(QQuickView::SizeRootObjectToView);
winId();
connect(this, SIGNAL(frameSwapped()), this, SLOT(frameSwappedSlot()));
}
signals:
void windowAdded(QVariant window);
void windowDestroyed(QVariant window);
void windowResized(QVariant window);
public slots:
void destroyWindow(QVariant window) {
qvariant_cast<QObject *>(window)->deleteLater();
}
private slots:
void surfaceMapped() {
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
WaylandSurfaceItem *item = surface->surfaceItem();
item->takeFocus();
emit windowAdded(QVariant::fromValue(static_cast<QQuickItem *>(item)));
}
void surfaceUnmapped() {
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
QQuickItem *item = surface->surfaceItem();
emit windowDestroyed(QVariant::fromValue(item));
}
void surfaceDestroyed(QObject *object) {
WaylandSurface *surface = static_cast<WaylandSurface *>(object);
QQuickItem *item = surface->surfaceItem();
emit windowDestroyed(QVariant::fromValue(item));
}
void frameSwappedSlot() {
frameFinished();
}
protected:
void resizeEvent(QResizeEvent *)
{
WaylandCompositor::setOutputGeometry(QRect(0, 0, width(), height()));
}
void surfaceCreated(WaylandSurface *surface) {
WaylandSurfaceItem *item = new WaylandSurfaceItem(surface, rootObject());
item->setTouchEventsEnabled(true);
connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
connect(surface,SIGNAL(unmapped()), this,SLOT(surfaceUnmapped()));
}
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QmlCompositor compositor;
compositor.setWindowTitle(QLatin1String("QML Compositor"));
compositor.show();
compositor.rootContext()->setContextProperty("compositor", &compositor);
QObject::connect(&compositor, SIGNAL(windowAdded(QVariant)), compositor.rootObject(), SLOT(windowAdded(QVariant)));
QObject::connect(&compositor, SIGNAL(windowDestroyed(QVariant)), compositor.rootObject(), SLOT(windowDestroyed(QVariant)));
QObject::connect(&compositor, SIGNAL(windowResized(QVariant)), compositor.rootObject(), SLOT(windowResized(QVariant)));
return app.exec();
}
#include "main.moc"
<commit_msg>Make qml compositor resize to window<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $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 "waylandcompositor.h"
#include "waylandsurface.h"
#include "waylandsurfaceitem.h"
#include <QGuiApplication>
#include <QTimer>
#include <QPainter>
#include <QMouseEvent>
#include <QQmlContext>
#include <QQuickItem>
#include <QQuickView>
class QmlCompositor : public QQuickView, public WaylandCompositor
{
Q_OBJECT
public:
QmlCompositor()
: WaylandCompositor(this)
{
enableSubSurfaceExtension();
setSource(QUrl(QLatin1String("qrc:qml/QmlCompositor/main.qml")));
setResizeMode(QQuickView::SizeRootObjectToView);
winId();
connect(this, SIGNAL(frameSwapped()), this, SLOT(frameSwappedSlot()));
}
signals:
void windowAdded(QVariant window);
void windowDestroyed(QVariant window);
void windowResized(QVariant window);
public slots:
void destroyWindow(QVariant window) {
qvariant_cast<QObject *>(window)->deleteLater();
}
private slots:
void surfaceMapped() {
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
WaylandSurfaceItem *item = surface->surfaceItem();
item->takeFocus();
emit windowAdded(QVariant::fromValue(static_cast<QQuickItem *>(item)));
}
void surfaceUnmapped() {
WaylandSurface *surface = qobject_cast<WaylandSurface *>(sender());
QQuickItem *item = surface->surfaceItem();
emit windowDestroyed(QVariant::fromValue(item));
}
void surfaceDestroyed(QObject *object) {
WaylandSurface *surface = static_cast<WaylandSurface *>(object);
QQuickItem *item = surface->surfaceItem();
emit windowDestroyed(QVariant::fromValue(item));
}
void frameSwappedSlot() {
frameFinished();
}
protected:
void resizeEvent(QResizeEvent *event)
{
QQuickView::resizeEvent(event);
WaylandCompositor::setOutputGeometry(QRect(0, 0, width(), height()));
}
void surfaceCreated(WaylandSurface *surface) {
WaylandSurfaceItem *item = new WaylandSurfaceItem(surface, rootObject());
item->setTouchEventsEnabled(true);
connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
connect(surface,SIGNAL(unmapped()), this,SLOT(surfaceUnmapped()));
}
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QmlCompositor compositor;
compositor.setWindowTitle(QLatin1String("QML Compositor"));
compositor.show();
compositor.rootContext()->setContextProperty("compositor", &compositor);
QObject::connect(&compositor, SIGNAL(windowAdded(QVariant)), compositor.rootObject(), SLOT(windowAdded(QVariant)));
QObject::connect(&compositor, SIGNAL(windowDestroyed(QVariant)), compositor.rootObject(), SLOT(windowDestroyed(QVariant)));
QObject::connect(&compositor, SIGNAL(windowResized(QVariant)), compositor.rootObject(), SLOT(windowResized(QVariant)));
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>
#include "gps.hpp"
#include "nmea.hpp"
#include "backtrace.hpp"
#include <iostream>
gps::gps() : running(false), gps_port(io_service), queue_len(50)
{
}
gps::~gps()
{
stop();
}
void gps::start()
{
running = true;
iothread = boost::thread(boost::bind(&gps::gps_comm, this));
}
void gps::stop()
{
running = false;
iothread.join();
}
bool gps::get_last_state(GPSState& state)
{
boost::mutex::scoped_lock lock(state_queue_mutex);
if(state_queue.empty())
{
std::cerr << "GPS queue empty!" << std::endl;
return false;
}
struct timeval now;
gettimeofday(&now, NULL);
time_t secDelta = difftime(now.tv_sec, state_queue.back().laptoptime.tv_sec);
suseconds_t usecDelta = now.tv_usec - state_queue.back().laptoptime.tv_usec;
double delta = double(secDelta) + 1e-6*double(usecDelta);
if(delta > .5)
{
std::cerr << "GPS Marker Out Of Date!" << std::endl;
return false;
}
if( (state_queue.back().qual != GPS_QUALITY_NON_DIFF) && (state_queue.back().qual != GPS_QUALITY_WAAS))
{
std::cerr << "GPS state bad - " << int(state_queue.back().qual) << std::endl;
return false;
}
state = state_queue.back();
return true;
}
bool gps::get_speed(double& speed)
{
GPSState state;
if(get_last_state(state))
{
speed = state.speedoverground;
return true;
}
return false;
}
bool gps::get_heading(double& heading)
{
GPSState state;
if(get_last_state(state))
{
heading = state.courseoverground;
return true;
}
return false;
}
bool gps::open(const char* port, size_t baud)
{
m_port = port;
m_baud = baud;
try
{
gps_port.open(port);
}
catch(...)
{
std::cerr << "Failed to open serial port" << std::endl;
stacktrace();
return false;
}
if(!gps_port.is_open())
{
return false;
}
try
{
gps_port.set_option(boost::asio::serial_port_base::baud_rate(baud));
//gps_port.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
gps_port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
gps_port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
}
catch(...)
{
return false;
}
m_connected = true;
return true;
}
void gps::close()
{
gps_port.close();
m_connected = false;
}
void gps::handle_serial_read_timer(const boost::system::error_code& ec)
{
if(ec)
{
return;
}
std::cerr << "Serial Timout" << std::endl;
{
boost::mutex::scoped_lock lock(state_queue_mutex);
state_queue.clear();
}
gps_port.cancel();
reconnect();
}
void gps::handle_serial_read(const boost::system::error_code& ec, size_t len, boost::asio::deadline_timer& timeout)
{
if(ec || (len == 0))
{
return;
}
timeout.cancel();//data rec, kill the timer
std::string line;
try
{
std::istream is(&comm_buffer);
std::getline(is, line);
}
catch(...)
{
std::cerr << "Error parsing GPS packet!" << std::endl;
return;
}
try
{
GPSState state;
//if(nmea::decodeGPGGA(line, state))
if(nmea::decodeGPRMC(line, state))
{
gettimeofday(&state.laptoptime, NULL);
boost::mutex::scoped_lock lock(state_queue_mutex);
state_queue.push_back(state);
if(state_queue.size() > queue_len)
{
state_queue.pop_front();
}
}
}
catch(...)
{
std::cerr << "Error parsing GPS packet!" << std::endl;
}
}
void gps::gps_comm()
{
while(running)
{
boost::asio::deadline_timer timeout(io_service);
timeout.expires_from_now(boost::posix_time::milliseconds(2e3));
try
{
boost::asio::async_read_until(gps_port, comm_buffer, '\n', boost::bind(&gps::handle_serial_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(timeout)));
timeout.async_wait(boost::bind(&gps::handle_serial_read_timer, this, boost::asio::placeholders::error));
io_service.run();
io_service.reset();
}
catch(...)
{
reconnect();
}
}
}
void gps::reconnect()
{
close();
usleep(1e6);
open(m_port.c_str(), m_baud);
}
bool gps::parse_message(const std::string& line, GPSState& state)
{
if(nmea::decodeGPGGA(line, state))
{
return true;
}
if(nmea::decodeGPRMC(line, state))
{
return true;
}
if(nmea::decodeGPRMT(line))
{
return true;
}
if(nmea::decodeGPGSA(line))
{
return true;
}
if(nmea::decodeGPGSV(line))
{
return true;
}
return false;
}
<commit_msg>improve gps slightly<commit_after>
#include "gps.hpp"
#include "nmea.hpp"
#include "backtrace.hpp"
#include <iostream>
gps::gps() : running(false), gps_port(io_service), queue_len(50)
{
}
gps::~gps()
{
stop();
}
void gps::start()
{
running = true;
iothread = boost::thread(boost::bind(&gps::gps_comm, this));
}
void gps::stop()
{
running = false;
iothread.join();
}
bool gps::get_last_state(GPSState& state)
{
boost::mutex::scoped_lock lock(state_queue_mutex);
if(state_queue.empty())
{
std::cerr << "GPS queue empty!" << std::endl;
return false;
}
struct timeval now;
gettimeofday(&now, NULL);
time_t secDelta = difftime(now.tv_sec, state_queue.back().laptoptime.tv_sec);
suseconds_t usecDelta = now.tv_usec - state_queue.back().laptoptime.tv_usec;
double delta = double(secDelta) + 1e-6*double(usecDelta);
if(delta > .5)
{
std::cerr << "GPS Marker Out Of Date!" << std::endl;
//return false;//if we want it to be fatal HACK
}
if( (state_queue.back().qual != GPS_QUALITY_NON_DIFF) && (state_queue.back().qual != GPS_QUALITY_WAAS))
{
std::cerr << "GPS state bad - " << int(state_queue.back().qual) << std::endl;
//return false;//if we want it to be fatal HACK
}
state = state_queue.back();
return true;
}
bool gps::get_speed(double& speed)
{
GPSState state;
if(get_last_state(state))
{
speed = state.speedoverground;
return true;
}
return false;
}
bool gps::get_heading(double& heading)
{
GPSState state;
if(get_last_state(state))
{
heading = state.courseoverground;
return true;
}
return false;
}
bool gps::open(const char* port, size_t baud)
{
m_port = port;
m_baud = baud;
try
{
gps_port.open(port);
}
catch(...)
{
std::cerr << "Failed to open serial port" << std::endl;
stacktrace();
return false;
}
if(!gps_port.is_open())
{
return false;
}
try
{
gps_port.set_option(boost::asio::serial_port_base::baud_rate(baud));
//gps_port.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));
gps_port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
gps_port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
}
catch(...)
{
return false;
}
m_connected = true;
return true;
}
void gps::close()
{
gps_port.close();
m_connected = false;
}
void gps::handle_serial_read_timer(const boost::system::error_code& ec)
{
if(ec)
{
return;
}
std::cerr << "Serial Timout" << std::endl;
{
boost::mutex::scoped_lock lock(state_queue_mutex);
state_queue.clear();
}
gps_port.cancel();
reconnect();
}
void gps::handle_serial_read(const boost::system::error_code& ec, size_t len, boost::asio::deadline_timer& timeout)
{
if(ec || (len == 0))
{
return;
}
timeout.cancel();//data rec, kill the timer
std::string line;
try
{
std::istream is(&comm_buffer);
std::getline(is, line);
}
catch(...)
{
std::cerr << "Error parsing GPS packet!" << std::endl;
return;
}
try
{
GPSState state;
//if(nmea::decodeGPGGA(line, state))
//if(nmea::decodeGPRMC(line, state))
if(gps::parse_message(line, state))
{
gettimeofday(&state.laptoptime, NULL);
boost::mutex::scoped_lock lock(state_queue_mutex);
state_queue.push_back(state);
if(state_queue.size() > queue_len)
{
state_queue.pop_front();
}
}
}
catch(...)
{
std::cerr << "Error parsing GPS packet!" << std::endl;
}
}
void gps::gps_comm()
{
while(running)
{
boost::asio::deadline_timer timeout(io_service);
timeout.expires_from_now(boost::posix_time::milliseconds(2e3));
try
{
boost::asio::async_read_until(gps_port, comm_buffer, '\n', boost::bind(&gps::handle_serial_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(timeout)));
timeout.async_wait(boost::bind(&gps::handle_serial_read_timer, this, boost::asio::placeholders::error));
io_service.run();
io_service.reset();
}
catch(...)
{
reconnect();
}
}
}
void gps::reconnect()
{
close();
usleep(1e6);
open(m_port.c_str(), m_baud);
}
bool gps::parse_message(const std::string& line, GPSState& state)
{
if(nmea::decodeGPGGA(line, state))
{
return true;
}
if(nmea::decodeGPRMC(line, state))
{
return true;
}
if(nmea::decodeGPRMT(line))
{
return true;
}
if(nmea::decodeGPGSA(line))
{
return true;
}
if(nmea::decodeGPGSV(line))
{
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
typedef pair<int, int> path;
void encode() {
int N, M;
cin >> N >> M;
bool pass[110][110];
fill(&pass[0][0], &pass[0][0]+110*110, false);
int a[110], b[110];
for (auto i = 0; i < M; ++i) {
cin >> a[i] >> b[i];
a[i]--;
b[i]--;
pass[a[i]][b[i]] = true;
pass[b[i]][a[i]] = true;
}
vector<int> V[110];
for (auto i = 0; i < N; ++i) {
for (auto j = 0; j < N; ++j) {
if (i == j) continue;
if (!pass[i][j]) {
V[i].push_back(j);
}
}
}
ll X;
cin >> X;
bool bit[62];
bool isone = true;
fill(bit, bit+62, false);
int cnt = 0;
for (auto i = 0; i < 60; ++i) {
if (((X >> i) & 1) == 1) {
bit[i] = true;
++cnt;
}
}
isone = (cnt <= 30);
if (!isone) {
for (auto i = 0; i < 60; ++i) {
bit[i] = !bit[i];
}
}
random_device rd; mt19937 mt(rd());
vector<path> ans;
bool visited[110];
while (true) {
ans.clear();
fill(visited, visited+110, false);
int root = mt()%N;
visited[root] = true;
if (V[root].size() < 5) continue;
random_shuffle(V[root].begin(), V[root].end());
int num = (isone ? 3 : 4);
for (auto i = 0; i < num; ++i) {
ans.push_back(path(root, V[root][i]));
visited[V[root][i]] = true;
}
ans.push_back(path(root, V[root][num]));
int now = V[root][num];
visited[now] = true;
bool failed = false;
for (auto i = 0; i < 62; ++i) {
if ((bit[i] && isone) || (!bit[i] && !isone)) {
num = 2;
} else {
num = 1;
}
if (i >= 60) num = 1;
random_shuffle(V[now].begin(), V[now].end());
int cnt = 0;
for (auto x : V[now]) {
if (!visited[x]) {
visited[x] = true;
ans.push_back(path(now, x));
cnt++;
if (cnt == num) {
now = x;
break;
}
}
}
if (cnt < num) {
failed = true;
break;
}
}
if (failed) {
continue;
} else {
cout << ans.size() << endl;
for (auto x : ans) {
cout << x.first+1 << " " << x.second+1 << endl;
}
return;
}
}
}
void decode() {
int N, A;
cin >> N >> A;
int c[5000];
int d[5000];
vector<int> V[110];
for (auto i = 0; i < A; ++i) {
cin >> c[i] >> d[i];
c[i]--;
d[i]--;
V[c[i]].push_back(d[i]);
V[d[i]].push_back(c[i]);
}
int root = -1;
bool isone = true;
for (auto i = 0; i < N; ++i) {
if ((int)V[i].size() >= 4) {
root = i;
if ((int)V[root].size() == 4) {
isone = true;
} else {
isone = false;
}
break;
}
}
assert(root >= 0);
int now = 0;
for (auto x : V[root]) {
if (V[x].size() > 1) {
now = x;
break;
}
}
assert(now >= 0);
ll ans = 0;
bool visited[110];
fill(visited, visited+110, false);
visited[root] = true;
for (auto i = 0; i < 60; ++i) {
visited[now] = true;
// cerr << "V[" << now << "].size() = " << V[now].size() << endl;
if ((V[now].size() == 3 && isone)
|| (V[now].size() == 2 && !isone)) {
ans += ((ll)1 << i);
}
for (auto x : V[now]) {
if (!visited[x] && V[x].size() >= 2) {
now = x;
break;
}
}
}
cout << ans << endl;
}
int main () {
string s;
cin >> s;
if (s == "encode") {
encode();
} else {
decode();
}
}
<commit_msg>submit G.cpp to 'G - encode/decode 2017' (kupc2017) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
typedef pair<int, int> path;
void encode() {
int N, M;
cin >> N >> M;
bool pass[110][110];
fill(&pass[0][0], &pass[0][0]+110*110, false);
int a[110], b[110];
for (auto i = 0; i < M; ++i) {
cin >> a[i] >> b[i];
a[i]--;
b[i]--;
pass[a[i]][b[i]] = true;
pass[b[i]][a[i]] = true;
}
vector<int> V[110];
for (auto i = 0; i < N; ++i) {
for (auto j = 0; j < N; ++j) {
if (i == j) continue;
if (!pass[i][j]) {
V[i].push_back(j);
}
}
}
ll X;
cin >> X;
bool bit[62];
bool isone = true;
fill(bit, bit+62, false);
int cnt = 0;
for (auto i = 0; i < 60; ++i) {
if (((X >> i) & 1) == 1) {
bit[i] = true;
++cnt;
}
}
isone = (cnt <= 30);
if (!isone) {
for (auto i = 0; i < 60; ++i) {
bit[i] = !bit[i];
}
}
random_device rd; mt19937 mt(rd());
vector<path> ans;
bool visited[110];
int forbid = 0;
int mini = 1000;
for (auto i = 0; i < N; ++i) {
if ((int)V[i].size() < mini) {
forbid = i;
mini = V[i].size();
}
}
while (true) {
bool failed = false;
ans.clear();
fill(visited, visited+110, false);
visited[forbid] = true;
int root = mt()%N;
if (visited[root]) continue;
visited[root] = true;
if (V[root].size() < 5) continue;
random_shuffle(V[root].begin(), V[root].end());
int num = (isone ? 3 : 4);
for (auto i = 0; i < num; ++i) {
ans.push_back(path(root, V[root][i]));
if (visited[V[root][i]]) {
failed = true;
break;
}
visited[V[root][i]] = true;
}
if (failed) continue;
ans.push_back(path(root, V[root][num]));
int now = V[root][num];
if (visited[now]) continue;
visited[now] = true;
for (auto i = 0; i < 62; ++i) {
if (bit[i]) {
num = 2;
} else {
num = 1;
}
if (i >= 60) num = 1;
random_shuffle(V[now].begin(), V[now].end());
int cnt = 0;
for (auto x : V[now]) {
if (!visited[x]) {
visited[x] = true;
ans.push_back(path(now, x));
cnt++;
if (cnt == num) {
now = x;
break;
}
}
}
if (cnt < num) {
failed = true;
break;
}
}
if (failed) {
continue;
} else {
cout << ans.size() << endl;
for (auto x : ans) {
cout << x.first+1 << " " << x.second+1 << endl;
}
return;
}
}
}
void decode() {
int N, A;
cin >> N >> A;
int c[5000];
int d[5000];
vector<int> V[110];
for (auto i = 0; i < A; ++i) {
cin >> c[i] >> d[i];
c[i]--;
d[i]--;
V[c[i]].push_back(d[i]);
V[d[i]].push_back(c[i]);
}
int root = -1;
bool isone = true;
for (auto i = 0; i < N; ++i) {
if ((int)V[i].size() >= 4) {
root = i;
break;
}
}
// cerr << "V[" << root << "].size() = " << V[root].size() << endl;
/*
for (auto x : V[root]) {
cerr << x << " ";
}
cerr << endl;
*/
if ((int)V[root].size() == 4) {
isone = true;
} else {
isone = false;
}
// cerr << "isone = " << isone << endl;
assert(root >= 0);
int now = 0;
for (auto x : V[root]) {
if (V[x].size() > 1) {
now = x;
break;
}
}
assert(now >= 0);
ll ans = 0;
bool visited[110];
fill(visited, visited+110, false);
visited[root] = true;
for (auto i = 0; i < 60; ++i) {
visited[now] = true;
// cerr << "V[" << now << "].size() = " << V[now].size() << endl;
if ((V[now].size() == 3 && isone)
|| (V[now].size() == 2 && !isone)) {
ans += ((ll)1 << i);
}
for (auto x : V[now]) {
if (!visited[x] && V[x].size() >= 2) {
now = x;
break;
}
}
}
cout << ans << endl;
}
int main () {
string s;
cin >> s;
if (s == "encode") {
encode();
} else {
decode();
}
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "Servo.h"
namespace servo {
void on_load_started() { sServo->Delegate().OnLoadStarted(); }
void on_load_ended() { sServo->Delegate().OnLoadEnded(); }
void on_history_changed(bool back, bool forward) {
sServo->Delegate().OnHistoryChanged(back, forward);
}
void on_shutdown_complete() { sServo->Delegate().OnShutdownComplete(); }
void on_alert(const char *message) {
sServo->Delegate().OnAlert(char2w(message));
}
void on_title_changed(const char *title) {
sServo->Delegate().OnTitleChanged(char2w(title));
}
void on_url_changed(const char *url) {
sServo->Delegate().OnURLChanged(char2w(url));
}
void flush() { sServo->Delegate().Flush(); }
void make_current() { sServo->Delegate().MakeCurrent(); }
void wakeup() { sServo->Delegate().WakeUp(); }
bool on_allow_navigation(const char *url) {
return sServo->Delegate().OnAllowNavigation(char2w(url));
};
void on_animating_changed(bool aAnimating) {
sServo->Delegate().OnAnimatingChanged(aAnimating);
}
Servo::Servo(GLsizei width, GLsizei height, ServoDelegate &aDelegate)
: mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {
capi::CInitOptions o;
o.args = NULL;
o.url = "https://servo.org";
o.width = mWindowWidth;
o.height = mWindowHeight;
o.density = 1.0;
o.enable_subpixel_text_antialiasing = false;
o.vr_pointer = NULL;
sServo = this; // FIXME;
capi::CHostCallbacks c;
c.flush = &flush;
c.make_current = &make_current;
c.on_alert = &on_alert;
c.on_load_started = &on_load_started;
c.on_load_ended = &on_load_ended;
c.on_title_changed = &on_title_changed;
c.on_url_changed = &on_url_changed;
c.on_history_changed = &on_history_changed;
c.on_animating_changed = &on_animating_changed;
c.on_shutdown_complete = &on_shutdown_complete;
c.on_allow_navigation = &on_allow_navigation;
init_with_egl(o, &wakeup, c);
}
Servo::~Servo() { sServo = nullptr; }
std::wstring char2w(const char *c_str) {
auto str = std::string(c_str);
int size_needed =
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring str2(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],
size_needed);
return str2;
}
} // namespace servo
<commit_msg>Enable webxr for the UWP port.<commit_after>#include "pch.h"
#include "Servo.h"
namespace servo {
void on_load_started() { sServo->Delegate().OnLoadStarted(); }
void on_load_ended() { sServo->Delegate().OnLoadEnded(); }
void on_history_changed(bool back, bool forward) {
sServo->Delegate().OnHistoryChanged(back, forward);
}
void on_shutdown_complete() { sServo->Delegate().OnShutdownComplete(); }
void on_alert(const char *message) {
sServo->Delegate().OnAlert(char2w(message));
}
void on_title_changed(const char *title) {
sServo->Delegate().OnTitleChanged(char2w(title));
}
void on_url_changed(const char *url) {
sServo->Delegate().OnURLChanged(char2w(url));
}
void flush() { sServo->Delegate().Flush(); }
void make_current() { sServo->Delegate().MakeCurrent(); }
void wakeup() { sServo->Delegate().WakeUp(); }
bool on_allow_navigation(const char *url) {
return sServo->Delegate().OnAllowNavigation(char2w(url));
};
void on_animating_changed(bool aAnimating) {
sServo->Delegate().OnAnimatingChanged(aAnimating);
}
Servo::Servo(GLsizei width, GLsizei height, ServoDelegate &aDelegate)
: mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {
capi::CInitOptions o;
o.args = "--pref dom.webxr.enabled";
o.url = "https://servo.org";
o.width = mWindowWidth;
o.height = mWindowHeight;
o.density = 1.0;
o.enable_subpixel_text_antialiasing = false;
o.vr_pointer = NULL;
sServo = this; // FIXME;
capi::CHostCallbacks c;
c.flush = &flush;
c.make_current = &make_current;
c.on_alert = &on_alert;
c.on_load_started = &on_load_started;
c.on_load_ended = &on_load_ended;
c.on_title_changed = &on_title_changed;
c.on_url_changed = &on_url_changed;
c.on_history_changed = &on_history_changed;
c.on_animating_changed = &on_animating_changed;
c.on_shutdown_complete = &on_shutdown_complete;
c.on_allow_navigation = &on_allow_navigation;
init_with_egl(o, &wakeup, c);
}
Servo::~Servo() { sServo = nullptr; }
std::wstring char2w(const char *c_str) {
auto str = std::string(c_str);
int size_needed =
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring str2(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],
size_needed);
return str2;
}
} // namespace servo
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include "lightsout.hpp"
#include "print.hpp"
namespace roadagain
{
board::board(int width, int height) : width(width), height(height)
{
// init seed of rand() by current time
srand(time(NULL));
lights = new bool*[height + 2]();
for (int i = 0; i < height + 2; i++){
lights[i] = new bool[width + 2]();
for (int j = 1; j < width + 1; j++){
lights[i][j] = (rand() % 2 == 0);
}
}
// print the board
print_board(width, height);
}
board::~board()
{
;
}
}
<commit_msg>Split getting-array and init-print-array<commit_after>#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include "lightsout.hpp"
#include "print.hpp"
namespace roadagain
{
board::board(int width, int height) : width(width), height(height)
{
// init seed of rand() by current time
srand(time(NULL));
lights = new bool*[height + 2]();
for (int i = 0; i < height + 2; i++){
lights[i] = new bool[width + 2]();
}
// init and print the board
print_board(width, height);
for (int i = 1; i < height + 1; i++){
for (int j = 1; j < width + 1; j++){
lights[i][j] = (rand() % 2 == 0);
print_light(i, j, lights[i][j]);
}
}
}
board::~board()
{
;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: test.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:31:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
//_________________________________________________________________________________________________________________
// switches
// use it to enable test szenarios
//_________________________________________________________________________________________________________________
#define TEST_DYNAMICMENUOPTIONS
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include "dynamicmenuoptions.hxx"
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/regpathhelper.hxx>
#endif
#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#include <cppuhelper/servicefactory.hxx>
#endif
#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
/*
#ifndef _SVT_UNOIFACE_HXX
#include <svtools/unoiface.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
*/
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <stdio.h>
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::comphelper ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::beans ;
using namespace ::com::sun::star::registry ;
//_________________________________________________________________________________________________________________
// defines
//_________________________________________________________________________________________________________________
#define ASCII( STEXT ) OUString( RTL_CONSTASCII_USTRINGPARAM( STEXT ))
#define SERVICENAME_SIMPLEREGISTRY OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.registry.SimpleRegistry" ))
#define SERVICENAME_NESTEDREGISTRY OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.registry.NestedRegistry" ))
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
class TestApplication : public Application
{
//*************************************************************************************************************
// interface
//*************************************************************************************************************
public:
void Main();
//*************************************************************************************************************
// test methods
//*************************************************************************************************************
private:
void impl_testDynamicMenuOptions();
//*************************************************************************************************************
// helper methods
//*************************************************************************************************************
private:
static Reference< XMultiServiceFactory > getUNOServiceManager();
//*************************************************************************************************************
// member
//*************************************************************************************************************
private:
}; // class TestApplication
//_________________________________________________________________________________________________________________
// global variables
//_________________________________________________________________________________________________________________
TestApplication aTestApplication ;
//_________________________________________________________________________________________________________________
// main
//_________________________________________________________________________________________________________________
void TestApplication::Main()
{
/**-***********************************************************************************************************
initialize program
**************************************************************************************************************/
// Init global servicemanager and set it for external services.
::comphelper::setProcessServiceFactory( TestApplication::getUNOServiceManager() );
// Control sucess of operation.
OSL_ENSURE( !(::comphelper::getProcessServiceFactory()!=TestApplication::getUNOServiceManager()), "TestApplication::Main()\nGlobal servicemanager not right initialized.\n" );
/**-***********************************************************************************************************
test area
**************************************************************************************************************/
#ifdef TEST_DYNAMICMENUOPTIONS
impl_testDynamicMenuOptions();
#endif
// Execute();
OSL_ENSURE( sal_False, "Test was successful!\n" );
}
//*****************************************************************************************************************
// test configuration of dynamic menus "New" and "Wizard"
//*****************************************************************************************************************
void TestApplication::impl_testDynamicMenuOptions()
{
SvtDynamicMenuOptions aCFG;
// Test:
// read menus
// if( menus == empty )
// {
// fill it with samples
// read it again
// }
// output content
Sequence< Sequence< PropertyValue > > lNewMenu = aCFG.GetMenu( E_NEWMENU );
Sequence< Sequence< PropertyValue > > lWizardMenu = aCFG.GetMenu( E_WIZARDMENU );
if( lNewMenu.getLength() < 1 )
{
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/swriter"), ASCII("new writer"), ASCII("icon_writer"), ASCII("_blank") );
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/scalc" ), ASCII("new calc" ), ASCII("icon_calc" ), ASCII("_blank") );
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/sdraw" ), ASCII("new draw" ), ASCII("icon_draw" ), ASCII("_blank") );
lNewMenu = aCFG.GetMenu( E_NEWMENU );
}
if( lWizardMenu.getLength() < 1 )
{
aCFG.AppendItem( E_WIZARDMENU, ASCII("file://a"), ASCII("system file"), ASCII("icon_file"), ASCII("_self") );
aCFG.AppendItem( E_WIZARDMENU, ASCII("ftp://b" ), ASCII("ftp host" ), ASCII("icon_ftp" ), ASCII("_self") );
aCFG.AppendItem( E_WIZARDMENU, ASCII("http://c"), ASCII("www" ), ASCII("icon_www" ), ASCII("_self") );
lWizardMenu = aCFG.GetMenu( E_WIZARDMENU );
}
sal_uInt32 nItemCount ;
sal_uInt32 nItem ;
sal_uInt32 nPropertyCount;
sal_uInt32 nProperty ;
OUString sPropertyValue;
OUStringBuffer sOut( 5000 ) ;
nItemCount = lNewMenu.getLength();
for( nItem=0; nItem<nItemCount; ++nItem )
{
nPropertyCount = lNewMenu[nItem].getLength();
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
lNewMenu[nItem][nProperty].Value >>= sPropertyValue;
sOut.appendAscii ( "New/" );
sOut.append ( (sal_Int32)nItem );
sOut.appendAscii ( "/" );
sOut.append ( lNewMenu[nItem][nProperty].Name );
sOut.appendAscii ( " = " );
sOut.append ( sPropertyValue );
sOut.appendAscii ( "\n" );
}
}
sOut.appendAscii("\n--------------------------------------\n");
nItemCount = lWizardMenu.getLength();
for( nItem=0; nItem<nItemCount; ++nItem )
{
nPropertyCount = lNewMenu[nItem].getLength();
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
lWizardMenu[nItem][nProperty].Value >>= sPropertyValue;
sOut.appendAscii ( "Wizard/" );
sOut.append ( (sal_Int32)nItem );
sOut.appendAscii ( "/" );
sOut.append ( lNewMenu[nItem][nProperty].Name );
sOut.appendAscii ( " = " );
sOut.append ( sPropertyValue );
sOut.appendAscii ( "\n" );
}
}
OSL_ENSURE( sal_False, OUStringToOString( sOut.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ).getStr() );
}
//*****************************************************************************************************************
// create new uno servicemanager by using normall applicat.rdb and user.rdb of an office installation!
// Don't use this application at same time like the office!
//*****************************************************************************************************************
Reference< XMultiServiceFactory > TestApplication::getUNOServiceManager()
{
static Reference< XMultiServiceFactory > smgr;
if( ! smgr.is() )
{
Reference< XComponentContext > rCtx =
cppu::defaultBootstrap_InitialComponentContext();
smgr = Reference< XMultiServiceFactory > ( rCtx->getServiceManager() , UNO_QUERY );
}
return smgr;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.200); FILE MERGED 2007/06/04 13:31:27 vg 1.5.200.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: test.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 21:18:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
//_________________________________________________________________________________________________________________
// switches
// use it to enable test szenarios
//_________________________________________________________________________________________________________________
#define TEST_DYNAMICMENUOPTIONS
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <svtools/dynamicmenuoptions.hxx>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/regpathhelper.hxx>
#endif
#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#include <cppuhelper/servicefactory.hxx>
#endif
#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
/*
#ifndef _SVT_UNOIFACE_HXX
#include <svtools/unoiface.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
*/
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <stdio.h>
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::comphelper ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::beans ;
using namespace ::com::sun::star::registry ;
//_________________________________________________________________________________________________________________
// defines
//_________________________________________________________________________________________________________________
#define ASCII( STEXT ) OUString( RTL_CONSTASCII_USTRINGPARAM( STEXT ))
#define SERVICENAME_SIMPLEREGISTRY OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.registry.SimpleRegistry" ))
#define SERVICENAME_NESTEDREGISTRY OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.registry.NestedRegistry" ))
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
class TestApplication : public Application
{
//*************************************************************************************************************
// interface
//*************************************************************************************************************
public:
void Main();
//*************************************************************************************************************
// test methods
//*************************************************************************************************************
private:
void impl_testDynamicMenuOptions();
//*************************************************************************************************************
// helper methods
//*************************************************************************************************************
private:
static Reference< XMultiServiceFactory > getUNOServiceManager();
//*************************************************************************************************************
// member
//*************************************************************************************************************
private:
}; // class TestApplication
//_________________________________________________________________________________________________________________
// global variables
//_________________________________________________________________________________________________________________
TestApplication aTestApplication ;
//_________________________________________________________________________________________________________________
// main
//_________________________________________________________________________________________________________________
void TestApplication::Main()
{
/**-***********************************************************************************************************
initialize program
**************************************************************************************************************/
// Init global servicemanager and set it for external services.
::comphelper::setProcessServiceFactory( TestApplication::getUNOServiceManager() );
// Control sucess of operation.
OSL_ENSURE( !(::comphelper::getProcessServiceFactory()!=TestApplication::getUNOServiceManager()), "TestApplication::Main()\nGlobal servicemanager not right initialized.\n" );
/**-***********************************************************************************************************
test area
**************************************************************************************************************/
#ifdef TEST_DYNAMICMENUOPTIONS
impl_testDynamicMenuOptions();
#endif
// Execute();
OSL_ENSURE( sal_False, "Test was successful!\n" );
}
//*****************************************************************************************************************
// test configuration of dynamic menus "New" and "Wizard"
//*****************************************************************************************************************
void TestApplication::impl_testDynamicMenuOptions()
{
SvtDynamicMenuOptions aCFG;
// Test:
// read menus
// if( menus == empty )
// {
// fill it with samples
// read it again
// }
// output content
Sequence< Sequence< PropertyValue > > lNewMenu = aCFG.GetMenu( E_NEWMENU );
Sequence< Sequence< PropertyValue > > lWizardMenu = aCFG.GetMenu( E_WIZARDMENU );
if( lNewMenu.getLength() < 1 )
{
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/swriter"), ASCII("new writer"), ASCII("icon_writer"), ASCII("_blank") );
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/scalc" ), ASCII("new calc" ), ASCII("icon_calc" ), ASCII("_blank") );
aCFG.AppendItem( E_NEWMENU, ASCII("private:factory/sdraw" ), ASCII("new draw" ), ASCII("icon_draw" ), ASCII("_blank") );
lNewMenu = aCFG.GetMenu( E_NEWMENU );
}
if( lWizardMenu.getLength() < 1 )
{
aCFG.AppendItem( E_WIZARDMENU, ASCII("file://a"), ASCII("system file"), ASCII("icon_file"), ASCII("_self") );
aCFG.AppendItem( E_WIZARDMENU, ASCII("ftp://b" ), ASCII("ftp host" ), ASCII("icon_ftp" ), ASCII("_self") );
aCFG.AppendItem( E_WIZARDMENU, ASCII("http://c"), ASCII("www" ), ASCII("icon_www" ), ASCII("_self") );
lWizardMenu = aCFG.GetMenu( E_WIZARDMENU );
}
sal_uInt32 nItemCount ;
sal_uInt32 nItem ;
sal_uInt32 nPropertyCount;
sal_uInt32 nProperty ;
OUString sPropertyValue;
OUStringBuffer sOut( 5000 ) ;
nItemCount = lNewMenu.getLength();
for( nItem=0; nItem<nItemCount; ++nItem )
{
nPropertyCount = lNewMenu[nItem].getLength();
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
lNewMenu[nItem][nProperty].Value >>= sPropertyValue;
sOut.appendAscii ( "New/" );
sOut.append ( (sal_Int32)nItem );
sOut.appendAscii ( "/" );
sOut.append ( lNewMenu[nItem][nProperty].Name );
sOut.appendAscii ( " = " );
sOut.append ( sPropertyValue );
sOut.appendAscii ( "\n" );
}
}
sOut.appendAscii("\n--------------------------------------\n");
nItemCount = lWizardMenu.getLength();
for( nItem=0; nItem<nItemCount; ++nItem )
{
nPropertyCount = lNewMenu[nItem].getLength();
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
lWizardMenu[nItem][nProperty].Value >>= sPropertyValue;
sOut.appendAscii ( "Wizard/" );
sOut.append ( (sal_Int32)nItem );
sOut.appendAscii ( "/" );
sOut.append ( lNewMenu[nItem][nProperty].Name );
sOut.appendAscii ( " = " );
sOut.append ( sPropertyValue );
sOut.appendAscii ( "\n" );
}
}
OSL_ENSURE( sal_False, OUStringToOString( sOut.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ).getStr() );
}
//*****************************************************************************************************************
// create new uno servicemanager by using normall applicat.rdb and user.rdb of an office installation!
// Don't use this application at same time like the office!
//*****************************************************************************************************************
Reference< XMultiServiceFactory > TestApplication::getUNOServiceManager()
{
static Reference< XMultiServiceFactory > smgr;
if( ! smgr.is() )
{
Reference< XComponentContext > rCtx =
cppu::defaultBootstrap_InitialComponentContext();
smgr = Reference< XMultiServiceFactory > ( rCtx->getServiceManager() , UNO_QUERY );
}
return smgr;
}
<|endoftext|> |
<commit_before><commit_msg>ARMY - ARMY STRENGTH.cpp<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2007-05-10 14:49:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include "svxitems.hrc"
#include "dialmgr.hxx"
TYPEINIT1_FACTORY(SvxCharHiddenItem, SfxBoolItem, new SvxCharHiddenItem(sal_False, 0));
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/,
SfxMapUnit /*ePresUnit*/,
XubString& rText, const IntlWrapper * /*pIntl*/
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
default: ; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.7.32); FILE MERGED 2007/06/04 13:27:04 vg 1.7.32.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:26:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include <svx/svxitems.hrc>
#include <svx/dialmgr.hxx>
TYPEINIT1_FACTORY(SvxCharHiddenItem, SfxBoolItem, new SvxCharHiddenItem(sal_False, 0));
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/,
SfxMapUnit /*ePresUnit*/,
XubString& rText, const IntlWrapper * /*pIntl*/
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
default: ; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:10:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define ITEMID_CHARHIDDEN 0
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include "svxitems.hrc"
#include "dialmgr.hxx"
TYPEINIT1_AUTOFACTORY(SvxCharHiddenItem, SfxBoolItem);
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/,
SfxMapUnit /*ePresUnit*/,
XubString& rText, const IntlWrapper */*pIntl*/
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
default: ; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.116); FILE MERGED 2006/09/01 17:46:58 kaib 1.4.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charhiddenitem.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:18:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#define ITEMID_CHARHIDDEN 0
#ifndef _SVX_CHARHIDDENITEM_HXX
#include <charhiddenitem.hxx>
#endif
#include "svxitems.hrc"
#include "dialmgr.hxx"
TYPEINIT1_AUTOFACTORY(SvxCharHiddenItem, SfxBoolItem);
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SvxCharHiddenItem::SvxCharHiddenItem( const sal_Bool bHidden, const USHORT nId ) :
SfxBoolItem( nId, bHidden )
{
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxPoolItem* SvxCharHiddenItem::Clone( SfxItemPool * ) const
{
return new SvxCharHiddenItem( *this );
}
/*-- 16.12.2003 15:24:25---------------------------------------------------
-----------------------------------------------------------------------*/
SfxItemPresentation SvxCharHiddenItem::GetPresentation
(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/,
SfxMapUnit /*ePresUnit*/,
XubString& rText, const IntlWrapper */*pIntl*/
) const
{
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_NONE:
rText.Erase();
return ePres;
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
{
USHORT nId = RID_SVXITEMS_CHARHIDDEN_FALSE;
if ( GetValue() )
nId = RID_SVXITEMS_CHARHIDDEN_TRUE;
rText = SVX_RESSTR(nId);
return ePres;
}
default: ; //prevent warning
}
return SFX_ITEM_PRESENTATION_NONE;
}
<|endoftext|> |
<commit_before>//===-- sanitizer_win.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements windows-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#include <stdlib.h>
#include <io.h>
#include <windows.h>
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include "sanitizer_placement_new.h"
#include "sanitizer_mutex.h"
namespace __sanitizer {
// --------------------- sanitizer_common.h
uptr GetPageSize() {
return 1U << 14; // FIXME: is this configurable?
}
uptr GetMmapGranularity() {
return 1U << 16; // FIXME: is this configurable?
}
bool FileExists(const char *filename) {
UNIMPLEMENTED();
}
int GetPid() {
return GetProcessId(GetCurrentProcess());
}
uptr GetThreadSelf() {
return GetCurrentThreadId();
}
void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
uptr *stack_bottom) {
CHECK(stack_top);
CHECK(stack_bottom);
MEMORY_BASIC_INFORMATION mbi;
CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
// FIXME: is it possible for the stack to not be a single allocation?
// Are these values what ASan expects to get (reserved, not committed;
// including stack guard page) ?
*stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
*stack_bottom = (uptr)mbi.AllocationBase;
}
void *MmapOrDie(uptr size, const char *mem_type) {
void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (rv == 0) {
Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n",
size, size, mem_type);
CHECK("unable to mmap" && 0);
}
return rv;
}
void UnmapOrDie(void *addr, uptr size) {
if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
Report("ERROR: Failed to deallocate 0x%zx (%zd) bytes at address %p\n",
size, size, addr);
CHECK("unable to unmap" && 0);
}
}
void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
// FIXME: is this really "NoReserve"? On Win32 this does not matter much,
// but on Win64 it does.
void *p = VirtualAlloc((LPVOID)fixed_addr, size,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (p == 0)
Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n",
size, size, fixed_addr, GetLastError());
return p;
}
void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
return MmapFixedNoReserve(fixed_addr, size);
}
void *Mprotect(uptr fixed_addr, uptr size) {
return VirtualAlloc((LPVOID)fixed_addr, size,
MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS);
}
void FlushUnneededShadowMemory(uptr addr, uptr size) {
// This is almost useless on 32-bits.
// FIXME: add madvice-analog when we move to 64-bits.
}
bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
// FIXME: shall we do anything here on Windows?
return true;
}
void *MapFileToMemory(const char *file_name, uptr *buff_size) {
UNIMPLEMENTED();
}
static const kMaxEnvNameLength = 128;
static const kMaxEnvValueLength = 32767;
namespace {
struct EnvVariable {
char name[kMaxEnvNameLength];
char value[kMaxEnvValueLength];
};
} // namespace
static const int kEnvVariables = 5;
static EnvVariable env_vars[kEnvVariables];
static int num_env_vars;
const char *GetEnv(const char *name) {
// Note: this implementation caches the values of the environment variables
// and limits their quantity.
for (int i = 0; i < num_env_vars; i++) {
if (0 == internal_strcmp(name, env_vars[i].name))
return env_vars[i].value;
}
CHECK_LT(num_env_vars, kEnvVariables);
DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
kMaxEnvValueLength);
if (rv > 0 && rv < kMaxEnvValueLength) {
CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
num_env_vars++;
return env_vars[num_env_vars - 1].value;
}
return 0;
}
const char *GetPwd() {
UNIMPLEMENTED();
}
u32 GetUid() {
UNIMPLEMENTED();
}
void DumpProcessMap() {
UNIMPLEMENTED();
}
void DisableCoreDumper() {
UNIMPLEMENTED();
}
void ReExec() {
UNIMPLEMENTED();
}
void PrepareForSandboxing() {
// Nothing here for now.
}
bool StackSizeIsUnlimited() {
UNIMPLEMENTED();
}
void SetStackSizeLimitInBytes(uptr limit) {
UNIMPLEMENTED();
}
void SleepForSeconds(int seconds) {
Sleep(seconds * 1000);
}
void SleepForMillis(int millis) {
Sleep(millis);
}
void Abort() {
abort();
_exit(-1); // abort is not NORETURN on Windows.
}
#ifndef SANITIZER_GO
int Atexit(void (*function)(void)) {
return atexit(function);
}
#endif
// ------------------ sanitizer_libc.h
void *internal_mmap(void *addr, uptr length, int prot, int flags,
int fd, u64 offset) {
UNIMPLEMENTED();
}
int internal_munmap(void *addr, uptr length) {
UNIMPLEMENTED();
}
int internal_close(fd_t fd) {
UNIMPLEMENTED();
}
int internal_isatty(fd_t fd) {
return _isatty(fd);
}
fd_t internal_open(const char *filename, int flags) {
UNIMPLEMENTED();
}
fd_t internal_open(const char *filename, int flags, u32 mode) {
UNIMPLEMENTED();
}
fd_t OpenFile(const char *filename, bool write) {
UNIMPLEMENTED();
}
uptr internal_read(fd_t fd, void *buf, uptr count) {
UNIMPLEMENTED();
}
uptr internal_write(fd_t fd, const void *buf, uptr count) {
if (fd != kStderrFd)
UNIMPLEMENTED();
HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
if (err == 0)
return 0; // FIXME: this might not work on some apps.
DWORD ret;
if (!WriteFile(err, buf, count, &ret, 0))
return 0;
return ret;
}
int internal_stat(const char *path, void *buf) {
UNIMPLEMENTED();
}
int internal_lstat(const char *path, void *buf) {
UNIMPLEMENTED();
}
int internal_fstat(fd_t fd, void *buf) {
UNIMPLEMENTED();
}
uptr internal_filesize(fd_t fd) {
UNIMPLEMENTED();
}
int internal_dup2(int oldfd, int newfd) {
UNIMPLEMENTED();
}
uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
UNIMPLEMENTED();
}
int internal_sched_yield() {
Sleep(0);
return 0;
}
void internal__exit(int exitcode) {
_exit(exitcode);
}
// ---------------------- BlockingMutex ---------------- {{{1
const uptr LOCK_UNINITIALIZED = 0;
const uptr LOCK_READY = (uptr)-1;
BlockingMutex::BlockingMutex(LinkerInitialized li) {
// FIXME: see comments in BlockingMutex::Lock() for the details.
CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
owner_ = LOCK_READY;
}
void BlockingMutex::Lock() {
if (owner_ == LOCK_UNINITIALIZED) {
// FIXME: hm, global BlockingMutex objects are not initialized?!?
// This might be a side effect of the clang+cl+link Frankenbuild...
new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
// FIXME: If it turns out the linker doesn't invoke our
// constructors, we should probably manually Lock/Unlock all the global
// locks while we're starting in one thread to avoid double-init races.
}
EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
CHECK_EQ(owner_, LOCK_READY);
owner_ = GetThreadSelf();
}
void BlockingMutex::Unlock() {
CHECK_EQ(owner_, GetThreadSelf());
owner_ = LOCK_READY;
LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
}
void BlockingMutex::CheckLocked() {
CHECK_EQ(owner_, GetThreadSelf());
}
uptr GetTlsSize() {
return 0;
}
void InitTlsSize() {
}
} // namespace __sanitizer
#endif // _WIN32
<commit_msg>[Sanitizer] fix compilation for Windows<commit_after>//===-- sanitizer_win.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements windows-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#include <stdlib.h>
#include <io.h>
#include <windows.h>
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include "sanitizer_placement_new.h"
#include "sanitizer_mutex.h"
namespace __sanitizer {
// --------------------- sanitizer_common.h
uptr GetPageSize() {
return 1U << 14; // FIXME: is this configurable?
}
uptr GetMmapGranularity() {
return 1U << 16; // FIXME: is this configurable?
}
bool FileExists(const char *filename) {
UNIMPLEMENTED();
}
int GetPid() {
return GetProcessId(GetCurrentProcess());
}
uptr GetThreadSelf() {
return GetCurrentThreadId();
}
void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
uptr *stack_bottom) {
CHECK(stack_top);
CHECK(stack_bottom);
MEMORY_BASIC_INFORMATION mbi;
CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
// FIXME: is it possible for the stack to not be a single allocation?
// Are these values what ASan expects to get (reserved, not committed;
// including stack guard page) ?
*stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
*stack_bottom = (uptr)mbi.AllocationBase;
}
void *MmapOrDie(uptr size, const char *mem_type) {
void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (rv == 0) {
Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n",
size, size, mem_type);
CHECK("unable to mmap" && 0);
}
return rv;
}
void UnmapOrDie(void *addr, uptr size) {
if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
Report("ERROR: Failed to deallocate 0x%zx (%zd) bytes at address %p\n",
size, size, addr);
CHECK("unable to unmap" && 0);
}
}
void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
// FIXME: is this really "NoReserve"? On Win32 this does not matter much,
// but on Win64 it does.
void *p = VirtualAlloc((LPVOID)fixed_addr, size,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (p == 0)
Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n",
size, size, fixed_addr, GetLastError());
return p;
}
void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
return MmapFixedNoReserve(fixed_addr, size);
}
void *Mprotect(uptr fixed_addr, uptr size) {
return VirtualAlloc((LPVOID)fixed_addr, size,
MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS);
}
void FlushUnneededShadowMemory(uptr addr, uptr size) {
// This is almost useless on 32-bits.
// FIXME: add madvice-analog when we move to 64-bits.
}
bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
// FIXME: shall we do anything here on Windows?
return true;
}
void *MapFileToMemory(const char *file_name, uptr *buff_size) {
UNIMPLEMENTED();
}
static const int kMaxEnvNameLength = 128;
static const int kMaxEnvValueLength = 32767;
namespace {
struct EnvVariable {
char name[kMaxEnvNameLength];
char value[kMaxEnvValueLength];
};
} // namespace
static const int kEnvVariables = 5;
static EnvVariable env_vars[kEnvVariables];
static int num_env_vars;
const char *GetEnv(const char *name) {
// Note: this implementation caches the values of the environment variables
// and limits their quantity.
for (int i = 0; i < num_env_vars; i++) {
if (0 == internal_strcmp(name, env_vars[i].name))
return env_vars[i].value;
}
CHECK_LT(num_env_vars, kEnvVariables);
DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
kMaxEnvValueLength);
if (rv > 0 && rv < kMaxEnvValueLength) {
CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
num_env_vars++;
return env_vars[num_env_vars - 1].value;
}
return 0;
}
const char *GetPwd() {
UNIMPLEMENTED();
}
u32 GetUid() {
UNIMPLEMENTED();
}
void DumpProcessMap() {
UNIMPLEMENTED();
}
void DisableCoreDumper() {
UNIMPLEMENTED();
}
void ReExec() {
UNIMPLEMENTED();
}
void PrepareForSandboxing() {
// Nothing here for now.
}
bool StackSizeIsUnlimited() {
UNIMPLEMENTED();
}
void SetStackSizeLimitInBytes(uptr limit) {
UNIMPLEMENTED();
}
void SleepForSeconds(int seconds) {
Sleep(seconds * 1000);
}
void SleepForMillis(int millis) {
Sleep(millis);
}
void Abort() {
abort();
_exit(-1); // abort is not NORETURN on Windows.
}
#ifndef SANITIZER_GO
int Atexit(void (*function)(void)) {
return atexit(function);
}
#endif
// ------------------ sanitizer_libc.h
void *internal_mmap(void *addr, uptr length, int prot, int flags,
int fd, u64 offset) {
UNIMPLEMENTED();
}
int internal_munmap(void *addr, uptr length) {
UNIMPLEMENTED();
}
int internal_close(fd_t fd) {
UNIMPLEMENTED();
}
int internal_isatty(fd_t fd) {
return _isatty(fd);
}
fd_t internal_open(const char *filename, int flags) {
UNIMPLEMENTED();
}
fd_t internal_open(const char *filename, int flags, u32 mode) {
UNIMPLEMENTED();
}
fd_t OpenFile(const char *filename, bool write) {
UNIMPLEMENTED();
}
uptr internal_read(fd_t fd, void *buf, uptr count) {
UNIMPLEMENTED();
}
uptr internal_write(fd_t fd, const void *buf, uptr count) {
if (fd != kStderrFd)
UNIMPLEMENTED();
HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
if (err == 0)
return 0; // FIXME: this might not work on some apps.
DWORD ret;
if (!WriteFile(err, buf, count, &ret, 0))
return 0;
return ret;
}
int internal_stat(const char *path, void *buf) {
UNIMPLEMENTED();
}
int internal_lstat(const char *path, void *buf) {
UNIMPLEMENTED();
}
int internal_fstat(fd_t fd, void *buf) {
UNIMPLEMENTED();
}
uptr internal_filesize(fd_t fd) {
UNIMPLEMENTED();
}
int internal_dup2(int oldfd, int newfd) {
UNIMPLEMENTED();
}
uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
UNIMPLEMENTED();
}
int internal_sched_yield() {
Sleep(0);
return 0;
}
void internal__exit(int exitcode) {
_exit(exitcode);
}
// ---------------------- BlockingMutex ---------------- {{{1
const uptr LOCK_UNINITIALIZED = 0;
const uptr LOCK_READY = (uptr)-1;
BlockingMutex::BlockingMutex(LinkerInitialized li) {
// FIXME: see comments in BlockingMutex::Lock() for the details.
CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
owner_ = LOCK_READY;
}
void BlockingMutex::Lock() {
if (owner_ == LOCK_UNINITIALIZED) {
// FIXME: hm, global BlockingMutex objects are not initialized?!?
// This might be a side effect of the clang+cl+link Frankenbuild...
new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
// FIXME: If it turns out the linker doesn't invoke our
// constructors, we should probably manually Lock/Unlock all the global
// locks while we're starting in one thread to avoid double-init races.
}
EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
CHECK_EQ(owner_, LOCK_READY);
owner_ = GetThreadSelf();
}
void BlockingMutex::Unlock() {
CHECK_EQ(owner_, GetThreadSelf());
owner_ = LOCK_READY;
LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
}
void BlockingMutex::CheckLocked() {
CHECK_EQ(owner_, GetThreadSelf());
}
uptr GetTlsSize() {
return 0;
}
void InitTlsSize() {
}
} // namespace __sanitizer
#endif // _WIN32
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Test program for libkdepim/email.h
#include "email.h"
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <kdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
using namespace KPIM;
static bool check(const QString& txt, const QString& a, const QString& b)
{
if (a == b) {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
}
else {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
exit(1);
}
return true;
}
static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal)
{
QString name, email;
bool retVal = KPIM::getNameAndMail(input, name, email);
check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" );
check( "getNameAndMail " + input + " name", name, expName );
check( "getNameAndMail " + input + " email", email, expEmail );
return true;
}
// convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice
static QString emailTestParseResultToString( EmailParseResult errorCode )
{
if( errorCode == TooManyAts ) {
return "TooManyAts";
} else if( errorCode == TooFewAts ) {
return "TooFewAts";
} else if( errorCode == AddressEmpty ) {
return "AddressEmpty";
} else if( errorCode == MissingLocalPart ) {
return "MissingLocalPart";
} else if( errorCode == MissingDomainPart ) {
return "MissingDomainPart";
} else if( errorCode == UnbalancedParens ) {
return "UnbalancedParens";
} else if( errorCode == AddressOk ) {
return "AddressOk";
} else if( errorCode == UnclosedAngleAddr ) {
return "UnclosedAngleAddr";
} else if( errorCode == UnexpectedEnd ) {
return "UnexpectedEnd";
} else if( errorCode == UnopenedAngleAddr ) {
return "UnopenedAngleAddr";
}
return "unknown errror code";
}
static QString simpleEmailTestParseResultToString( bool validEmail )
{
if ( validEmail ) {
return "true";
} else if ( !validEmail ) {
return "false";
}
}
static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode )
{
EmailParseResult errorCode = KPIM::isValidEmailAddress( input );
QString errorC = emailTestParseResultToString( errorCode );
check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode );
return true;
}
static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult )
{
bool validEmail = KPIM::isValidSimpleEmailAddress( input );
QString result = simpleEmailTestParseResultToString( validEmail );
check( "isValidSimpleEmailAddress " + input + " result ", result, expResult );
return true;
}
int main(int argc, char *argv[])
{
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 );
KApplication app( false, false );
// Empty input
checkGetNameAndEmail( QString::null, QString::null, QString::null, false );
// Email only
checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false );
// Normal case
checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true );
// Double-quotes
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true );
// Parenthesis
checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513
// Double-quotes inside parenthesis
checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true );
// Parenthesis inside double-quotes
checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true );
// Space in email
checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true );
// Check that '@' in name doesn't confuse it
checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true );
// Interestingly, this isn't supported.
//checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true );
// While typing, when there's no '@' yet
checkGetNameAndEmail( "foo", "foo", QString::null, false );
checkGetNameAndEmail( "foo <", "foo", QString::null, false );
checkGetNameAndEmail( "foo <b", "foo", "b", true );
// If multiple emails are there, only return the first one
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true );
// No '@'
checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true );
// To many @'s
checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" );
// To few @'s
checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" );
// An empty string
checkIsValidEmailAddress( QString::null , "AddressEmpty" );
// email address starting with a @
checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" );
// make sure that starting @ and an additional @ in the same email address don't conflict
// trap the starting @ first and break
checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" );
// email address ending with a @
checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" );
// make sure that ending with@ and an additional @ in the email address don't conflict
checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" );
// unbalanced Parens
checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" );
// unbalanced Parens the other way around
checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" );
// Correct parens just to make sure it works
checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" );
// Check that anglebrackets are closed
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" );
// Check that angle brackets are closed the other way around
checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" );
// Check that angle brackets are closed the other way around, and anglebrackets in domainpart
// instead of local part
// checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" );
// check that a properly formated anglebrackets situation is OK
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" );
// a full email address with comments angle brackets and the works should be valid too
checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" );
// Double quotes
checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" );
// Double quotes inside parens
checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" );
// Parens inside double quotes
checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" );
// Space in email
checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" );
// @ is allowed inisde doublequotes
checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" );
// a , inside a double quoted string is OK, how do I know this? well Ingo says so
// and it makes sense since it is also a seperator of email addresses
checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" );
// checks for "pure" email addresses in the form of xxx@yyy.tld
checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" );
// non-ASCII char as first char of IDN
checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" );
// check if the pure email address is wrong
checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" );
printf("\nTest OK !\n");
return 0;
}
<commit_msg>MOre testcases, mostly to do with weird and wonderful domain parts like matt@[123.123.123.123] that was discussed with Ingo<commit_after>/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Test program for libkdepim/email.h
#include "email.h"
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <kdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
using namespace KPIM;
static bool check(const QString& txt, const QString& a, const QString& b)
{
if (a == b) {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
}
else {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
exit(1);
}
return true;
}
static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal)
{
QString name, email;
bool retVal = KPIM::getNameAndMail(input, name, email);
check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" );
check( "getNameAndMail " + input + " name", name, expName );
check( "getNameAndMail " + input + " email", email, expEmail );
return true;
}
// convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice
static QString emailTestParseResultToString( EmailParseResult errorCode )
{
if( errorCode == TooManyAts ) {
return "TooManyAts";
} else if( errorCode == TooFewAts ) {
return "TooFewAts";
} else if( errorCode == AddressEmpty ) {
return "AddressEmpty";
} else if( errorCode == MissingLocalPart ) {
return "MissingLocalPart";
} else if( errorCode == MissingDomainPart ) {
return "MissingDomainPart";
} else if( errorCode == UnbalancedParens ) {
return "UnbalancedParens";
} else if( errorCode == AddressOk ) {
return "AddressOk";
} else if( errorCode == UnclosedAngleAddr ) {
return "UnclosedAngleAddr";
} else if( errorCode == UnexpectedEnd ) {
return "UnexpectedEnd";
} else if( errorCode == UnopenedAngleAddr ) {
return "UnopenedAngleAddr";
}
return "unknown errror code";
}
static QString simpleEmailTestParseResultToString( bool validEmail )
{
if ( validEmail ) {
return "true";
} else if ( !validEmail ) {
return "false";
}
}
static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode )
{
EmailParseResult errorCode = KPIM::isValidEmailAddress( input );
QString errorC = emailTestParseResultToString( errorCode );
check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode );
return true;
}
static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult )
{
bool validEmail = KPIM::isValidSimpleEmailAddress( input );
QString result = simpleEmailTestParseResultToString( validEmail );
check( "isValidSimpleEmailAddress " + input + " result ", result, expResult );
return true;
}
int main(int argc, char *argv[])
{
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 );
KApplication app( false, false );
// Empty input
checkGetNameAndEmail( QString::null, QString::null, QString::null, false );
// Email only
checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false );
// Normal case
checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true );
// Double-quotes
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true );
// Parenthesis
checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513
// Double-quotes inside parenthesis
checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true );
// Parenthesis inside double-quotes
checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true );
// Space in email
checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true );
// Check that '@' in name doesn't confuse it
checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true );
// Interestingly, this isn't supported.
//checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true );
// While typing, when there's no '@' yet
checkGetNameAndEmail( "foo", "foo", QString::null, false );
checkGetNameAndEmail( "foo <", "foo", QString::null, false );
checkGetNameAndEmail( "foo <b", "foo", "b", true );
// If multiple emails are there, only return the first one
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true );
// No '@'
checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true );
// To many @'s
checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" );
// To few @'s
checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" );
// An empty string
checkIsValidEmailAddress( QString::null , "AddressEmpty" );
// email address starting with a @
checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" );
// make sure that starting @ and an additional @ in the same email address don't conflict
// trap the starting @ first and break
checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" );
// email address ending with a @
checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" );
// make sure that ending with@ and an additional @ in the email address don't conflict
checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" );
// unbalanced Parens
checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" );
// unbalanced Parens the other way around
checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" );
// Correct parens just to make sure it works
checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" );
// Check that anglebrackets are closed
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" );
// Check that angle brackets are closed the other way around
checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" );
// Check that angle brackets are closed the other way around, and anglebrackets in domainpart
// instead of local part
// checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" );
// check that a properly formated anglebrackets situation is OK
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" );
// a full email address with comments angle brackets and the works should be valid too
checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" );
// Double quotes
checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" );
// Double quotes inside parens
checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" );
// Parens inside double quotes
checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" );
// Space in email
checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" );
// @ is allowed inisde doublequotes
checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" );
// a , inside a double quoted string is OK, how do I know this? well Ingo says so
// and it makes sense since it is also a seperator of email addresses
checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" );
// checks for "pure" email addresses in the form of xxx@yyy.tld
checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" );
// non-ASCII char as first char of IDN
checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123]", "true" );
// check if the pure email address is wrong
checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123", "false" );
checkIsValidSimpleEmailAddress( "matt@123.123.123.123]", "false" );
printf("\nTest OK !\n");
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Test program for libkdepim/email.h
#include "email.h"
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <kdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
using namespace KPIM;
static bool check(const QString& txt, const QString& a, const QString& b)
{
if (a == b) {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
}
else {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
exit(1);
}
return true;
}
static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal)
{
QString name, email;
bool retVal = KPIM::getNameAndMail(input, name, email);
check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" );
check( "getNameAndMail " + input + " name", name, expName );
check( "getNameAndMail " + input + " email", email, expEmail );
return true;
}
// convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice
static QString emailTestParseResultToString( EmailParseResult errorCode )
{
if( errorCode == TooManyAts ) {
return "TooManyAts";
} else if( errorCode == TooFewAts ) {
return "TooFewAts";
} else if( errorCode == AddressEmpty ) {
return "AddressEmpty";
} else if( errorCode == MissingLocalPart ) {
return "MissingLocalPart";
} else if( errorCode == MissingDomainPart ) {
return "MissingDomainPart";
} else if( errorCode == UnbalancedParens ) {
return "UnbalancedParens";
} else if( errorCode == AddressOk ) {
return "AddressOk";
} else if( errorCode == UnclosedAngleAddr ) {
return "UnclosedAngleAddr";
} else if( errorCode == UnexpectedEnd ) {
return "UnexpectedEnd";
} else if( errorCode == UnopenedAngleAddr ) {
return "UnopenedAngleAddr";
}
return "unknown errror code";
}
static QString simpleEmailTestParseResultToString( bool validEmail )
{
if ( validEmail ) {
return "true";
} else if ( !validEmail ) {
return "false";
}
}
static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode )
{
EmailParseResult errorCode = KPIM::isValidEmailAddress( input );
QString errorC = emailTestParseResultToString( errorCode );
check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode );
return true;
}
static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult )
{
bool validEmail = KPIM::isValidSimpleEmailAddress( input );
QString result = simpleEmailTestParseResultToString( validEmail );
check( "isValidSimpleEmailAddress " + input + " result ", result, expResult );
return true;
}
int main(int argc, char *argv[])
{
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 );
KApplication app( false, false );
// Empty input
checkGetNameAndEmail( QString::null, QString::null, QString::null, false );
// Email only
checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false );
// Normal case
checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true );
// Double-quotes
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true );
// Parenthesis
checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513
// Double-quotes inside parenthesis
checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true );
// Parenthesis inside double-quotes
checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true );
// Space in email
checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true );
// Check that '@' in name doesn't confuse it
checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true );
// Interestingly, this isn't supported.
//checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true );
// While typing, when there's no '@' yet
checkGetNameAndEmail( "foo", "foo", QString::null, false );
checkGetNameAndEmail( "foo <", "foo", QString::null, false );
checkGetNameAndEmail( "foo <b", "foo", "b", true );
// If multiple emails are there, only return the first one
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true );
// domain literals also need to work
checkGetNameAndEmail( "Matt Douhan <matt@[123.123.123.123]>", "Matt Douhan", "matt@[123.123.123.123]", true );
// No '@'
checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true );
// To many @'s
checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" );
// To few @'s
checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" );
// An empty string
checkIsValidEmailAddress( QString::null , "AddressEmpty" );
// email address starting with a @
checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" );
// make sure that starting @ and an additional @ in the same email address don't conflict
// trap the starting @ first and break
checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" );
// email address ending with a @
checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" );
// make sure that ending with@ and an additional @ in the email address don't conflict
checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" );
// unbalanced Parens
checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" );
// unbalanced Parens the other way around
checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" );
// Correct parens just to make sure it works
checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" );
// Check that anglebrackets are closed
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" );
// Check that angle brackets are closed the other way around
checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" );
// Check that angle brackets are closed the other way around, and anglebrackets in domainpart
// instead of local part
// checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" );
// check that a properly formated anglebrackets situation is OK
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" );
// a full email address with comments angle brackets and the works should be valid too
checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" );
// Double quotes
checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" );
// Double quotes inside parens
checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" );
// Parens inside double quotes
checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" );
// Space in email
checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" );
// @ is allowed inisde doublequotes
checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" );
// a , inside a double quoted string is OK, how do I know this? well Ingo says so
// and it makes sense since it is also a seperator of email addresses
checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" );
// Domains literals also need to work
checkIsValidEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "AddressOk" );
// checks for "pure" email addresses in the form of xxx@yyy.tld
checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" );
// non-ASCII char as first char of IDN
checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123]", "true" );
checkIsValidSimpleEmailAddress( "\"matt\"@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( "-matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( "\"-matt\"@fruitsalad.org", "true" );
// check if the pure email address is wrong
checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123", "false" );
checkIsValidSimpleEmailAddress( "matt@123.123.123.123]", "false" );
checkIsValidSimpleEmailAddress( "\"matt@fruitsalad.org", "false" );
checkIsValidSimpleEmailAddress( "matt\"@fruitsalad.org", "false" );
// and here some insane but still valid cases
checkIsValidSimpleEmailAddress( "\"m@tt\"@fruitsalad.org", "true" );
printf("\nTest OK !\n");
return 0;
}
<commit_msg>Updated to also check for "m@tt"@jongel.org<commit_after>/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
// Test program for libkdepim/email.h
#include "email.h"
#include <kcmdlineargs.h>
#include <kapplication.h>
#include <kdebug.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
using namespace KPIM;
static bool check(const QString& txt, const QString& a, const QString& b)
{
if (a == b) {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
}
else {
kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
exit(1);
}
return true;
}
static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal)
{
QString name, email;
bool retVal = KPIM::getNameAndMail(input, name, email);
check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" );
check( "getNameAndMail " + input + " name", name, expName );
check( "getNameAndMail " + input + " email", email, expEmail );
return true;
}
// convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice
static QString emailTestParseResultToString( EmailParseResult errorCode )
{
if( errorCode == TooManyAts ) {
return "TooManyAts";
} else if( errorCode == TooFewAts ) {
return "TooFewAts";
} else if( errorCode == AddressEmpty ) {
return "AddressEmpty";
} else if( errorCode == MissingLocalPart ) {
return "MissingLocalPart";
} else if( errorCode == MissingDomainPart ) {
return "MissingDomainPart";
} else if( errorCode == UnbalancedParens ) {
return "UnbalancedParens";
} else if( errorCode == AddressOk ) {
return "AddressOk";
} else if( errorCode == UnclosedAngleAddr ) {
return "UnclosedAngleAddr";
} else if( errorCode == UnexpectedEnd ) {
return "UnexpectedEnd";
} else if( errorCode == UnopenedAngleAddr ) {
return "UnopenedAngleAddr";
}
return "unknown errror code";
}
static QString simpleEmailTestParseResultToString( bool validEmail )
{
if ( validEmail ) {
return "true";
} else if ( !validEmail ) {
return "false";
}
}
static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode )
{
EmailParseResult errorCode = KPIM::isValidEmailAddress( input );
QString errorC = emailTestParseResultToString( errorCode );
check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode );
return true;
}
static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult )
{
bool validEmail = KPIM::isValidSimpleEmailAddress( input );
QString result = simpleEmailTestParseResultToString( validEmail );
check( "isValidSimpleEmailAddress " + input + " result ", result, expResult );
return true;
}
int main(int argc, char *argv[])
{
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 );
KApplication app( false, false );
// Empty input
checkGetNameAndEmail( QString::null, QString::null, QString::null, false );
// Email only
checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false );
// Normal case
checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true );
// Double-quotes
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true );
// Parenthesis
checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true );
checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513
// Double-quotes inside parenthesis
checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true );
checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true );
// Parenthesis inside double-quotes
checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true );
checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true );
// Space in email
checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true );
// Check that '@' in name doesn't confuse it
checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true );
// Interestingly, this isn't supported.
//checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true );
// While typing, when there's no '@' yet
checkGetNameAndEmail( "foo", "foo", QString::null, false );
checkGetNameAndEmail( "foo <", "foo", QString::null, false );
checkGetNameAndEmail( "foo <b", "foo", "b", true );
// If multiple emails are there, only return the first one
checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true );
// domain literals also need to work
checkGetNameAndEmail( "Matt Douhan <matt@[123.123.123.123]>", "Matt Douhan", "matt@[123.123.123.123]", true );
// No '@'
checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true );
// To many @'s
checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" );
// To few @'s
checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" );
// An empty string
checkIsValidEmailAddress( QString::null , "AddressEmpty" );
// email address starting with a @
checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" );
// make sure that starting @ and an additional @ in the same email address don't conflict
// trap the starting @ first and break
checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" );
// email address ending with a @
checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" );
// make sure that ending with@ and an additional @ in the email address don't conflict
checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" );
// unbalanced Parens
checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" );
// unbalanced Parens the other way around
checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" );
// Correct parens just to make sure it works
checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" );
// Check that anglebrackets are closed
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" );
// Check that angle brackets are closed the other way around
checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" );
// Check that angle brackets are closed the other way around, and anglebrackets in domainpart
// instead of local part
// checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" );
// check that a properly formated anglebrackets situation is OK
checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" );
// a full email address with comments angle brackets and the works should be valid too
checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" );
// Double quotes
checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" );
// Double quotes inside parens
checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" );
// Parens inside double quotes
checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" );
// Space in email
checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" );
// @ is allowed inisde doublequotes
checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" );
// a , inside a double quoted string is OK, how do I know this? well Ingo says so
// and it makes sense since it is also a seperator of email addresses
checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" );
// Domains literals also need to work
checkIsValidEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "AddressOk" );
// Some more insane tests but still valid so they must work
checkIsValidEmailAddress( "Matt Douhan <\"m@att\"@jongel.com>", "AddressOk" );
// checks for "pure" email addresses in the form of xxx@yyy.tld
checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" );
// non-ASCII char as first char of IDN
checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123]", "true" );
checkIsValidSimpleEmailAddress( "\"matt\"@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( "-matt@fruitsalad.org", "true" );
checkIsValidSimpleEmailAddress( "\"-matt\"@fruitsalad.org", "true" );
// check if the pure email address is wrong
checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" );
checkIsValidSimpleEmailAddress( "matt@[123.123.123.123", "false" );
checkIsValidSimpleEmailAddress( "matt@123.123.123.123]", "false" );
checkIsValidSimpleEmailAddress( "\"matt@fruitsalad.org", "false" );
checkIsValidSimpleEmailAddress( "matt\"@fruitsalad.org", "false" );
// and here some insane but still valid cases
checkIsValidSimpleEmailAddress( "\"m@tt\"@fruitsalad.org", "true" );
printf("\nTest OK !\n");
return 0;
}
<|endoftext|> |
<commit_before>/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <uuid/uuid.h>
#include <fstream>
#include "FlowController.h"
#include "unit/ProvenanceTestHelper.h"
#include "core/logging/LogAppenders.h"
#include "core/logging/BaseLogger.h"
#include "processors/GetFile.h"
#include "core/core.h"
#include "core/FlowFile.h"
#include "core/Processor.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
#include "core/ProcessorNode.h"
int main(int argc, char **argv)
{
std::ostringstream oss;
std::unique_ptr<logging::BaseLogger> outputLogger = std::unique_ptr<
logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::OutputStreamAppender(oss,
0));
std::shared_ptr<logging::Logger> logger = logging::Logger::getLogger();
logger->updateLogger(std::move(outputLogger));
outputLogger = std::unique_ptr<logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::NullAppender());
logger->updateLogger(std::move(outputLogger));
std::shared_ptr<core::Processor> processor = std::make_shared<
org::apache::nifi::minifi::processors::ExecuteProcess>("executeProcess");
processor->setMaxConcurrentTasks(1);
std::shared_ptr<core::Repository> test_repo =
std::make_shared<TestRepository>();
std::shared_ptr<TestRepository> repo =
std::static_pointer_cast<TestRepository>(test_repo);
std::shared_ptr<minifi::FlowController> controller = std::make_shared<
TestFlowController>(test_repo, test_repo);
uuid_t processoruuid;
assert(true == processor->getUUID(processoruuid));
std::shared_ptr<minifi::Connection> connection = std::make_shared<
minifi::Connection>(test_repo, "executeProcessConnection");
connection->setRelationship(core::Relationship("success", "description"));
// link the connections so that we can test results at the end for this
connection->setSource(processor);
connection->setDestination(processor);
connection->setSourceUUID(processoruuid);
connection->setDestinationUUID(processoruuid);
processor->addConnection(connection);
assert(processor->getName() == "executeProcess");
std::shared_ptr<core::FlowFile> record;
processor->setScheduledState(core::ScheduledState::RUNNING);
processor->initialize();
std::atomic<bool> is_ready(false);
std::vector<std::thread> processor_workers;
core::ProcessorNode node2(processor);
std::shared_ptr<core::ProcessContext> contextset = std::make_shared<
core::ProcessContext>(node2, test_repo);
core::ProcessSessionFactory factory(contextset.get());
processor->onSchedule(contextset.get(), &factory);
for (int i = 0; i < 1; i++) {
//
processor_workers.push_back(
std::thread(
[processor,test_repo,&is_ready]()
{
core::ProcessorNode node(processor);
std::shared_ptr<core::ProcessContext> context = std::make_shared<core::ProcessContext>(node, test_repo);
context->setProperty(org::apache::nifi::minifi::processors::ExecuteProcess::Command,"sleep 0.5");
//context->setProperty(org::apache::nifi::minifi::processors::ExecuteProcess::CommandArguments," 1 >>" + ss.str());
std::shared_ptr<core::ProcessSession> session = std::make_shared<core::ProcessSession>(context.get());
while(!is_ready.load(std::memory_order_relaxed)) {
}
processor->onTrigger(context.get(), session.get());
}));
}
is_ready.store(true, std::memory_order_relaxed);
//is_ready.store(true);
std::for_each(processor_workers.begin(), processor_workers.end(),
[](std::thread &t)
{
t.join();
});
outputLogger = std::unique_ptr<logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::NullAppender());
logger->updateLogger(std::move(outputLogger));
std::shared_ptr<org::apache::nifi::minifi::processors::ExecuteProcess> execp =
std::static_pointer_cast<
org::apache::nifi::minifi::processors::ExecuteProcess>(processor);
}
<commit_msg>MINIFI-254 Adjusting issue with casing in TestExecuteProcess from merge of linter updates.<commit_after>/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <uuid/uuid.h>
#include <fstream>
#include "FlowController.h"
#include "unit/ProvenanceTestHelper.h"
#include "core/logging/LogAppenders.h"
#include "core/logging/BaseLogger.h"
#include "processors/GetFile.h"
#include "core/Core.h"
#include "core/FlowFile.h"
#include "core/Processor.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
#include "core/ProcessorNode.h"
int main(int argc, char **argv)
{
std::ostringstream oss;
std::unique_ptr<logging::BaseLogger> outputLogger = std::unique_ptr<
logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::OutputStreamAppender(oss,
0));
std::shared_ptr<logging::Logger> logger = logging::Logger::getLogger();
logger->updateLogger(std::move(outputLogger));
outputLogger = std::unique_ptr<logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::NullAppender());
logger->updateLogger(std::move(outputLogger));
std::shared_ptr<core::Processor> processor = std::make_shared<
org::apache::nifi::minifi::processors::ExecuteProcess>("executeProcess");
processor->setMaxConcurrentTasks(1);
std::shared_ptr<core::Repository> test_repo =
std::make_shared<TestRepository>();
std::shared_ptr<TestRepository> repo =
std::static_pointer_cast<TestRepository>(test_repo);
std::shared_ptr<minifi::FlowController> controller = std::make_shared<
TestFlowController>(test_repo, test_repo);
uuid_t processoruuid;
assert(true == processor->getUUID(processoruuid));
std::shared_ptr<minifi::Connection> connection = std::make_shared<
minifi::Connection>(test_repo, "executeProcessConnection");
connection->setRelationship(core::Relationship("success", "description"));
// link the connections so that we can test results at the end for this
connection->setSource(processor);
connection->setDestination(processor);
connection->setSourceUUID(processoruuid);
connection->setDestinationUUID(processoruuid);
processor->addConnection(connection);
assert(processor->getName() == "executeProcess");
std::shared_ptr<core::FlowFile> record;
processor->setScheduledState(core::ScheduledState::RUNNING);
processor->initialize();
std::atomic<bool> is_ready(false);
std::vector<std::thread> processor_workers;
core::ProcessorNode node2(processor);
std::shared_ptr<core::ProcessContext> contextset = std::make_shared<
core::ProcessContext>(node2, test_repo);
core::ProcessSessionFactory factory(contextset.get());
processor->onSchedule(contextset.get(), &factory);
for (int i = 0; i < 1; i++) {
//
processor_workers.push_back(
std::thread(
[processor,test_repo,&is_ready]()
{
core::ProcessorNode node(processor);
std::shared_ptr<core::ProcessContext> context = std::make_shared<core::ProcessContext>(node, test_repo);
context->setProperty(org::apache::nifi::minifi::processors::ExecuteProcess::Command,"sleep 0.5");
//context->setProperty(org::apache::nifi::minifi::processors::ExecuteProcess::CommandArguments," 1 >>" + ss.str());
std::shared_ptr<core::ProcessSession> session = std::make_shared<core::ProcessSession>(context.get());
while(!is_ready.load(std::memory_order_relaxed)) {
}
processor->onTrigger(context.get(), session.get());
}));
}
is_ready.store(true, std::memory_order_relaxed);
//is_ready.store(true);
std::for_each(processor_workers.begin(), processor_workers.end(),
[](std::thread &t)
{
t.join();
});
outputLogger = std::unique_ptr<logging::BaseLogger>(
new org::apache::nifi::minifi::core::logging::NullAppender());
logger->updateLogger(std::move(outputLogger));
std::shared_ptr<org::apache::nifi::minifi::processors::ExecuteProcess> execp =
std::static_pointer_cast<
org::apache::nifi::minifi::processors::ExecuteProcess>(processor);
}
<|endoftext|> |
<commit_before>/*
** network_client.hpp
** Login : <ctaf42@donnetout>
** Started on Thu Feb 2 11:59:48 2012 Cedric GESTES
** $Id$
**
** Author(s):
** - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Cedric GESTES
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** 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
*/
#ifndef NETWORK_CLIENT_HPP_
# define NETWORK_CLIENT_HPP_
#include <qimessaging/transport/transport_socket.hpp>
#include <vector>
#include <string>
namespace qi {
class NetworkThread;
class MachineInfo {
public:
std::string uuid;
};
class Broker : public qi::TransportSocketDelegate {
public:
Broker();
virtual ~Broker();
void setThread(qi::NetworkThread *n);
void onConnected(const qi::Message &msg);
void onWrite(const qi::Message &msg);
void onRead(const qi::Message &msg);
void connect(const std::string masterAddress);
bool disconnect();
bool waitForConnected(int msecs = 30000);
bool waitForDisconnected(int msecs = 30000);
void registerMachine(const qi::MachineInfo& m);
void unregisterMachine(const qi::MachineInfo& m);
std::vector<std::string> machines();
bool isInitialized() const;
protected:
std::string _masterAddress;
bool _isInitialized;
qi::NetworkThread *nthd;
qi::TransportSocket *tc;
};
}
#endif /* !NETWORK_CLIENT_PP_ */
<commit_msg>Add ServiceInfo and EndpointInfo<commit_after>/*
** network_client.hpp
** Login : <ctaf42@donnetout>
** Started on Thu Feb 2 11:59:48 2012 Cedric GESTES
** $Id$
**
** Author(s):
** - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Cedric GESTES
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** 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
*/
#ifndef NETWORK_CLIENT_HPP_
# define NETWORK_CLIENT_HPP_
#include <qimessaging/transport/transport_socket.hpp>
#include <qimessaging/datastream.hpp>
#include <vector>
#include <string>
namespace qi {
class NetworkThread;
class MachineInfo {
public:
std::string uuid;
};
class EndpointInfo {
public:
int port;
std::string ip;
std::string type;
bool operator==(const EndpointInfo &b) const
{
if (port == b.port &&
ip == b.ip &&
type == b.type)
return true;
return false;
}
};
static DataStream& operator<<(DataStream &d, const EndpointInfo &e)
{
d << e.ip;
d << e.port;
d << e.type;
return d;
}
static DataStream& operator>>(DataStream &d, EndpointInfo &e)
{
d >> e.ip;
d >> e.port;
d >> e.type;
return d;
}
class ServiceInfo {
public:
std::string name;
std::vector<qi::EndpointInfo> endpoint;
};
class Broker : public qi::TransportSocketDelegate {
public:
Broker();
virtual ~Broker();
void setThread(qi::NetworkThread *n);
void onConnected(const qi::Message &msg);
void onWrite(const qi::Message &msg);
void onRead(const qi::Message &msg);
void connect(const std::string masterAddress);
bool disconnect();
bool waitForConnected(int msecs = 30000);
bool waitForDisconnected(int msecs = 30000);
void registerMachine(const qi::MachineInfo& m);
void unregisterMachine(const qi::MachineInfo& m);
std::vector<std::string> machines();
bool isInitialized() const;
protected:
std::string _masterAddress;
bool _isInitialized;
qi::NetworkThread *nthd;
qi::TransportSocket *tc;
};
}
#endif /* !NETWORK_CLIENT_PP_ */
<|endoftext|> |
<commit_before>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
namespace math {
template<typename T>
struct toms748_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename T>
struct bisect_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::bisect(Fn, a, b, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; });
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while (minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if (Ans.first < maxval) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval) {
*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator stable_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval && FnVal<0) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root_with_stability(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator stable_root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return stable_root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
}
}
#
#endif
<commit_msg>Fix: bisect did not use max_iter.<commit_after>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
namespace math {
template<typename T>
struct toms748_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename T>
struct bisect_root_stepper {
using value_type = T;
private:
value_type step;
value_type error;
public:
bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
template<typename fn, typename ans_type>
std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
value_type a = start;
ans_type fa = startFnVal;
while(a < end) {
auto b = std::min(a + step, end);
auto fb = Fn(b);
if(fb == 0) {
start = b;
startFnVal = fb;
return std::make_pair(b, b);
} else if(fa * fb < 0.0) {
boost::uintmax_t max_iter = 128;
auto ans = boost::math::tools::bisect(Fn, a, b, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; },max_iter);
start = b;
startFnVal = fb;
return ans;
}
a = b;
fa = fb;
}
start = a;
startFnVal = fa;
return std::make_pair(a, a);
}
void reset(value_type step_, value_type error_) {
step = step_;
error = error_;
}
};
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while (minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if (Ans.first < maxval) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval) {
*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
}
}
return out;
}
template<typename root_stepper, typename fn, typename T, typename output_iterator>
output_iterator stable_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
auto FnVal = Fn(minval);
while(minval<maxval) {
auto Ans = Stepper(Fn, minval, FnVal, maxval);
if(Ans.first < maxval && FnVal<0) {
*(out++) = (Ans.first + Ans.second) / 2.0;
}
}
return out;
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return root_with_stability(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
template<typename fn, typename T, typename output_iterator>
output_iterator stable_root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
toms748_root_stepper<T> Stepper(step, error);
return stable_root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
}
}
}
#
#endif
<|endoftext|> |
<commit_before>#include <mbed.h>
DigitalOut OE(P0_13, 1);
BusOut SEL(P0_7, P0_6);
/*
InterruptIn SW1(P0_3);
InterruptIn SW2(P0_2);
InterruptIn SW3(P0_11);
InterruptIn SW4(P0_10);
*/
InterruptIn SW1(P0_8);
InterruptIn SW2(P0_1);
InterruptIn SW3(P0_9);
InterruptIn SW4(P0_10);
BusOut LSEL(P0_3, P0_2);
// Setup the Serial to the PC for debugging
Serial pc(P0_4, P0_0);
void SW1_int() {
OE = 1;
SEL = 0;
LSEL = 0;
OE = 0;
pc.printf("SW1\n\r");
}
void SW2_int() {
OE = 1;
SEL = 1;
LSEL = 1;
OE = 0;
pc.printf("SW2\n\r");
}
void SW3_int() {
OE = 1;
SEL = 2;
LSEL = 2;
OE = 0;
pc.printf("SW3\n\r");
}
void SW4_int() {
OE = 1;
SEL = 3;
LSEL = 3;
OE = 0;
pc.printf("SW4\n\r");
}
int main() {
pc.baud(57600);
pc.printf("\nHello from USB4x3HUB \n\r");
OE = 1;
SEL = 0;
LSEL = 0;
OE = 0;
SW1.fall(&SW1_int);
SW1.mode(PullUp);
SW2.fall(&SW2_int);
SW2.mode(PullUp);
SW3.fall(&SW3_int);
SW3.mode(PullUp);
SW4.fall(&SW4_int);
SW4.mode(PullUp);
while (1) {
wait(5);
pc.printf(".");
}
}
<commit_msg>[ MBED ] remove comments<commit_after>#include <mbed.h>
DigitalOut OE(P0_13, 1);
BusOut SEL(P0_7, P0_6);
InterruptIn SW1(P0_8);
InterruptIn SW2(P0_1);
InterruptIn SW3(P0_9);
InterruptIn SW4(P0_10);
BusOut LSEL(P0_3, P0_2);
// Setup the Serial to the PC for debugging
Serial pc(P0_4, P0_0);
void SW1_int() {
OE = 1;
SEL = 0;
LSEL = 0;
OE = 0;
pc.printf("SW1\n\r");
}
void SW2_int() {
OE = 1;
SEL = 1;
LSEL = 1;
OE = 0;
pc.printf("SW2\n\r");
}
void SW3_int() {
OE = 1;
SEL = 2;
LSEL = 2;
OE = 0;
pc.printf("SW3\n\r");
}
void SW4_int() {
OE = 1;
SEL = 3;
LSEL = 3;
OE = 0;
pc.printf("SW4\n\r");
}
int main() {
pc.baud(57600);
pc.printf("\nHello from USB4x3HUB \n\r");
OE = 1;
SEL = 0;
LSEL = 0;
OE = 0;
SW1.fall(&SW1_int);
SW1.mode(PullUp);
SW2.fall(&SW2_int);
SW2.mode(PullUp);
SW3.fall(&SW3_int);
SW3.mode(PullUp);
SW4.fall(&SW4_int);
SW4.mode(PullUp);
while (1) {
wait(5);
pc.printf(".");
}
}
<|endoftext|> |
<commit_before>#include "md_parser.hpp"
#include "text_line_element.hpp"
#include "text_paragraph.hpp"
#include "title1_paragraph.hpp"
#include "title2_paragraph.hpp"
#include "ulist1_paragraph.hpp"
using namespace std;
namespace {
bool string_has_only(const std::string & s, const char & c) {
return (s.find_first_not_of(c) == std::string::npos);
}
template<class T>
T max(const T & a, const T & b) {
if (a > b) {
return a;
} else {
return b;
}
}
size_t string_startswith(const std::string & s, const char & c) {
size_t i(0);
while (s[i] == c and i < s.length()){
++i;
}
return i;
}
bool string_startswith(const std::string & s, const std::string & c) {
if (s.length() < c.length()) {
return false;
}
size_t i(0);
while (s[i] == c[i] and i < c.length() ){
++i;
}
if (i != c.length()) {
return false;
}
return true;
}
std::string string_clear_leading(const std::string & s, const std::string & subset) {
return s.substr(s.find_first_not_of(subset));
}
};
MdParser::MdParser(const std::string & filename) :
Parser(filename) {
parse();
}
MdParser::~MdParser() {
// dtor
}
void MdParser::parse() {
std::string line;
_document = new Document(_filename);
Paragraph *p0(nullptr), *p1(nullptr);
LineElement *e = nullptr, *last_e = nullptr;
size_t sharps(0);
while (getline(_input_file, line)) {
if (line.empty()) {
// end of line, change paragraph
if (p0) {
_document->append_paragraph(p0);
}
p0 = new TextParagraph();
} else {
sharps = string_startswith(line, '#');
if (!p0) {
p0 = new TextParagraph();
}
if (sharps != 0) {
switch(sharps) {
case 1:
delete p0;
p0 = new Title1Paragraph();
break;
case 2:
delete p0;
p0 = new Title2Paragraph();
break;
default:
break;
}
e = new TextLineElement(string_clear_leading(line," \t#"));
p0->append_line_element(e);
} else if (string_has_only(line, '=')) { // title 1 delimiter
p1 = new Title1Paragraph(p0);
delete p0;
p0 = nullptr;
_document->append_paragraph(p1);
p1 = nullptr;
} else if (string_has_only(line, '-')) { // title 2 delimiter
p1 = new Title2Paragraph(p0);
delete p0;
p0 = nullptr;
_document->append_paragraph(p1);
p1 = nullptr;
} else if (string_startswith(line, "* ")) { // level 1 list delimiter
delete p0;
p0 = new UList1Paragraph();
e = new TextLineElement(string_clear_leading(line,"* \t#"));
p0->append_line_element(e);
} else {
// other content
if (p0->size() && last_e && (last_e->content()).back() != ' ' && line.front() != ' ') {
line = " "+line;
}
e = new TextLineElement(line);
p0->append_line_element(e);
last_e = e;
e = nullptr;
}
}
}
if (p0) {
_document->append_paragraph(p0);
}
}
<commit_msg>Fix unnumbered list printing multiple instances<commit_after>#include "md_parser.hpp"
#include "text_line_element.hpp"
#include "text_paragraph.hpp"
#include "title1_paragraph.hpp"
#include "title2_paragraph.hpp"
#include "ulist1_paragraph.hpp"
using namespace std;
namespace {
bool string_has_only(const std::string & s, const char & c) {
return (s.find_first_not_of(c) == std::string::npos);
}
template<class T>
T max(const T & a, const T & b) {
if (a > b) {
return a;
} else {
return b;
}
}
size_t string_startswith(const std::string & s, const char & c) {
size_t i(0);
while (s[i] == c and i < s.length()){
++i;
}
return i;
}
bool string_startswith(const std::string & s, const std::string & c) {
if (s.length() < c.length()) {
return false;
}
size_t i(0);
while (s[i] == c[i] and i < c.length() ){
++i;
}
if (i != c.length()) {
return false;
}
return true;
}
std::string string_clear_leading(const std::string & s, const std::string & subset) {
return s.substr(s.find_first_not_of(subset));
}
};
MdParser::MdParser(const std::string & filename) :
Parser(filename) {
parse();
}
MdParser::~MdParser() {
// dtor
}
void MdParser::parse() {
std::string line;
_document = new Document(_filename);
Paragraph *p0(nullptr), *p1(nullptr);
LineElement *e = nullptr, *last_e = nullptr;
size_t sharps(0);
while (getline(_input_file, line)) {
if (line.empty()) {
// end of line, change paragraph
if (p0 and p0->size()) {
_document->append_paragraph(p0);
p0 = nullptr;
}
p0 = new TextParagraph();
} else {
sharps = string_startswith(line, '#');
if (!p0) {
p0 = new TextParagraph();
}
if (sharps != 0) {
switch(sharps) {
case 1:
delete p0;
p0 = new Title1Paragraph();
break;
case 2:
delete p0;
p0 = new Title2Paragraph();
break;
default:
break;
}
e = new TextLineElement(string_clear_leading(line," \t#"));
p0->append_line_element(e);
} else if (string_has_only(line, '=')) { // title 1 delimiter
p1 = new Title1Paragraph(p0);
delete p0;
p0 = nullptr;
_document->append_paragraph(p1);
p1 = nullptr;
} else if (string_has_only(line, '-')) { // title 2 delimiter
p1 = new Title2Paragraph(p0);
delete p0;
p0 = nullptr;
_document->append_paragraph(p1);
p1 = nullptr;
} else if (string_startswith(line, "* ")) { // level 1 list delimiter
if (p0 and p0->size()) {
_document->append_paragraph(p0);
delete p0;
}
p0 = new UList1Paragraph();
e = new TextLineElement(string_clear_leading(line,"* \t#"));
p0->append_line_element(e);
} else {
// other content
if (p0->size() && last_e && (last_e->content()).back() != ' ' && line.front() != ' ') {
line = " "+line;
}
e = new TextLineElement(line);
p0->append_line_element(e);
last_e = e;
e = nullptr;
}
}
}
if (p0 and p0->size()) {
_document->append_paragraph(p0);
}
}
<|endoftext|> |
<commit_before>/*
* 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 Library 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.
*
* SelectServerTest.cpp
* Test fixture for the Socket classes
* Copyright (C) 2005-2008 Simon Newton
*/
#include <cppunit/extensions/HelperMacros.h>
#include "ola/Clock.h"
#include "ola/ExportMap.h"
#include "ola/Closure.h"
#include "ola/network/SelectServer.h"
#include "ola/network/Socket.h"
using ola::ExportMap;
using ola::IntegerVariable;
using ola::network::LoopbackSocket;
using ola::network::SelectServer;
using ola::network::UdpSocket;
class SelectServerTest: public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SelectServerTest);
CPPUNIT_TEST(testAddRemoveSocket);
CPPUNIT_TEST(testTimeout);
CPPUNIT_TEST(testLoopClosures);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void testAddRemoveSocket();
void testTimeout();
void testLoopClosures();
void FatalTimeout() {
CPPUNIT_ASSERT(false);
}
void TerminateTimeout() {
if (m_ss) { m_ss->Terminate(); }
}
void SingleIncrementTimeout() { m_timeout_counter++; }
bool IncrementTimeout() {
m_timeout_counter++;
return true;
}
void IncrementLoopCounter() { m_loop_counter++; }
private:
unsigned int m_timeout_counter;
unsigned int m_loop_counter;
ExportMap *m_map;
SelectServer *m_ss;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SelectServerTest);
void SelectServerTest::setUp() {
m_map = new ExportMap();
m_ss = new SelectServer(m_map);
m_timeout_counter = 0;
m_loop_counter = 0;
}
void SelectServerTest::tearDown() {
delete m_ss;
delete m_map;
}
/*
* Check AddSocket/RemoveSocket works correctly and that the export map is
* updated.
*/
void SelectServerTest::testAddRemoveSocket() {
LoopbackSocket bad_socket;
IntegerVariable *connected_socket_count =
m_map->GetIntegerVar(SelectServer::K_CONNECTED_SOCKET_VAR);
IntegerVariable *socket_count =
m_map->GetIntegerVar(SelectServer::K_SOCKET_VAR);
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// adding and removin a non-connected socket should fail
CPPUNIT_ASSERT(!m_ss->AddSocket(&bad_socket));
CPPUNIT_ASSERT(!m_ss->RemoveSocket(&bad_socket));
LoopbackSocket loopback_socket;
loopback_socket.Init();
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
CPPUNIT_ASSERT(m_ss->AddSocket(&loopback_socket));
// Adding a second time should fail
CPPUNIT_ASSERT(!m_ss->AddSocket(&loopback_socket));
CPPUNIT_ASSERT_EQUAL(1, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// Add a udp socket
UdpSocket udp_socket;
CPPUNIT_ASSERT(udp_socket.Init());
CPPUNIT_ASSERT(m_ss->AddSocket(&udp_socket));
CPPUNIT_ASSERT(!m_ss->AddSocket(&udp_socket));
CPPUNIT_ASSERT_EQUAL(1, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(1, socket_count->Get());
// Check remove works
CPPUNIT_ASSERT(m_ss->RemoveSocket(&loopback_socket));
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(1, socket_count->Get());
CPPUNIT_ASSERT(m_ss->RemoveSocket(&udp_socket));
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// Remove again should fail
CPPUNIT_ASSERT(!m_ss->RemoveSocket(&loopback_socket));
}
/*
* Timeout tests
*/
void SelectServerTest::testTimeout() {
// check a single timeout
m_ss->RegisterSingleTimeout(
10,
ola::NewSingleClosure(this, &SelectServerTest::SingleIncrementTimeout));
m_ss->RegisterSingleTimeout(
20,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Run();
CPPUNIT_ASSERT_EQUAL((unsigned int) 1, m_timeout_counter);
// check repeating timeouts
m_timeout_counter = 0;
m_ss->RegisterRepeatingTimeout(
10,
ola::NewClosure(this, &SelectServerTest::IncrementTimeout));
m_ss->RegisterSingleTimeout(
98,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Restart();
m_ss->Run();
// Some systems have bad timing and only do 8 ticks here
//CPPUNIT_ASSERT(m_timeout_counter == 8 || m_timeout_counter == 9);
// check timeouts are removed correctly
ola::network::timeout_id timeout1 = m_ss->RegisterSingleTimeout(
10,
ola::NewSingleClosure(this, &SelectServerTest::FatalTimeout));
m_ss->RegisterSingleTimeout(
20,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->RemoveTimeout(timeout1);
m_ss->Restart();
m_ss->Run();
}
/*
* Check that the loop closures are called
*/
void SelectServerTest::testLoopClosures() {
m_ss->SetDefaultInterval(ola::TimeInterval(0, 100000)); // poll every 100ms
m_ss->RunInLoop(ola::NewClosure(this,
&SelectServerTest::IncrementLoopCounter));
m_ss->RegisterSingleTimeout(
500,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Run();
// we should have at least 5 calls to IncrementLoopCounter
CPPUNIT_ASSERT(m_loop_counter >= 5);
}
<commit_msg> * remove the mistake<commit_after>/*
* 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 Library 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.
*
* SelectServerTest.cpp
* Test fixture for the Socket classes
* Copyright (C) 2005-2008 Simon Newton
*/
#include <cppunit/extensions/HelperMacros.h>
#include "ola/Clock.h"
#include "ola/ExportMap.h"
#include "ola/Closure.h"
#include "ola/network/SelectServer.h"
#include "ola/network/Socket.h"
using ola::ExportMap;
using ola::IntegerVariable;
using ola::network::LoopbackSocket;
using ola::network::SelectServer;
using ola::network::UdpSocket;
class SelectServerTest: public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SelectServerTest);
CPPUNIT_TEST(testAddRemoveSocket);
CPPUNIT_TEST(testTimeout);
CPPUNIT_TEST(testLoopClosures);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void testAddRemoveSocket();
void testTimeout();
void testLoopClosures();
void FatalTimeout() {
CPPUNIT_ASSERT(false);
}
void TerminateTimeout() {
if (m_ss) { m_ss->Terminate(); }
}
void SingleIncrementTimeout() { m_timeout_counter++; }
bool IncrementTimeout() {
m_timeout_counter++;
return true;
}
void IncrementLoopCounter() { m_loop_counter++; }
private:
unsigned int m_timeout_counter;
unsigned int m_loop_counter;
ExportMap *m_map;
SelectServer *m_ss;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SelectServerTest);
void SelectServerTest::setUp() {
m_map = new ExportMap();
m_ss = new SelectServer(m_map);
m_timeout_counter = 0;
m_loop_counter = 0;
}
void SelectServerTest::tearDown() {
delete m_ss;
delete m_map;
}
/*
* Check AddSocket/RemoveSocket works correctly and that the export map is
* updated.
*/
void SelectServerTest::testAddRemoveSocket() {
LoopbackSocket bad_socket;
IntegerVariable *connected_socket_count =
m_map->GetIntegerVar(SelectServer::K_CONNECTED_SOCKET_VAR);
IntegerVariable *socket_count =
m_map->GetIntegerVar(SelectServer::K_SOCKET_VAR);
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// adding and removin a non-connected socket should fail
CPPUNIT_ASSERT(!m_ss->AddSocket(&bad_socket));
CPPUNIT_ASSERT(!m_ss->RemoveSocket(&bad_socket));
LoopbackSocket loopback_socket;
loopback_socket.Init();
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
CPPUNIT_ASSERT(m_ss->AddSocket(&loopback_socket));
// Adding a second time should fail
CPPUNIT_ASSERT(!m_ss->AddSocket(&loopback_socket));
CPPUNIT_ASSERT_EQUAL(1, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// Add a udp socket
UdpSocket udp_socket;
CPPUNIT_ASSERT(udp_socket.Init());
CPPUNIT_ASSERT(m_ss->AddSocket(&udp_socket));
CPPUNIT_ASSERT(!m_ss->AddSocket(&udp_socket));
CPPUNIT_ASSERT_EQUAL(1, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(1, socket_count->Get());
// Check remove works
CPPUNIT_ASSERT(m_ss->RemoveSocket(&loopback_socket));
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(1, socket_count->Get());
CPPUNIT_ASSERT(m_ss->RemoveSocket(&udp_socket));
CPPUNIT_ASSERT_EQUAL(0, connected_socket_count->Get());
CPPUNIT_ASSERT_EQUAL(0, socket_count->Get());
// Remove again should fail
CPPUNIT_ASSERT(!m_ss->RemoveSocket(&loopback_socket));
}
/*
* Timeout tests
*/
void SelectServerTest::testTimeout() {
// check a single timeout
m_ss->RegisterSingleTimeout(
10,
ola::NewSingleClosure(this, &SelectServerTest::SingleIncrementTimeout));
m_ss->RegisterSingleTimeout(
20,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Run();
CPPUNIT_ASSERT_EQUAL((unsigned int) 1, m_timeout_counter);
// check repeating timeouts
m_timeout_counter = 0;
m_ss->RegisterRepeatingTimeout(
10,
ola::NewClosure(this, &SelectServerTest::IncrementTimeout));
m_ss->RegisterSingleTimeout(
98,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Restart();
m_ss->Run();
// Some systems have bad timing and only do 8 ticks here
CPPUNIT_ASSERT(m_timeout_counter == 8 || m_timeout_counter == 9);
// check timeouts are removed correctly
ola::network::timeout_id timeout1 = m_ss->RegisterSingleTimeout(
10,
ola::NewSingleClosure(this, &SelectServerTest::FatalTimeout));
m_ss->RegisterSingleTimeout(
20,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->RemoveTimeout(timeout1);
m_ss->Restart();
m_ss->Run();
}
/*
* Check that the loop closures are called
*/
void SelectServerTest::testLoopClosures() {
m_ss->SetDefaultInterval(ola::TimeInterval(0, 100000)); // poll every 100ms
m_ss->RunInLoop(ola::NewClosure(this,
&SelectServerTest::IncrementLoopCounter));
m_ss->RegisterSingleTimeout(
500,
ola::NewSingleClosure(this, &SelectServerTest::TerminateTimeout));
m_ss->Run();
// we should have at least 5 calls to IncrementLoopCounter
CPPUNIT_ASSERT(m_loop_counter >= 5);
}
<|endoftext|> |
<commit_before>#ifndef _MATH_ANGLE_HPP
#define _MATH_ANGLE_HPP
#include <cmath>
#include <iosfwd>
#include <type_traits>
namespace math {
template <typename _T>
struct radian_traits {
static_assert(::std::is_floating_point<_T>::value,
"radian_traits<_T> requires floating point type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(3.14159265359);
}
};
template <typename _T>
struct degree_traits {
static_assert(::std::is_arithmetic<_T>::value,
"degree_traits<_T> requires arithmetic type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(180);
}
};
template <typename _T>
struct gradian_traits {
static_assert(::std::is_arithmetic<_T>::value,
"gradian_traits<_T> requires arithmetic type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(200);
}
};
template <typename _T>
struct revolution_traits {
static_assert(::std::is_floating_point<_T>::value,
"revolution_traits<_T> requires floating point type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(0.5);
}
};
template <typename _T, typename _Traits> struct basic_angle;
template <typename _T> using radians = basic_angle<_T, radian_traits<_T>>;
template <typename _T> using degrees = basic_angle<_T, degree_traits<_T>>;
template <typename _T> using gradians = basic_angle<_T, gradian_traits<_T>>;
template <typename _T> using revolutions = basic_angle<_T, revolution_traits<_T>>;
template <
typename _T,
typename _Traits = radian_traits<_T>>
struct basic_angle {
//////////////////////////////////////////////////////////////////////////////
// type definitions.
typedef _Traits traits_type;
typedef _T value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef value_type const* const_pointer;
typedef value_type const& const_reference;
//////////////////////////////////////////////////////////////////////////////
// construction.
constexpr explicit basic_angle(value_type val = static_cast<_T>(0)) noexcept
: _value { val } {}
constexpr basic_angle(basic_angle&&) = default;
constexpr basic_angle(basic_angle const&) = default;
//////////////////////////////////////////////////////////////////////////////
// assignment operators.
basic_angle& operator = (basic_angle&&) = default;
basic_angle& operator = (basic_angle const&) = default;
//////////////////////////////////////////////////////////////////////////////
// accessor methods.
constexpr value_type value() const noexcept {
return _value;
}
//////////////////////////////////////////////////////////////////////////////
// unary arithmetic operators.
constexpr basic_angle operator +() const noexcept {
return basic_angle { _value };
}
constexpr basic_angle operator -() const noexcept {
return basic_angle { -_value };
}
//////////////////////////////////////////////////////////////////////////////
// compound arithmetic operators.
basic_angle& operator ++() noexcept {
++_value;
return *this;
}
basic_angle& operator --() noexcept {
--_value;
return *this;
}
basic_angle operator ++(int) noexcept {
basic_angle tmp(*this); ++*this;
return *this;
}
basic_angle operator --(int) noexcept {
basic_angle tmp(*this); --*this;
return *this;
}
basic_angle& operator += (basic_angle const& other) noexcept {
_value += other._value;
return *this;
}
basic_angle& operator -= (basic_angle const& other) noexcept {
_value -= other._value;
return *this;
}
basic_angle& operator *= (value_type val) noexcept {
_value *= val;
return *this;
}
basic_angle& operator /= (value_type val) noexcept {
_value /= val;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
// conversion operators.
template <typename _Traits2>
constexpr operator basic_angle<_T, _Traits2>() const noexcept {
return _convert<_T, _Traits2>();
}
template <typename _T2, typename _Traits2>
constexpr operator basic_angle<_T2, _Traits2>() const noexcept {
return _convert<_T2, _Traits2>();
}
//////////////////////////////////////////////////////////////////////////////
// streaming operators.
template <typename _CharT, typename _OsTraits>
friend std::basic_ostream<_CharT, _OsTraits>& operator << (std::basic_ostream<_CharT, _OsTraits>& ostr, basic_angle const& angle) {
return ostr << angle._value;
}
template <typename _CharT, typename _IsTraits>
friend std::basic_istream<_CharT, _IsTraits>& operator << (std::basic_istream<_CharT, _IsTraits>& istr, basic_angle& angle) {
return istr >> angle._value;
}
private:
value_type _value;
template <typename _T2, typename _Traits2>
constexpr basic_angle<_T2, _Traits2> _convert() const noexcept {
typedef typename std::common_type<_T, _T2>::type common_t;
return basic_angle<_T2, _Traits2> { static_cast<common_t>(_value) * _Traits2::pi() / _Traits::pi() };
}
};
constexpr const radians<long double> pi = degrees<long double>(180);
//////////////////////////////////////////////////////////////////////////////
// binary arithmetic operators.
template <typename _T1, typename _T2, typename _Traits1, typename _Traits2>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits1> operator + (
basic_angle<_T1, _Traits1> const& lhs, basic_angle<_T2, _Traits2> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits1>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator + (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator + (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits1, typename _Traits2>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits1> operator - (
basic_angle<_T1, _Traits1> const& lhs, basic_angle<_T2, _Traits2> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits1>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator - (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator - (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator * (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) *= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator * (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) { return rhs * lhs; }
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator / (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) /= rhs;
}
//////////////////////////////////////////////////////////////////////////////
// comparison operators.
template <typename _T, typename _Traits>
inline constexpr bool operator == (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) noexcept {
return lhs.value() == rhs.value();
}
template <typename _T, typename _Traits>
inline constexpr bool operator < (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) noexcept {
return lhs.value() < rhs.value();
}
template <typename _T, typename _Traits>
inline constexpr bool operator != (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(lhs == rhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator <= (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(rhs < lhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator >= (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(lhs < rhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator > (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return rhs < lhs;
}
//////////////////////////////////////////////////////////////////////////////
// helper functions.
template <typename _T>
constexpr radians<typename std::common_type<_T, float>::type> rad(_T const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return radians<common_t> { static_cast<common_t>(angle) };
}
template <typename _T>
constexpr revolutions<typename std::common_type<_T, float>::type> revs(_T const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return revolutions<common_t> { static_cast<common_t>(angle) };
}
template <typename _T>
constexpr degrees<_T> deg(_T const& angle) {
return degrees<_T> { angle };
}
template <typename _T>
constexpr gradians<_T> grad(_T const& angle) {
return gradians<_T> { angle };
}
template <typename _T, typename _Traits>
constexpr radians<typename std::common_type<_T, float>::type> rad(basic_angle<_T, _Traits> const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return radians<common_t> { angle };
}
template <typename _T, typename _Traits>
constexpr revolutions<typename std::common_type<_T, float>::type> revs(basic_angle<_T, _Traits> const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return revolutions<common_t> { angle };
}
template <typename _T, typename _Traits>
constexpr degrees<_T> deg(basic_angle<_T, _Traits> const& angle) {
return degrees<_T> { angle };
}
template <typename _T, typename _Traits>
constexpr gradians<_T> grad(basic_angle<_T, _Traits> const& angle) {
return gradians<_T> { angle };
}
}
namespace math {
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type sin(basic_angle<_T, _Traits> const& x) { return std::sin(math::rad(x).value()); }
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type cos(basic_angle<_T, _Traits> const& x) { return std::cos(math::rad(x).value()); }
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type tan(basic_angle<_T, _Traits> const& x) { return std::tan(math::rad(x).value()); }
}
#endif // _MATH_ANGLE_HPP<commit_msg>Use std::acos(-1) for Pi constant in radians<commit_after>#ifndef _MATH_ANGLE_HPP
#define _MATH_ANGLE_HPP
#include <cmath>
#include <iosfwd>
#include <type_traits>
namespace math {
template <typename _T>
struct radian_traits {
static_assert(::std::is_floating_point<_T>::value,
"radian_traits<_T> requires floating point type.");
private:
static constexpr _T _pivalue =
std::acos(static_cast<_T>(-1));
public:
static constexpr _T pi() noexcept {
return _pivalue;
}
};
template <typename _T>
struct degree_traits {
static_assert(::std::is_arithmetic<_T>::value,
"degree_traits<_T> requires arithmetic type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(180);
}
};
template <typename _T>
struct gradian_traits {
static_assert(::std::is_arithmetic<_T>::value,
"gradian_traits<_T> requires arithmetic type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(200);
}
};
template <typename _T>
struct revolution_traits {
static_assert(::std::is_floating_point<_T>::value,
"revolution_traits<_T> requires floating point type.");
static constexpr _T pi() noexcept {
return static_cast<_T>(0.5);
}
};
template <typename _T, typename _Traits> struct basic_angle;
template <typename _T> using radians = basic_angle<_T, radian_traits<_T>>;
template <typename _T> using degrees = basic_angle<_T, degree_traits<_T>>;
template <typename _T> using gradians = basic_angle<_T, gradian_traits<_T>>;
template <typename _T> using revolutions = basic_angle<_T, revolution_traits<_T>>;
template <
typename _T,
typename _Traits = radian_traits<_T>>
struct basic_angle {
//////////////////////////////////////////////////////////////////////////////
// type definitions.
typedef _Traits traits_type;
typedef _T value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef value_type const* const_pointer;
typedef value_type const& const_reference;
//////////////////////////////////////////////////////////////////////////////
// construction.
constexpr explicit basic_angle(value_type val = static_cast<_T>(0)) noexcept
: _value { val } {}
constexpr basic_angle(basic_angle&&) = default;
constexpr basic_angle(basic_angle const&) = default;
//////////////////////////////////////////////////////////////////////////////
// assignment operators.
basic_angle& operator = (basic_angle&&) = default;
basic_angle& operator = (basic_angle const&) = default;
//////////////////////////////////////////////////////////////////////////////
// accessor methods.
constexpr value_type value() const noexcept {
return _value;
}
//////////////////////////////////////////////////////////////////////////////
// unary arithmetic operators.
constexpr basic_angle operator +() const noexcept {
return basic_angle { _value };
}
constexpr basic_angle operator -() const noexcept {
return basic_angle { -_value };
}
//////////////////////////////////////////////////////////////////////////////
// compound arithmetic operators.
basic_angle& operator ++() noexcept {
++_value;
return *this;
}
basic_angle& operator --() noexcept {
--_value;
return *this;
}
basic_angle operator ++(int) noexcept {
basic_angle tmp(*this); ++*this;
return *this;
}
basic_angle operator --(int) noexcept {
basic_angle tmp(*this); --*this;
return *this;
}
basic_angle& operator += (basic_angle const& other) noexcept {
_value += other._value;
return *this;
}
basic_angle& operator -= (basic_angle const& other) noexcept {
_value -= other._value;
return *this;
}
basic_angle& operator *= (value_type val) noexcept {
_value *= val;
return *this;
}
basic_angle& operator /= (value_type val) noexcept {
_value /= val;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
// conversion operators.
template <typename _Traits2>
constexpr operator basic_angle<_T, _Traits2>() const noexcept {
return _convert<_T, _Traits2>();
}
template <typename _T2, typename _Traits2>
constexpr operator basic_angle<_T2, _Traits2>() const noexcept {
return _convert<_T2, _Traits2>();
}
//////////////////////////////////////////////////////////////////////////////
// streaming operators.
template <typename _CharT, typename _OsTraits>
friend std::basic_ostream<_CharT, _OsTraits>& operator << (std::basic_ostream<_CharT, _OsTraits>& ostr, basic_angle const& angle) {
return ostr << angle._value;
}
template <typename _CharT, typename _IsTraits>
friend std::basic_istream<_CharT, _IsTraits>& operator << (std::basic_istream<_CharT, _IsTraits>& istr, basic_angle& angle) {
return istr >> angle._value;
}
private:
value_type _value;
template <typename _T2, typename _Traits2>
constexpr basic_angle<_T2, _Traits2> _convert() const noexcept {
typedef typename std::common_type<_T, _T2>::type common_t;
return basic_angle<_T2, _Traits2> { static_cast<common_t>(_value) * _Traits2::pi() / _Traits::pi() };
}
};
constexpr const radians<long double> pi = degrees<long double>(180);
//////////////////////////////////////////////////////////////////////////////
// binary arithmetic operators.
template <typename _T1, typename _T2, typename _Traits1, typename _Traits2>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits1> operator + (
basic_angle<_T1, _Traits1> const& lhs, basic_angle<_T2, _Traits2> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits1>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator + (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator + (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) += rhs;
}
template <typename _T1, typename _T2, typename _Traits1, typename _Traits2>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits1> operator - (
basic_angle<_T1, _Traits1> const& lhs, basic_angle<_T2, _Traits2> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits1>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator - (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator - (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) -= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator * (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) *= rhs;
}
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator * (
_T1 const& lhs, basic_angle<_T2, _Traits> const& rhs) { return rhs * lhs; }
template <typename _T1, typename _T2, typename _Traits>
inline constexpr basic_angle<typename std::common_type<_T1, _T2>::type, _Traits> operator / (
basic_angle<_T1, _Traits> const& lhs, _T2 const& rhs) {
typedef typename std::common_type<_T1, _T2>::type common_t;
return basic_angle<common_t, _Traits>(lhs) /= rhs;
}
//////////////////////////////////////////////////////////////////////////////
// comparison operators.
template <typename _T, typename _Traits>
inline constexpr bool operator == (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) noexcept {
return lhs.value() == rhs.value();
}
template <typename _T, typename _Traits>
inline constexpr bool operator < (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) noexcept {
return lhs.value() < rhs.value();
}
template <typename _T, typename _Traits>
inline constexpr bool operator != (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(lhs == rhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator <= (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(rhs < lhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator >= (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return !(lhs < rhs);
}
template <typename _T, typename _Traits>
inline constexpr bool operator > (basic_angle<_T, _Traits> const& lhs, typename std::common_type<basic_angle<_T, _Traits>>::type const& rhs) {
return rhs < lhs;
}
//////////////////////////////////////////////////////////////////////////////
// helper functions.
template <typename _T>
constexpr radians<typename std::common_type<_T, float>::type> rad(_T const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return radians<common_t> { static_cast<common_t>(angle) };
}
template <typename _T>
constexpr revolutions<typename std::common_type<_T, float>::type> revs(_T const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return revolutions<common_t> { static_cast<common_t>(angle) };
}
template <typename _T>
constexpr degrees<_T> deg(_T const& angle) {
return degrees<_T> { angle };
}
template <typename _T>
constexpr gradians<_T> grad(_T const& angle) {
return gradians<_T> { angle };
}
template <typename _T, typename _Traits>
constexpr radians<typename std::common_type<_T, float>::type> rad(basic_angle<_T, _Traits> const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return radians<common_t> { angle };
}
template <typename _T, typename _Traits>
constexpr revolutions<typename std::common_type<_T, float>::type> revs(basic_angle<_T, _Traits> const& angle) {
typedef typename std::common_type<_T, float>::type common_t;
return revolutions<common_t> { angle };
}
template <typename _T, typename _Traits>
constexpr degrees<_T> deg(basic_angle<_T, _Traits> const& angle) {
return degrees<_T> { angle };
}
template <typename _T, typename _Traits>
constexpr gradians<_T> grad(basic_angle<_T, _Traits> const& angle) {
return gradians<_T> { angle };
}
}
namespace math {
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type sin(basic_angle<_T, _Traits> const& x) { return std::sin(math::rad(x).value()); }
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type cos(basic_angle<_T, _Traits> const& x) { return std::cos(math::rad(x).value()); }
template <typename _T, typename _Traits>
inline typename std::common_type<_T, float>::type tan(basic_angle<_T, _Traits> const& x) { return std::tan(math::rad(x).value()); }
}
#endif // _MATH_ANGLE_HPP<|endoftext|> |
<commit_before>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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 <GameServer/Common/IDHolder.hpp>
#include <GameServer/Human/Key.hpp>
#include <GameServer/Resource/Helpers.hpp>
#include <GameServer/Resource/Key.hpp>
#include <GameServer/Turn/Managers/TurnManager.hpp>
#include <math.h>
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
using namespace GameServer::Settlement;
using namespace GameServer::World;
namespace GameServer
{
namespace Turn
{
TurnManager::TurnManager(
IContextShrPtr const a_context,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade,
ISettlementPersistenceFacadeShrPtr a_settlement_persistence_facade
)
: m_context(a_context),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade),
m_settlement_persistence_facade(a_settlement_persistence_facade)
{
}
bool TurnManager::turn(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get lands that belong to the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Execute turn of every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = executeTurn(a_transaction, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool TurnManager::executeTurn(
ITransactionShrPtr a_transaction,
ILandShrPtr const a_land
) const
{
ISettlementMap settlements = m_settlement_persistence_facade->getSettlements(a_transaction, a_land);
for (ISettlementMap::iterator it = settlements.begin(); it != settlements.end(); ++it)
{
bool const result = executeTurnSettlement(a_transaction, it->second->getSettlementName());
if (!result)
{
return false;
}
}
m_land_persistence_facade->increaseAge(a_transaction, a_land);
return true;
}
bool TurnManager::executeTurnSettlement(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
// Correct engagement.
// TODO: Implement me!
// Get the available resources.
ResourceWithVolumeMap const available_resources = m_resource_persistence_facade->getResources(a_transaction, id_holder);
// Get the cost of living.
ResourceWithVolumeMap const cost_of_living = getCostOfLiving(a_transaction, a_settlement_name);
// Verify if famine happened.
bool const famine_happened = verifyFamine(available_resources, cost_of_living);
if (famine_happened)
{
bool const result = famine(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Verify if poverty happened.
bool const poverty_happened = verifyPoverty(available_resources, cost_of_living);
if (poverty_happened)
{
bool const result = poverty(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Expenses.
{
m_resource_persistence_facade->subtractResourcesSafely(a_transaction, id_holder, cost_of_living);
}
// Receipts.
if (verifyReceipts())
{
receipts(a_transaction, a_settlement_name);
}
// Experience.
if (!poverty_happened)
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property experienceable.
Configuration::IKey const key = it->second->getHuman()->getKey();
if (key == Human::KEY_WORKER_JOBLESS_NOVICE or key == Human::KEY_WORKER_JOBLESS_ADVANCED)
{
continue;
}
if (it->second->getHuman()->getExperience() == "advanced") // TODO: A nasty hardcode. Fixme!
{
continue;
}
// TODO: Hardcoded HUMAN_EXPERIENCE_FACTOR.
Human::Volume const experienced = it->second->getVolume() * 0.1;
if (experienced)
{
IKey key_novice = it->first;
IKey key_advanced;
// TODO: A nasty workaround.
if (key_novice == KEY_WORKER_BREEDER_NOVICE ) key_advanced = KEY_WORKER_BREEDER_ADVANCED;
if (key_novice == KEY_WORKER_FARMER_NOVICE ) key_advanced = KEY_WORKER_FARMER_ADVANCED;
if (key_novice == KEY_WORKER_FISHERMAN_NOVICE ) key_advanced = KEY_WORKER_FISHERMAN_ADVANCED;
if (key_novice == KEY_WORKER_JOBLESS_NOVICE ) key_advanced = KEY_WORKER_JOBLESS_ADVANCED;
if (key_novice == KEY_WORKER_LUMBERJACK_NOVICE ) key_advanced = KEY_WORKER_LUMBERJACK_ADVANCED;
if (key_novice == KEY_WORKER_MERCHANT_NOVICE ) key_advanced = KEY_WORKER_MERCHANT_ADVANCED;
if (key_novice == KEY_WORKER_MINER_NOVICE ) key_advanced = KEY_WORKER_MINER_ADVANCED;
if (key_novice == KEY_WORKER_STEELWORKER_NOVICE ) key_advanced = KEY_WORKER_STEELWORKER_ADVANCED;
if (key_novice == KEY_WORKER_STONE_MASON_NOVICE ) key_advanced = KEY_WORKER_STONE_MASON_ADVANCED;
m_human_persistence_facade->addHuman(a_transaction, id_holder, key_advanced, experienced);
bool const result = m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
key_novice,
experienced
);
if (!result)
{
return false;
}
}
}
}
// Reproduce.
if (!famine_happened)
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property reproduceable.
// TODO: Hardcoded HUMAN_REPRODUCE_FACTOR.
// TODO: Random choosing if reproduction happened (if the uint result of volume * HUMAN_REPRODUCE_FACTOR < 1).
Human::Volume const reproduced = it->second->getVolume() * 0.1;
if (reproduced)
{
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, reproduced);
}
}
}
return true;
}
ResourceWithVolumeMap TurnManager::getCostOfLiving(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
ResourceWithVolumeMap total_cost;
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<IKey, GameServer::Resource::Volume> const & cost_map =
it->second->getHuman()->getCostsToLive();
// FIXME: Workaround to get the ResourceWithVolumeMap.
ResourceWithVolumeMap resources;
for (std::map<IKey, Volume>::const_iterator itr = cost_map.begin(); itr != cost_map.end(); ++itr)
{
ResourceWithVolumeShrPtr resource(new ResourceWithVolume(m_context, itr->first, itr->second));
resources[itr->first] = resource;
}
resources = multiply(m_context, resources, it->second->getVolume());
total_cost = add(m_context, total_cost, resources);
}
return total_cost;
}
bool TurnManager::verifyFamine(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
Resource::Volume available(0), used(0);
try
{
// FIXME: Code smell - envious class.
available = a_available_resources.at(KEY_RESOURCE_FOOD)->getVolume();
}
catch (...)
{
}
try
{
// FIXME: Code smell - envious class.
used = a_used_resources.at(KEY_RESOURCE_FOOD)->getVolume();
}
catch (...)
{
}
return (available < used) ? true : false;
}
bool TurnManager::famine(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded FAMINE_DEATH_FACTOR.
Human::Volume died = ceil(it->second->getVolume() * 0.1);
if (died)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
died
);
if (!result)
{
return false;
}
}
}
return true;
}
bool TurnManager::verifyPoverty(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
Resource::Volume available(0), used(0);
try
{
// FIXME: Code smell - envious class.
available = a_available_resources.at(KEY_RESOURCE_GOLD)->getVolume();
}
catch (...)
{
}
try
{
// FIXME: Code smell - envious class.
used = a_used_resources.at(KEY_RESOURCE_GOLD)->getVolume();
}
catch (...)
{
}
return (available < used) ? true : false;
}
bool TurnManager::poverty(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded POVERTY_DISMISS_FACTOR.
Human::Volume dismissed = ceil(it->second->getVolume() * 0.1);
if (dismissed)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
dismissed
);
if (!result)
{
return false;
}
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, dismissed);
}
}
return true;
}
bool TurnManager::verifyReceipts() const
{
return true;
}
void TurnManager::receipts(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
if (!it->second->getHuman()->getResourceProduced().empty())
{
// TODO: Define whether and how to check if volume is greater than 0.
m_resource_persistence_facade->addResource(
a_transaction,
id_holder,
it->second->getHuman()->getResourceProduced(),
it->second->getHuman()->getProduction() * it->second->getVolume()
);
}
}
}
} // namespace Turn
} // namespace GameServer
<commit_msg>Closes #68<commit_after>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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 <GameServer/Common/IDHolder.hpp>
#include <GameServer/Human/Key.hpp>
#include <GameServer/Resource/Helpers.hpp>
#include <GameServer/Resource/Key.hpp>
#include <GameServer/Turn/Managers/TurnManager.hpp>
#include <math.h>
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Human;
using namespace GameServer::Land;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
using namespace GameServer::Settlement;
using namespace GameServer::World;
namespace GameServer
{
namespace Turn
{
TurnManager::TurnManager(
IContextShrPtr const a_context,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
ILandPersistenceFacadeShrPtr a_land_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade,
ISettlementPersistenceFacadeShrPtr a_settlement_persistence_facade
)
: m_context(a_context),
m_human_persistence_facade(a_human_persistence_facade),
m_land_persistence_facade(a_land_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade),
m_settlement_persistence_facade(a_settlement_persistence_facade)
{
}
bool TurnManager::turn(
ITransactionShrPtr a_transaction,
IWorldShrPtr const a_world
) const
{
try
{
// Get lands that belong to the world.
ILandMap lands = m_land_persistence_facade->getLands(a_transaction, a_world);
// Execute turn of every land.
for (ILandMap::const_iterator it = lands.begin(); it != lands.end(); ++it)
{
bool const result = executeTurn(a_transaction, it->second);
if (!result)
{
return false;
}
}
return true;
}
catch (...)
{
return false;
}
}
bool TurnManager::executeTurn(
ITransactionShrPtr a_transaction,
ILandShrPtr const a_land
) const
{
ISettlementMap settlements = m_settlement_persistence_facade->getSettlements(a_transaction, a_land);
for (ISettlementMap::iterator it = settlements.begin(); it != settlements.end(); ++it)
{
bool const result = executeTurnSettlement(a_transaction, it->second->getSettlementName());
if (!result)
{
return false;
}
}
m_land_persistence_facade->increaseAge(a_transaction, a_land);
return true;
}
bool TurnManager::executeTurnSettlement(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
// Correct engagement.
// TODO: Implement me!
// Get the available resources.
ResourceWithVolumeMap const available_resources = m_resource_persistence_facade->getResources(a_transaction, id_holder);
// Get the cost of living.
ResourceWithVolumeMap const cost_of_living = getCostOfLiving(a_transaction, a_settlement_name);
// Verify if famine happened.
bool const famine_happened = verifyFamine(available_resources, cost_of_living);
if (famine_happened)
{
bool const result = famine(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Verify if poverty happened.
bool const poverty_happened = verifyPoverty(available_resources, cost_of_living);
if (poverty_happened)
{
bool const result = poverty(a_transaction, a_settlement_name);
if (!result)
{
return false;
}
}
// Expenses.
{
m_resource_persistence_facade->subtractResourcesSafely(a_transaction, id_holder, cost_of_living);
}
// Receipts.
if (verifyReceipts())
{
receipts(a_transaction, a_settlement_name);
}
// Experience.
if (!poverty_happened)
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property experienceable.
Configuration::IKey const key = it->second->getHuman()->getKey();
if (key == Human::KEY_WORKER_JOBLESS_NOVICE or key == Human::KEY_WORKER_JOBLESS_ADVANCED)
{
continue;
}
if (it->second->getHuman()->getExperience() == "advanced") // TODO: A nasty hardcode. Fixme!
{
continue;
}
Human::Volume const experienced =
it->second->getVolume()
* m_context->getConfiguratorBase()->getHumanExperienceFactor() / 100;
if (experienced)
{
IKey key_novice = it->first;
IKey key_advanced;
// TODO: A nasty workaround.
if (key_novice == KEY_WORKER_BREEDER_NOVICE ) key_advanced = KEY_WORKER_BREEDER_ADVANCED;
if (key_novice == KEY_WORKER_FARMER_NOVICE ) key_advanced = KEY_WORKER_FARMER_ADVANCED;
if (key_novice == KEY_WORKER_FISHERMAN_NOVICE ) key_advanced = KEY_WORKER_FISHERMAN_ADVANCED;
if (key_novice == KEY_WORKER_JOBLESS_NOVICE ) key_advanced = KEY_WORKER_JOBLESS_ADVANCED;
if (key_novice == KEY_WORKER_LUMBERJACK_NOVICE ) key_advanced = KEY_WORKER_LUMBERJACK_ADVANCED;
if (key_novice == KEY_WORKER_MERCHANT_NOVICE ) key_advanced = KEY_WORKER_MERCHANT_ADVANCED;
if (key_novice == KEY_WORKER_MINER_NOVICE ) key_advanced = KEY_WORKER_MINER_ADVANCED;
if (key_novice == KEY_WORKER_STEELWORKER_NOVICE ) key_advanced = KEY_WORKER_STEELWORKER_ADVANCED;
if (key_novice == KEY_WORKER_STONE_MASON_NOVICE ) key_advanced = KEY_WORKER_STONE_MASON_ADVANCED;
m_human_persistence_facade->addHuman(a_transaction, id_holder, key_advanced, experienced);
bool const result = m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
key_novice,
experienced
);
if (!result)
{
return false;
}
}
}
}
// Reproduce.
if (!famine_happened)
{
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Use property reproduceable.
// TODO: Hardcoded HUMAN_REPRODUCE_FACTOR.
// TODO: Random choosing if reproduction happened (if the uint result of volume * HUMAN_REPRODUCE_FACTOR < 1).
Human::Volume const reproduced = it->second->getVolume() * 0.1;
if (reproduced)
{
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, reproduced);
}
}
}
return true;
}
ResourceWithVolumeMap TurnManager::getCostOfLiving(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
ResourceWithVolumeMap total_cost;
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
std::map<IKey, GameServer::Resource::Volume> const & cost_map =
it->second->getHuman()->getCostsToLive();
// FIXME: Workaround to get the ResourceWithVolumeMap.
ResourceWithVolumeMap resources;
for (std::map<IKey, Volume>::const_iterator itr = cost_map.begin(); itr != cost_map.end(); ++itr)
{
ResourceWithVolumeShrPtr resource(new ResourceWithVolume(m_context, itr->first, itr->second));
resources[itr->first] = resource;
}
resources = multiply(m_context, resources, it->second->getVolume());
total_cost = add(m_context, total_cost, resources);
}
return total_cost;
}
bool TurnManager::verifyFamine(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
Resource::Volume available(0), used(0);
try
{
// FIXME: Code smell - envious class.
available = a_available_resources.at(KEY_RESOURCE_FOOD)->getVolume();
}
catch (...)
{
}
try
{
// FIXME: Code smell - envious class.
used = a_used_resources.at(KEY_RESOURCE_FOOD)->getVolume();
}
catch (...)
{
}
return (available < used) ? true : false;
}
bool TurnManager::famine(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded FAMINE_DEATH_FACTOR.
Human::Volume died = ceil(it->second->getVolume() * 0.1);
if (died)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
died
);
if (!result)
{
return false;
}
}
}
return true;
}
bool TurnManager::verifyPoverty(
Resource::ResourceWithVolumeMap const & a_available_resources,
Resource::ResourceWithVolumeMap const & a_used_resources
) const
{
Resource::Volume available(0), used(0);
try
{
// FIXME: Code smell - envious class.
available = a_available_resources.at(KEY_RESOURCE_GOLD)->getVolume();
}
catch (...)
{
}
try
{
// FIXME: Code smell - envious class.
used = a_used_resources.at(KEY_RESOURCE_GOLD)->getVolume();
}
catch (...)
{
}
return (available < used) ? true : false;
}
bool TurnManager::poverty(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// TODO: Hardcoded POVERTY_DISMISS_FACTOR.
Human::Volume dismissed = ceil(it->second->getVolume() * 0.1);
if (dismissed)
{
bool const result =
m_human_persistence_facade->subtractHuman(
a_transaction,
id_holder,
it->second->getHuman()->getKey(),
dismissed
);
if (!result)
{
return false;
}
m_human_persistence_facade->addHuman(a_transaction, id_holder, KEY_WORKER_JOBLESS_NOVICE, dismissed);
}
}
return true;
}
bool TurnManager::verifyReceipts() const
{
return true;
}
void TurnManager::receipts(
ITransactionShrPtr a_transaction,
std::string const a_settlement_name
) const
{
IDHolder id_holder(ID_HOLDER_CLASS_SETTLEMENT, a_settlement_name);
HumanWithVolumeMap const humans = m_human_persistence_facade->getHumans(a_transaction, id_holder);
for (HumanWithVolumeMap::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
if (!it->second->getHuman()->getResourceProduced().empty())
{
// TODO: Define whether and how to check if volume is greater than 0.
m_resource_persistence_facade->addResource(
a_transaction,
id_holder,
it->second->getHuman()->getResourceProduced(),
it->second->getHuman()->getProduction() * it->second->getVolume()
);
}
}
}
} // namespace Turn
} // namespace GameServer
<|endoftext|> |
<commit_before>// Time: O(|V| + |E||)
// Space: O(|E|)
// Topological sort.
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> res;
// Store courses with in-degree zero.
queue<int> zeroInDegree;
// in-degree, out-degree
unordered_map<int, unordered_set<int>> inDegree;
unordered_map<int, unordered_set<int>> outDegree;
for (int i = 0; i < prerequisites.size(); ++i) {
inDegree[prerequisites[i].first].insert(prerequisites[i].second);
outDegree[prerequisites[i].second].insert(prerequisites[i].first);
}
// Put all the courses with in-degree zero into queue.
for(int i = 0; i < numCourses; ++i) {
if(inDegree.find(i) == inDegree.end()) {
zeroInDegree.push(i);
}
}
// V+E
while(!zeroInDegree.empty()) {
// Take the course which prerequisites are all taken.
int prerequisite = zeroInDegree.front();
res.emplace_back(prerequisite);
zeroInDegree.pop();
for (const auto & course: outDegree[prerequisite]) {
// Update info of all the courses with the taken prerequisite.
inDegree[course].erase(prerequisite);
// If all the prerequisites are taken, add the course to the queue.
if (inDegree[course].empty()) {
zeroInDegree.push(course);
}
}
// Mark the course as taken.
outDegree.erase(prerequisite);
}
// All of the courses have been taken.
if (!outDegree.empty()) {
return {};
}
return res;
}
};
<commit_msg>Update course-schedule-ii.cpp<commit_after>// Time: O(|V| + |E||)
// Space: O(|E|)
// Topological sort solution.
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> res;
// Store courses with in-degree zero.
queue<int> zeroInDegree;
// in-degree, out-degree
unordered_map<int, unordered_set<int>> inDegree;
unordered_map<int, unordered_set<int>> outDegree;
for (int i = 0; i < prerequisites.size(); ++i) {
inDegree[prerequisites[i].first].insert(prerequisites[i].second);
outDegree[prerequisites[i].second].insert(prerequisites[i].first);
}
// Put all the courses with in-degree zero into queue.
for(int i = 0; i < numCourses; ++i) {
if(inDegree.find(i) == inDegree.end()) {
zeroInDegree.push(i);
}
}
// V+E
while(!zeroInDegree.empty()) {
// Take the course which prerequisites are all taken.
int prerequisite = zeroInDegree.front();
res.emplace_back(prerequisite);
zeroInDegree.pop();
for (const auto & course: outDegree[prerequisite]) {
// Update info of all the courses with the taken prerequisite.
inDegree[course].erase(prerequisite);
// If all the prerequisites are taken, add the course to the queue.
if (inDegree[course].empty()) {
zeroInDegree.push(course);
}
}
// Mark the course as taken.
outDegree.erase(prerequisite);
}
// All of the courses have been taken.
if (!outDegree.empty()) {
return {};
}
return res;
}
};
<|endoftext|> |
<commit_before>namespace mant {
template <typename ParameterType>
class PropertyAnalysis {
public:
explicit PropertyAnalysis() noexcept;
void analyse(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;
void setDistanceFunction(
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction) noexcept;
double getPlausibility() const noexcept;
// Provides a default deconstructor.
virtual ~PropertyAnalysis() = default;
protected:
double plausibility_;
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction_;
void setDefaultDistanceFunction(std::true_type) noexcept;
void setDefaultDistanceFunction(std::false_type) noexcept;
virtual void analyseImplementation(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept = 0;
};
//
// Implementation
//
template <typename ParameterType>
PropertyAnalysis<ParameterType>::PropertyAnalysis() noexcept
: plausibility_(0.0) {
setDefaultDistanceFunction(std::is_floating_point<ParameterType>());
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::analyse(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept {
plausibility_ = 0.0;
analyseImplementation(optimisationProblem);
}
template <typename ParameterType>
double PropertyAnalysis<ParameterType>::getPlausibility() const noexcept {
return plausibility_;
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDistanceFunction(
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction) noexcept {
distanceFunction_ = distanceFunction;
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDefaultDistanceFunction(
std::true_type) noexcept {
setDistanceFunction(std::shared_ptr<DistanceFunction<ParameterType>>(new EuclideanDistance));
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDefaultDistanceFunction(
std::false_type) noexcept {
setDistanceFunction(std::shared_ptr<DistanceFunction<ParameterType>>(new ManhattanDistance<ParameterType>));
}
}
<commit_msg>devel: Removed analyse specification from the base class<commit_after>namespace mant {
template <typename ParameterType>
class PropertyAnalysis {
public:
explicit PropertyAnalysis() noexcept;
void setDistanceFunction(
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction) noexcept;
double getPlausibility() const noexcept;
// Provides a default deconstructor.
virtual ~PropertyAnalysis() = default;
protected:
double plausibility_;
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction_;
void setDefaultDistanceFunction(std::true_type) noexcept;
void setDefaultDistanceFunction(std::false_type) noexcept;
};
//
// Implementation
//
template <typename ParameterType>
PropertyAnalysis<ParameterType>::PropertyAnalysis() noexcept
: plausibility_(0.0) {
setDefaultDistanceFunction(std::is_floating_point<ParameterType>());
}
template <typename ParameterType>
double PropertyAnalysis<ParameterType>::getPlausibility() const noexcept {
return plausibility_;
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDistanceFunction(
std::shared_ptr<DistanceFunction<ParameterType>> distanceFunction) noexcept {
distanceFunction_ = distanceFunction;
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDefaultDistanceFunction(
std::true_type) noexcept {
setDistanceFunction(std::shared_ptr<DistanceFunction<ParameterType>>(new EuclideanDistance));
}
template <typename ParameterType>
void PropertyAnalysis<ParameterType>::setDefaultDistanceFunction(
std::false_type) noexcept {
setDistanceFunction(std::shared_ptr<DistanceFunction<ParameterType>>(new ManhattanDistance<ParameterType>));
}
}
<|endoftext|> |
<commit_before>/// @file
/// @brief time_point to iso8601 string converter
#pragma once
#include "default_clock.hxx"
#ifdef _WIN32
#include "time_zone_difference.hxx"
#endif
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <iostream>
namespace usagi
{
namespace chrono
{
#ifdef _WIN32
// TDM-GCC-5.1.0 is not support %F and %T
// note: mingw is supported. but we cannot predicate TDM or not.
constexpr auto format_date_time = "%Y-%m-%dT%H:%M:%S";
#else
constexpr auto format_date_time = "%FT%T";
#endif
constexpr auto format_time_zone = "%z";
namespace detail
{
template
< typename T = usagi::chrono::default_clock::time_point
, typename U = std::chrono::seconds
>
auto get_sub_seccond_string( const T& time_point )
-> std::string
{
constexpr auto ratio_in_real = static_cast< long double >( U::period::num ) / U::period::den;
constexpr auto sub_second_digits = -std::log10( ratio_in_real );
if ( sub_second_digits < 1 )
return "";
const auto full = std::chrono::duration_cast< std::chrono::duration< long double > >( time_point.time_since_epoch() );
const auto sec = std::chrono::duration_cast< std::chrono::seconds >( time_point.time_since_epoch() );
const auto sub_second_in_real = ( full - sec ).count();
std::stringstream s;
s << std::fixed << std::setprecision( sub_second_digits ) << sub_second_in_real;
constexpr auto in_dot = 1;
return s.str().substr( in_dot );
}
}
/// @brief time_point to iso8601 string
/// @tparam T clock type
/// @param t time_point
/// @return iso8601 string
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
auto to_string_iso8601_gmt
( const TIME_POINT& t = TIME_POINT::clock::now()
)
-> std::string
{
using namespace std::chrono;
const auto& ct = TIME_POINT::clock::to_time_t ( t );
const auto gt = std::gmtime( &ct );
std::stringstream r;
r << std::put_time( gt, format_date_time )
<< detail::get_sub_seccond_string< TIME_POINT, SECOND_UNIT >( t )
<< "Z"
;
return r.str();
}
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
auto to_string_iso8601_jst
( const TIME_POINT& t = TIME_POINT::clock::now()
)
{
using namespace std::chrono;
const auto& ct = TIME_POINT::clock::to_time_t ( t );
auto lt = *std::localtime( &ct );
#ifdef _WIN32
// MSVC++ ( and mingw ) put an invalid `%z` time zone string, then
// write convertible code and it requred a time zone difference.
const auto z = time_zone_difference();
#endif
std::stringstream r;
r << std::put_time( <, format_date_time )
<< detail::get_sub_seccond_string< TIME_POINT, SECOND_UNIT >( t )
#ifdef _WIN32
<< ( std::signbit( z.count() ) ? "-" : "+" )
<< std::setw( 2 ) << std::setfill( '0' )
<< std::to_string( std::abs( duration_cast< hours >( z ).count() ) )
<< ":"
<< std::setw( 2 ) << std::setfill( '0' )
<< std::to_string( std::abs( duration_cast< minutes >( z ).count() ) % minutes::period::den )
#else
<< std::put_time( <, format_time_zone )
#endif
;
return r.str();
}
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
[[deprecated ( "to use: to_string_iso8601_gmt" )]]
auto to_string_iso8601
( const TIME_POINT& t = TIME_POINT::clock::now()
)
{ return to_string_iso8601_gmt< TIME_POINT, SECOND_UNIT > ( t ); }
}
}
<commit_msg>fix-up<commit_after>/// @file
/// @brief time_point to iso8601 string converter
#pragma once
#include "default_clock.hxx"
#ifdef _WIN32
#include "time_zone_difference.hxx"
#include "to_time_t.hxx"
#endif
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <iostream>
namespace usagi
{
namespace chrono
{
#ifdef _WIN32
// TDM-GCC-5.1.0 is not support %F and %T
// note: mingw is supported. but we cannot predicate TDM or not.
constexpr auto format_date_time = "%Y-%m-%dT%H:%M:%S";
#else
constexpr auto format_date_time = "%FT%T";
#endif
constexpr auto format_time_zone = "%z";
namespace detail
{
template
< typename T = usagi::chrono::default_clock::time_point
, typename U = std::chrono::seconds
>
auto get_sub_seccond_string( const T& time_point )
-> std::string
{
constexpr auto ratio_in_real = static_cast< long double >( U::period::num ) / U::period::den;
constexpr auto sub_second_digits = -std::log10( ratio_in_real );
if ( sub_second_digits < 1 )
return "";
const auto full = std::chrono::duration_cast< std::chrono::duration< long double > >( time_point.time_since_epoch() );
const auto sec = std::chrono::duration_cast< std::chrono::seconds >( time_point.time_since_epoch() );
const auto sub_second_in_real = ( full - sec ).count();
std::stringstream s;
s << std::fixed << std::setprecision( sub_second_digits ) << sub_second_in_real;
constexpr auto in_dot = 1;
return s.str().substr( in_dot );
}
}
/// @brief time_point to iso8601 string
/// @tparam T clock type
/// @param t time_point
/// @return iso8601 string
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
auto to_string_iso8601_gmt
( const TIME_POINT& t = TIME_POINT::clock::now()
)
-> std::string
{
using namespace std::chrono;
const auto& ct = to_time_t ( t );
const auto gt = std::gmtime( &ct );
std::stringstream r;
r << std::put_time( gt, format_date_time )
<< detail::get_sub_seccond_string< TIME_POINT, SECOND_UNIT >( t )
<< "Z"
;
return r.str();
}
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
auto to_string_iso8601_jst
( const TIME_POINT& t = TIME_POINT::clock::now()
)
{
using namespace std::chrono;
const auto& ct = to_time_t ( t );
auto lt = *std::localtime( &ct );
#ifdef _WIN32
// MSVC++ ( and mingw ) put an invalid `%z` time zone string, then
// write convertible code and it requred a time zone difference.
const auto z = time_zone_difference();
#endif
std::stringstream r;
r << std::put_time( <, format_date_time )
<< detail::get_sub_seccond_string< TIME_POINT, SECOND_UNIT >( t )
#ifdef _WIN32
<< ( std::signbit( z.count() ) ? "-" : "+" )
<< std::setw( 2 ) << std::setfill( '0' )
<< std::to_string( std::abs( duration_cast< hours >( z ).count() ) )
<< ":"
<< std::setw( 2 ) << std::setfill( '0' )
<< std::to_string( std::abs( duration_cast< minutes >( z ).count() ) % minutes::period::den )
#else
<< std::put_time( <, format_time_zone )
#endif
;
return r.str();
}
template
< typename TIME_POINT = default_clock::time_point
, typename SECOND_UNIT = std::chrono::seconds
>
[[deprecated ( "to use: to_string_iso8601_gmt" )]]
auto to_string_iso8601
( const TIME_POINT& t = TIME_POINT::clock::now()
)
{ return to_string_iso8601_gmt< TIME_POINT, SECOND_UNIT > ( t ); }
}
}
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGAccelerometer.cpp
Author: Jon Berndt
Date started: 9 July 2005
------------- Copyright (C) 2005 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser 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.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGAccelerometer.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGAccelerometer.cpp,v 1.3 2009/08/29 14:25:12 jberndt Exp $";
static const char *IdHdr = ID_ACCELEROMETER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGAccelerometer::FGAccelerometer(FGFCS* fcs, Element* element) : FGSensor(fcs, element)
{
Propagate = fcs->GetExec()->GetPropagate();
MassBalance = fcs->GetExec()->GetMassBalance();
Inertial = fcs->GetExec()->GetInertial();
Element* location_element = element->FindElement("location");
if (location_element) vLocation = location_element->FindElementTripletConvertTo("IN");
else {cerr << "No location given for accelerometer. " << endl; exit(-1);}
vRadius = MassBalance->StructuralToBody(vLocation);
Element* orient_element = element->FindElement("orientation");
if (orient_element) vOrient = orient_element->FindElementTripletConvertTo("RAD");
else {cerr << "No orientation given for accelerometer. " << endl;}
Element* axis_element = element->FindElement("axis");
if (axis_element) {
string sAxis = element->FindElementValue("axis");
if (sAxis == "X" || sAxis == "x") {
axis = 1;
} else if (sAxis == "Y" || sAxis == "y") {
axis = 2;
} else if (sAxis == "Z" || sAxis == "z") {
axis = 3;
} else {
cerr << " Incorrect/no axis specified for accelerometer; assuming X axis" << endl;
axis = 1;
}
}
CalculateTransformMatrix();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGAccelerometer::~FGAccelerometer()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGAccelerometer::Run(void )
{
// There is no input assumed. This is a dedicated acceleration sensor.
vRadius = MassBalance->StructuralToBody(vLocation);
//gravitational forces
vAccel = Propagate->GetTl2b() * FGColumnVector3(0, 0, Inertial->gravity());
//aircraft forces
vAccel += (Propagate->GetUVWdot()
+ Propagate->GetPQRdot() * vRadius
+ Propagate->GetPQR() * (Propagate->GetPQR() * vRadius));
// transform to the specified orientation
vAccel = mt * vAccel;
Input = vAccel(axis);
Output = Input; // perfect accelerometer
// Degrade signal as specified
if (fail_stuck) {
Output = PreviousOutput;
return true;
}
if (lag != 0.0) Lag(); // models accelerometer lag
if (noise_variance != 0.0) Noise(); // models noise
if (drift_rate != 0.0) Drift(); // models drift over time
if (bias != 0.0) Bias(); // models a finite bias
if (fail_low) Output = -HUGE_VAL;
if (fail_high) Output = HUGE_VAL;
if (bits != 0) Quantize(); // models quantization degradation
// if (delay != 0.0) Delay(); // models system signal transport latencies
Clip(); // Is it right to clip an accelerometer?
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGAccelerometer::CalculateTransformMatrix(void)
{
double cp,sp,cr,sr,cy,sy;
cp=cos(vOrient(ePitch)); sp=sin(vOrient(ePitch));
cr=cos(vOrient(eRoll)); sr=sin(vOrient(eRoll));
cy=cos(vOrient(eYaw)); sy=sin(vOrient(eYaw));
mT(1,1) = cp*cy;
mT(1,2) = cp*sy;
mT(1,3) = -sp;
mT(2,1) = sr*sp*cy - cr*sy;
mT(2,2) = sr*sp*sy + cr*cy;
mT(2,3) = sr*cp;
mT(3,1) = cr*sp*cy + sr*sy;
mT(3,2) = cr*sp*sy - sr*cy;
mT(3,3) = cr*cp;
// This transform is different than for FGForce, where we want a native nozzle
// force in body frame. Here we calculate the body frame accel and want it in
// the transformed accelerometer frame. So, the next line is commented out.
// mT = mT.Inverse();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGAccelerometer::Debug(int from)
{
string ax[4] = {"none", "X", "Y", "Z"};
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " Axis: " << ax[axis] << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGAccelerometer" << endl;
if (from == 1) cout << "Destroyed: FGAccelerometer" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>Modified the accelerometer component to account for gravity.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGAccelerometer.cpp
Author: Jon Berndt
Date started: 9 July 2005
------------- Copyright (C) 2005 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser 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.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGAccelerometer.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGAccelerometer.cpp,v 1.4 2009/08/29 14:25:48 jberndt Exp $";
static const char *IdHdr = ID_ACCELEROMETER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGAccelerometer::FGAccelerometer(FGFCS* fcs, Element* element) : FGSensor(fcs, element)
{
Propagate = fcs->GetExec()->GetPropagate();
MassBalance = fcs->GetExec()->GetMassBalance();
Inertial = fcs->GetExec()->GetInertial();
Element* location_element = element->FindElement("location");
if (location_element) vLocation = location_element->FindElementTripletConvertTo("IN");
else {cerr << "No location given for accelerometer. " << endl; exit(-1);}
vRadius = MassBalance->StructuralToBody(vLocation);
Element* orient_element = element->FindElement("orientation");
if (orient_element) vOrient = orient_element->FindElementTripletConvertTo("RAD");
else {cerr << "No orientation given for accelerometer. " << endl;}
Element* axis_element = element->FindElement("axis");
if (axis_element) {
string sAxis = element->FindElementValue("axis");
if (sAxis == "X" || sAxis == "x") {
axis = 1;
} else if (sAxis == "Y" || sAxis == "y") {
axis = 2;
} else if (sAxis == "Z" || sAxis == "z") {
axis = 3;
} else {
cerr << " Incorrect/no axis specified for accelerometer; assuming X axis" << endl;
axis = 1;
}
}
CalculateTransformMatrix();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGAccelerometer::~FGAccelerometer()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGAccelerometer::Run(void )
{
// There is no input assumed. This is a dedicated acceleration sensor.
vRadius = MassBalance->StructuralToBody(vLocation);
//gravitational forces
vAccel = Propagate->GetTl2b() * FGColumnVector3(0, 0, Inertial->gravity());
//aircraft forces
vAccel += (Propagate->GetUVWdot()
+ Propagate->GetPQRdot() * vRadius
+ Propagate->GetPQR() * (Propagate->GetPQR() * vRadius));
// transform to the specified orientation
vAccel = mT * vAccel;
Input = vAccel(axis);
Output = Input; // perfect accelerometer
// Degrade signal as specified
if (fail_stuck) {
Output = PreviousOutput;
return true;
}
if (lag != 0.0) Lag(); // models accelerometer lag
if (noise_variance != 0.0) Noise(); // models noise
if (drift_rate != 0.0) Drift(); // models drift over time
if (bias != 0.0) Bias(); // models a finite bias
if (fail_low) Output = -HUGE_VAL;
if (fail_high) Output = HUGE_VAL;
if (bits != 0) Quantize(); // models quantization degradation
// if (delay != 0.0) Delay(); // models system signal transport latencies
Clip(); // Is it right to clip an accelerometer?
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGAccelerometer::CalculateTransformMatrix(void)
{
double cp,sp,cr,sr,cy,sy;
cp=cos(vOrient(ePitch)); sp=sin(vOrient(ePitch));
cr=cos(vOrient(eRoll)); sr=sin(vOrient(eRoll));
cy=cos(vOrient(eYaw)); sy=sin(vOrient(eYaw));
mT(1,1) = cp*cy;
mT(1,2) = cp*sy;
mT(1,3) = -sp;
mT(2,1) = sr*sp*cy - cr*sy;
mT(2,2) = sr*sp*sy + cr*cy;
mT(2,3) = sr*cp;
mT(3,1) = cr*sp*cy + sr*sy;
mT(3,2) = cr*sp*sy - sr*cy;
mT(3,3) = cr*cp;
// This transform is different than for FGForce, where we want a native nozzle
// force in body frame. Here we calculate the body frame accel and want it in
// the transformed accelerometer frame. So, the next line is commented out.
// mT = mT.Inverse();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGAccelerometer::Debug(int from)
{
string ax[4] = {"none", "X", "Y", "Z"};
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " Axis: " << ax[axis] << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGAccelerometer" << endl;
if (from == 1) cout << "Destroyed: FGAccelerometer" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
* Author: Mohammed Kabir <mhkabir98@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file camera_trigger.cpp
*
* External camera-IMU synchronisation and triggering via FMU auxillary pins.
*
* @author Mohammed Kabir <mhkabir98@gmail.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <stdbool.h>
#include <nuttx/clock.h>
#include <nuttx/arch.h>
#include <systemlib/systemlib.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <uORB/uORB.h>
#include <uORB/topics/camera_trigger.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_command.h>
#include <poll.h>
#include <drivers/drv_gpio.h>
#include <drivers/drv_hrt.h>
#include <mavlink/mavlink_log.h>
extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]);
class CameraTrigger
{
public:
/**
* Constructor
*/
CameraTrigger();
/**
* Destructor, also kills task.
*/
~CameraTrigger();
/**
* Start the task.
*/
void start();
/**
* Stop the task.
*/
void stop();
/**
* Display info.
*/
void info();
int pin;
private:
struct hrt_call _pollcall;
struct hrt_call _firecall;
int _gpio_fd;
int _polarity;
float _activation_time;
float _integration_time;
float _transfer_time;
uint32_t _trigger_seq;
bool _trigger_enabled;
int _sensor_sub;
int _vcommand_sub;
orb_advert_t _trigger_pub;
struct camera_trigger_s _trigger;
struct sensor_combined_s _sensor;
struct vehicle_command_s _command;
param_t polarity ;
param_t activation_time ;
param_t integration_time ;
param_t transfer_time ;
/**
* Topic poller to check for fire info.
*/
static void poll(void *arg);
/**
* Fires trigger
*/
static void engage(void *arg);
/**
* Resets trigger
*/
static void disengage(void *arg);
};
namespace camera_trigger
{
CameraTrigger *g_camera_trigger;
}
CameraTrigger::CameraTrigger() :
pin(1),
_gpio_fd(-1),
_polarity(0),
_activation_time(0.0f),
_integration_time(0.0f),
_transfer_time(0.0f),
_trigger_seq(0),
_trigger_enabled(true),
_sensor_sub(-1),
_vcommand_sub(-1),
_trigger_pub(nullptr),
_trigger{}
{
memset(&_trigger, 0, sizeof(_trigger));
memset(&_command, 0, sizeof(_command));
memset(&_sensor, 0, sizeof(_sensor));
memset(&_pollcall, 0, sizeof(_pollcall));
memset(&_firecall, 0, sizeof(_firecall));
/* Parameters */
polarity = param_find("TRIG_POLARITY");
activation_time = param_find("TRIG_ACT_TIME");
integration_time = param_find("TRIG_INT_TIME");
transfer_time = param_find("TRIG_TRANS_TIME");
}
CameraTrigger::~CameraTrigger()
{
camera_trigger::g_camera_trigger = nullptr;
}
void
CameraTrigger::start()
{
_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if (_gpio_fd < 0) {
warnx("GPIO device open fail");
stop();
}
else
{
warnx("GPIO device opened");
}
_sensor_sub = orb_subscribe(ORB_ID(sensor_combined));
_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command));
param_get(polarity, &_polarity);
param_get(activation_time, &_activation_time);
param_get(integration_time, &_integration_time);
param_get(transfer_time, &_transfer_time);
ioctl(_gpio_fd, GPIO_SET_OUTPUT, pin);
if(_polarity == 0)
{
ioctl(_gpio_fd, GPIO_SET, pin); /* GPIO pin pull high */
}
else if(_polarity == 1)
{
ioctl(_gpio_fd, GPIO_CLEAR, pin); /* GPIO pin pull low */
}
else
{
warnx(" invalid trigger polarity setting. stopping.");
stop();
}
close(_gpio_fd);
poll(this); /* Trampoline call */
}
void
CameraTrigger::stop()
{
hrt_cancel(&_firecall);
hrt_cancel(&_pollcall);
delete camera_trigger::g_camera_trigger;
}
void
CameraTrigger::poll(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
bool updated;
orb_check(trig->_vcommand_sub, &updated);
if (updated) {
orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &trig->_command);
if(trig->_command.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL)
{
if(trig->_command.param1 < 1)
{
if(trig->_trigger_enabled)
{
trig->_trigger_enabled = false ;
}
}
else if(trig->_command.param1 >= 1)
{
if(!trig->_trigger_enabled)
{
trig->_trigger_enabled = true ;
}
}
// Set trigger rate from command
if(trig->_command.param2 > 0)
{
trig->_integration_time = trig->_command.param2;
param_set(trig->integration_time, &(trig->_integration_time));
}
}
}
if(!trig->_trigger_enabled) {
hrt_call_after(&trig->_pollcall, 1000, (hrt_callout)&CameraTrigger::poll, trig);
return;
}
else
{
engage(trig);
hrt_call_after(&trig->_firecall, trig->_activation_time*1000, (hrt_callout)&CameraTrigger::disengage, trig);
orb_copy(ORB_ID(sensor_combined), trig->_sensor_sub, &trig->_sensor);
trig->_trigger.timestamp = trig->_sensor.timestamp; /* get IMU timestamp */
trig->_trigger.seq = trig->_trigger_seq++;
if (trig->_trigger_pub > 0) {
orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trig->_trigger);
} else {
trig->_trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trig->_trigger);
}
hrt_call_after(&trig->_pollcall, (trig->_transfer_time + trig->_integration_time)*1000, (hrt_callout)&CameraTrigger::poll, trig);
}
}
void
CameraTrigger::engage(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
trig->_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if(trig->_polarity == 0) /* ACTIVE_LOW */
{
ioctl(trig->_gpio_fd, GPIO_CLEAR, trig->pin);
}
else if(trig->_polarity == 1) /* ACTIVE_HIGH */
{
ioctl(trig->_gpio_fd, GPIO_SET, trig->pin);
}
close(trig->_gpio_fd);
}
void
CameraTrigger::disengage(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
trig->_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if(trig->_polarity == 0) /* ACTIVE_LOW */
{
ioctl(trig->_gpio_fd, GPIO_SET, trig->pin);
}
else if(trig->_polarity == 1) /* ACTIVE_HIGH */
{
ioctl(trig->_gpio_fd, GPIO_CLEAR, trig->pin);
}
close(trig->_gpio_fd);
}
void
CameraTrigger::info()
{
warnx("Trigger state : %s", _trigger_enabled ? "enabled" : "disabled");
warnx("Trigger pin : %i", pin);
warnx("Trigger polarity : %s", _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW");
warnx("Shutter integration time : %.2f", (double)_integration_time);
}
static void usage()
{
errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n"
"\t-p <n>\tUse specified AUX OUT pin number (default: 1)"
);
}
int camera_trigger_main(int argc, char *argv[])
{
if (argc < 2) {
usage();
}
if (!strcmp(argv[1], "start")) {
if (camera_trigger::g_camera_trigger != nullptr) {
errx(0, "already running");
}
camera_trigger::g_camera_trigger = new CameraTrigger;
if (camera_trigger::g_camera_trigger == nullptr) {
errx(1, "alloc failed");
}
if (argc > 3) {
camera_trigger::g_camera_trigger->pin = (int)argv[3];
if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) {
warnx("starting trigger on pin : %li ", atoi(argv[3]));
camera_trigger::g_camera_trigger->pin = atoi(argv[3]);
}
else
{
usage();
}
}
camera_trigger::g_camera_trigger->start();
return 0;
}
if (camera_trigger::g_camera_trigger == nullptr) {
errx(1, "not running");
}
else if (!strcmp(argv[1], "stop")) {
camera_trigger::g_camera_trigger->stop();
}
else if (!strcmp(argv[1], "info")) {
camera_trigger::g_camera_trigger->info();
} else {
usage();
}
return 0;
}
<commit_msg>camera trigger : cleanup - still crashes<commit_after>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
* Author: Mohammed Kabir <mhkabir98@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file camera_trigger.cpp
*
* External camera-IMU synchronisation and triggering via FMU auxillary pins.
*
* @author Mohammed Kabir <mhkabir98@gmail.com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <stdbool.h>
#include <nuttx/clock.h>
#include <nuttx/arch.h>
#include <systemlib/systemlib.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <uORB/uORB.h>
#include <uORB/topics/camera_trigger.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_command.h>
#include <poll.h>
#include <drivers/drv_gpio.h>
#include <drivers/drv_hrt.h>
#include <mavlink/mavlink_log.h>
extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]);
class CameraTrigger
{
public:
/**
* Constructor
*/
CameraTrigger();
/**
* Destructor, also kills task.
*/
~CameraTrigger();
/**
* Start the task.
*/
void start();
/**
* Stop the task.
*/
void stop();
/**
* Display info.
*/
void info();
int pin;
private:
struct hrt_call _pollcall;
struct hrt_call _firecall;
int _gpio_fd;
int _polarity;
float _activation_time;
float _integration_time;
float _transfer_time;
uint32_t _trigger_seq;
bool _trigger_enabled;
int _sensor_sub;
int _vcommand_sub;
orb_advert_t _trigger_pub;
struct camera_trigger_s _trigger;
struct sensor_combined_s _sensor;
struct vehicle_command_s _command;
param_t polarity ;
param_t activation_time ;
param_t integration_time ;
param_t transfer_time ;
/**
* Topic poller to check for fire info.
*/
static void poll(void *arg);
/**
* Fires trigger
*/
static void engage(void *arg);
/**
* Resets trigger
*/
static void disengage(void *arg);
};
namespace camera_trigger
{
CameraTrigger *g_camera_trigger;
}
CameraTrigger::CameraTrigger() :
pin(1),
_pollcall{},
_firecall{},
_gpio_fd(-1),
_polarity(0),
_activation_time(0.0f),
_integration_time(0.0f),
_transfer_time(0.0f),
_trigger_seq(0),
_trigger_enabled(true),
_sensor_sub(-1),
_vcommand_sub(-1),
_trigger_pub(nullptr),
_trigger{},
_sensor{},
_command{}
{
memset(&_trigger, 0, sizeof(_trigger));
memset(&_sensor, 0, sizeof(_sensor));
memset(&_command, 0, sizeof(_command));
memset(&_pollcall, 0, sizeof(_pollcall));
memset(&_firecall, 0, sizeof(_firecall));
/* Parameters */
polarity = param_find("TRIG_POLARITY");
activation_time = param_find("TRIG_ACT_TIME");
integration_time = param_find("TRIG_INT_TIME");
transfer_time = param_find("TRIG_TRANS_TIME");
}
CameraTrigger::~CameraTrigger()
{
camera_trigger::g_camera_trigger = nullptr;
}
void
CameraTrigger::start()
{
_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if (_gpio_fd < 0) {
warnx("GPIO device open fail");
stop();
}
else
{
warnx("GPIO device opened");
}
_sensor_sub = orb_subscribe(ORB_ID(sensor_combined));
_vcommand_sub = orb_subscribe(ORB_ID(vehicle_command));
param_get(polarity, &_polarity);
param_get(activation_time, &_activation_time);
param_get(integration_time, &_integration_time);
param_get(transfer_time, &_transfer_time);
px4_ioctl(_gpio_fd, GPIO_SET_OUTPUT, pin);
if(_polarity == 0)
{
px4_ioctl(_gpio_fd, GPIO_SET, pin); /* GPIO pin pull high */
}
else if(_polarity == 1)
{
px4_ioctl(_gpio_fd, GPIO_CLEAR, pin); /* GPIO pin pull low */
}
else
{
warnx(" invalid trigger polarity setting. stopping.");
stop();
}
close(_gpio_fd);
poll(this); /* Trampoline call */
}
void
CameraTrigger::stop()
{
hrt_cancel(&_firecall);
hrt_cancel(&_pollcall);
if (camera_trigger::g_camera_trigger != nullptr) {
delete (camera_trigger::g_camera_trigger);
}
}
void
CameraTrigger::poll(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
bool updated;
orb_check(trig->_vcommand_sub, &updated);
if (updated) {
orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &trig->_command);
if(trig->_command.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL)
{
if(trig->_command.param1 < 1)
{
if(trig->_trigger_enabled)
{
trig->_trigger_enabled = false ;
}
}
else if(trig->_command.param1 >= 1)
{
if(!trig->_trigger_enabled)
{
trig->_trigger_enabled = true ;
}
}
// Set trigger rate from command
if(trig->_command.param2 > 0)
{
trig->_integration_time = trig->_command.param2;
param_set(trig->integration_time, &(trig->_integration_time));
}
}
}
if(!trig->_trigger_enabled) {
hrt_call_after(&trig->_pollcall, 1000, (hrt_callout)&CameraTrigger::poll, trig);
return;
}
else
{
engage(trig);
hrt_call_after(&trig->_firecall, trig->_activation_time*1000, (hrt_callout)&CameraTrigger::disengage, trig);
orb_copy(ORB_ID(sensor_combined), trig->_sensor_sub, &trig->_sensor);
trig->_trigger.timestamp = trig->_sensor.timestamp; /* get IMU timestamp */
trig->_trigger.seq = trig->_trigger_seq++;
if (trig->_trigger_pub != nullptr) {
orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trig->_trigger);
} else {
trig->_trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trig->_trigger);
}
hrt_call_after(&trig->_pollcall, (trig->_transfer_time + trig->_integration_time)*1000, (hrt_callout)&CameraTrigger::poll, trig);
}
}
void
CameraTrigger::engage(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
trig->_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if(trig->_gpio_fd == -1) return;
if(trig->_polarity == 0) // ACTIVE_LOW
{
px4_ioctl(trig->_gpio_fd, GPIO_CLEAR, trig->pin);
}
else if(trig->_polarity == 1) // ACTIVE_HIGH
{
px4_ioctl(trig->_gpio_fd, GPIO_SET, trig->pin);
}
close(trig->_gpio_fd);
}
void
CameraTrigger::disengage(void *arg)
{
CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg);
trig->_gpio_fd = open(PX4FMU_DEVICE_PATH, 0);
if(trig->_gpio_fd == -1) return;
if(trig->_polarity == 0) // ACTIVE_LOW
{
px4_ioctl(trig->_gpio_fd, GPIO_SET, trig->pin);
}
else if(trig->_polarity == 1) // ACTIVE_HIGH
{
px4_ioctl(trig->_gpio_fd, GPIO_CLEAR, trig->pin);
}
close(trig->_gpio_fd);
}
void
CameraTrigger::info()
{
warnx("Trigger state : %s", _trigger_enabled ? "enabled" : "disabled");
warnx("Trigger pin : %i", pin);
warnx("Trigger polarity : %s", _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW");
warnx("Shutter integration time : %.2f", (double)_integration_time);
}
static void usage()
{
errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n"
"\t-p <n>\tUse specified AUX OUT pin number (default: 1)"
);
}
int camera_trigger_main(int argc, char *argv[])
{
if (argc < 2) {
usage();
}
if (!strcmp(argv[1], "start")) {
if (camera_trigger::g_camera_trigger != nullptr) {
errx(0, "already running");
}
camera_trigger::g_camera_trigger = new CameraTrigger;
if (camera_trigger::g_camera_trigger == nullptr) {
errx(1, "alloc failed");
}
if (argc > 3) {
camera_trigger::g_camera_trigger->pin = (int)argv[3];
if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) {
warnx("starting trigger on pin : %li ", atoi(argv[3]));
camera_trigger::g_camera_trigger->pin = atoi(argv[3]);
}
else
{
usage();
}
}
camera_trigger::g_camera_trigger->start();
return 0;
}
if (camera_trigger::g_camera_trigger == nullptr) {
errx(1, "not running");
}
else if (!strcmp(argv[1], "stop")) {
camera_trigger::g_camera_trigger->stop();
}
else if (!strcmp(argv[1], "info")) {
camera_trigger::g_camera_trigger->info();
} else {
usage();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
#include "obj_tool.h"
#include "obj_plant.h"
void TBeing::doPlant(string arg)
{
TThing *t;
TTool *seeds;
int found=0;
if ((t = searchLinkedListVis(this, arg.c_str(), getStuff(), NULL))){
if((seeds=dynamic_cast<TTool *>(t))){
if(seeds->getToolType() == TOOL_SEED){
found=1;
}
}
}
if(!found){
sendTo("You need to specify some seeds to plant.\n\r");
return;
}
if(roomp->isFallSector() || roomp->isWaterSector() ||
roomp->isIndoorSector()){
sendTo("You can't plant anything here.\n\r");
return;
}
TThing *tcount;
for(tcount=roomp->getStuff(),count=0;tcount;tcount=tcount->nextThing){
if(dynamic_cast<TPlant *>(tcount))
++count;
}
if(count>=8){
sendTo("There isn't any room for more plants in here.\n\r");
return;
}
sendTo("You begin to plant some seeds.\n\r");
start_task(this, t, NULL, TASK_PLANT, "", 2, inRoom(), 0, 0, 5);
}
int task_plant(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
TTool *tt;
if (ch->utilityTaskCommand(cmd) ||
ch->nobrainerTaskCommand(cmd))
return FALSE;
// basic tasky safechecking
if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !obj){
act("You stop planting your seeds.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops planting seeds.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
return FALSE; // returning FALSE lets command be interpreted
}
tt=dynamic_cast<TTool *>(obj);
if (ch->task->timeLeft < 0){
act("You finish planting $p.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n finishes planting $p.",
TRUE, ch, obj, 0, TO_ROOM);
ch->stopTask();
TObj *tp;
TPlant *tplant;
tp = read_object(OBJ_GENERIC_PLANT, VIRTUAL);
if((tplant=dynamic_cast<TPlant *>(tp))){
tplant->setType(tt->objVnum()-13880);
tplant->updateDesc();
}
*ch->roomp += *tp;
if (tt->getToolUses() <= 0) {
act("You disgard $p because it is empty.",
FALSE, ch, tt, 0, TO_CHAR);
delete tt;
}
return FALSE;
}
switch (cmd) {
case CMD_TASK_CONTINUE:
ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3);
switch (ch->task->timeLeft) {
case 2:
act("You dig a little hole for some seeds from $p.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n digs a little hole.",
TRUE, ch, obj, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 1:
act("You put some seeds from $p into your hole.",
FALSE, ch, tt, 0, TO_CHAR);
act("$n puts some seeds from $p into the hole.",
TRUE, ch, tt, 0, TO_ROOM);
ch->task->timeLeft--;
tt->addToToolUses(-1);
break;
case 0:
act("You cover up the hole.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n covers up the hole.",
TRUE, ch, obj, 0, TO_ROOM);
ch->task->timeLeft--;
break;
}
break;
case CMD_ABORT:
case CMD_STOP:
act("You stop planting seeds.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops planting seeds.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
break;
case CMD_TASK_FIGHTING:
ch->sendTo("You can't properly plant seeds while under attack.\n\r");
ch->stopTask();
break;
default:
if (cmd < MAX_CMD_LIST)
warn_busy(ch);
break; // eat the command
}
return TRUE;
}
<commit_msg>typo fix<commit_after>#include "stdsneezy.h"
#include "obj_tool.h"
#include "obj_plant.h"
void TBeing::doPlant(string arg)
{
TThing *t;
TTool *seeds;
int found=0, count;
if ((t = searchLinkedListVis(this, arg.c_str(), getStuff(), NULL))){
if((seeds=dynamic_cast<TTool *>(t))){
if(seeds->getToolType() == TOOL_SEED){
found=1;
}
}
}
if(!found){
sendTo("You need to specify some seeds to plant.\n\r");
return;
}
if(roomp->isFallSector() || roomp->isWaterSector() ||
roomp->isIndoorSector()){
sendTo("You can't plant anything here.\n\r");
return;
}
TThing *tcount;
for(tcount=roomp->getStuff(),count=0;tcount;tcount=tcount->nextThing){
if(dynamic_cast<TPlant *>(tcount))
++count;
}
if(count>=8){
sendTo("There isn't any room for more plants in here.\n\r");
return;
}
sendTo("You begin to plant some seeds.\n\r");
start_task(this, t, NULL, TASK_PLANT, "", 2, inRoom(), 0, 0, 5);
}
int task_plant(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
TTool *tt;
if (ch->utilityTaskCommand(cmd) ||
ch->nobrainerTaskCommand(cmd))
return FALSE;
// basic tasky safechecking
if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !obj){
act("You stop planting your seeds.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops planting seeds.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
return FALSE; // returning FALSE lets command be interpreted
}
tt=dynamic_cast<TTool *>(obj);
if (ch->task->timeLeft < 0){
act("You finish planting $p.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n finishes planting $p.",
TRUE, ch, obj, 0, TO_ROOM);
ch->stopTask();
TObj *tp;
TPlant *tplant;
tp = read_object(OBJ_GENERIC_PLANT, VIRTUAL);
if((tplant=dynamic_cast<TPlant *>(tp))){
tplant->setType(tt->objVnum()-13880);
tplant->updateDesc();
}
*ch->roomp += *tp;
if (tt->getToolUses() <= 0) {
act("You disgard $p because it is empty.",
FALSE, ch, tt, 0, TO_CHAR);
delete tt;
}
return FALSE;
}
switch (cmd) {
case CMD_TASK_CONTINUE:
ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3);
switch (ch->task->timeLeft) {
case 2:
act("You dig a little hole for some seeds from $p.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n digs a little hole.",
TRUE, ch, obj, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 1:
act("You put some seeds from $p into your hole.",
FALSE, ch, tt, 0, TO_CHAR);
act("$n puts some seeds from $p into the hole.",
TRUE, ch, tt, 0, TO_ROOM);
ch->task->timeLeft--;
tt->addToToolUses(-1);
break;
case 0:
act("You cover up the hole.",
FALSE, ch, obj, 0, TO_CHAR);
act("$n covers up the hole.",
TRUE, ch, obj, 0, TO_ROOM);
ch->task->timeLeft--;
break;
}
break;
case CMD_ABORT:
case CMD_STOP:
act("You stop planting seeds.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops planting seeds.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
break;
case CMD_TASK_FIGHTING:
ch->sendTo("You can't properly plant seeds while under attack.\n\r");
ch->stopTask();
break;
default:
if (cmd < MAX_CMD_LIST)
warn_busy(ch);
break; // eat the command
}
return TRUE;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
class RenameRewriter : public clang::Rewriter
{
/// Old names -> new names map.
std::map<std::string, std::string> maNameMap;
bool mbDump;
public:
RenameRewriter(const std::map<std::string, std::string>& rNameMap, bool bDump)
: maNameMap(rNameMap),
mbDump(bDump)
{
}
const std::map<std::string, std::string>& getNameMap()
{
return maNameMap;
}
bool getDump()
{
return mbDump;
}
};
class RenameVisitor : public clang::RecursiveASTVisitor<RenameVisitor>
{
RenameRewriter& mrRewriter;
// A set of handled locations, so in case a location would be handled
// multiple times due to macro usage, we only do the rewrite once.
// Otherwise an A -> BA replacement would be done twice.
std::set<clang::SourceLocation> maHandledLocations;
public:
explicit RenameVisitor(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
/*
* class C
* {
* public:
* int nX; <- Handles this declaration.
* };
*/
bool VisitFieldDecl(clang::FieldDecl* pDecl)
{
// Qualified name includes "C::" as a prefix, normal name does not.
std::string aName = pDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
mrRewriter.ReplaceText(pDecl->getLocation(), pDecl->getNameAsString().length(), it->second);
return true;
}
/*
* C::C()
* : nX(0) <- Handles this initializer.
* {
* }
*/
bool VisitCXXConstructorDecl(clang::CXXConstructorDecl* pDecl)
{
for (clang::CXXConstructorDecl::init_const_iterator itInit = pDecl->init_begin(); itInit != pDecl->init_end(); ++itInit)
{
const clang::CXXCtorInitializer* pInitializer = *itInit;
if (const clang::FieldDecl* pFieldDecl = pInitializer->getAnyMember())
{
std::string aName = pFieldDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
mrRewriter.ReplaceText(pInitializer->getSourceLocation(), pFieldDecl->getNameAsString().length(), it->second);
}
}
return true;
}
/*
* C aC;
* aC.nX = 1; <- Handles e.g. this...
* int y = aC.nX; <- ...and this.
*/
bool VisitMemberExpr(clang::MemberExpr* pExpr)
{
if (clang::ValueDecl* pDecl = pExpr->getMemberDecl())
{
std::string aName = pDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
{
clang::SourceLocation aLocation = pExpr->getMemberLoc();
if (pExpr->getMemberLoc().isMacroID())
/*
* int foo(int x);
* #define FOO(a) foo(a)
* FOO(aC.nX); <- Handles this.
*/
aLocation = mrRewriter.getSourceMgr().getImmediateSpellingLoc(aLocation);
if (maHandledLocations.find(aLocation) == maHandledLocations.end())
{
mrRewriter.ReplaceText(aLocation, pDecl->getNameAsString().length(), it->second);
maHandledLocations.insert(aLocation);
}
}
}
return true;
}
};
class RenameASTConsumer : public clang::ASTConsumer
{
RenameRewriter& mrRewriter;
std::string getNewName(const clang::FileEntry& rEntry)
{
std::stringstream ss;
ss << rEntry.getName();
ss << ".new";
return ss.str();
}
public:
RenameASTConsumer(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
virtual void HandleTranslationUnit(clang::ASTContext& rContext)
{
if (rContext.getDiagnostics().hasErrorOccurred())
return;
RenameVisitor aVisitor(mrRewriter);
mrRewriter.setSourceMgr(rContext.getSourceManager(), rContext.getLangOpts());
aVisitor.TraverseDecl(rContext.getTranslationUnitDecl());
for (clang::Rewriter::buffer_iterator it = mrRewriter.buffer_begin(); it != mrRewriter.buffer_end(); ++it)
{
if (mrRewriter.getDump())
it->second.write(llvm::errs());
else
{
const clang::FileEntry* pEntry = rContext.getSourceManager().getFileEntryForID(it->first);
if (!pEntry)
continue;
std::string aNewName = getNewName(*pEntry);
std::string aError;
std::unique_ptr<llvm::raw_fd_ostream> pStream(new llvm::raw_fd_ostream(aNewName.c_str(), aError, llvm::sys::fs::F_None));
if (aError.empty())
it->second.write(*pStream);
}
}
}
};
class RenameFrontendAction
{
RenameRewriter& mrRewriter;
public:
RenameFrontendAction(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
clang::ASTConsumer* newASTConsumer()
{
return new RenameASTConsumer(mrRewriter);
}
};
/// Parses rCsv and puts the first two column of it into rNameMap.
static void parseCsv(const std::string& rCsv, std::map<std::string, std::string>& rNameMap)
{
std::ifstream aStream(rCsv);
if (!aStream.is_open())
{
std::cerr << "parseCsv: failed to open " << rCsv << std::endl;
return;
}
std::string aLine;
while (std::getline(aStream, aLine))
{
std::stringstream ss(aLine);
std::string aOldName;
if (!std::getline(ss, aOldName, ','))
{
std::cerr << "parseCsv: first std::getline() failed for line '" << aLine << "'" << std::endl;
return;
}
std::string aNewName;
if (!std::getline(ss, aNewName, ','))
{
std::cerr << "parseCsv: second std::getline() failed for line '" << aLine << "'" << std::endl;
return;
}
rNameMap[aOldName] = aNewName;
}
aStream.close();
}
int main(int argc, const char** argv)
{
llvm::cl::OptionCategory aCategory("rename options");
llvm::cl::opt<std::string> aOldName("old-name",
llvm::cl::desc("Old, qualified name (Class::member)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<std::string> aNewName("new-name",
llvm::cl::desc("New, non-qualified name (without Class::)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<std::string> aCsv("csv",
llvm::cl::desc("Path to a CSV file, containing multiple renames -- seprator must be a comma (,)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<bool> bDump("dump",
llvm::cl::desc("Dump output on the console instead of writing to .new files."),
llvm::cl::cat(aCategory));
clang::tooling::CommonOptionsParser aParser(argc, argv, aCategory);
std::map<std::string, std::string> aNameMap;
if (!aOldName.empty() && !aNewName.empty())
aNameMap[aOldName] = aNewName;
else if (!aCsv.empty())
parseCsv(aCsv, aNameMap);
else
{
std::cerr << "either -old-name + -new-name or -csv is required." << std::endl;
return 1;
}
clang::tooling::ClangTool aTool(aParser.getCompilations(), aParser.getSourcePathList());
RenameRewriter aRewriter(aNameMap, bDump);
RenameFrontendAction aAction(aRewriter);
std::unique_ptr<clang::tooling::FrontendActionFactory> pFactory = clang::tooling::newFrontendActionFactory(&aAction);
return aTool.run(pFactory.get());
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>clang: handle nested macros<commit_after>#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
class RenameRewriter : public clang::Rewriter
{
/// Old names -> new names map.
std::map<std::string, std::string> maNameMap;
bool mbDump;
public:
RenameRewriter(const std::map<std::string, std::string>& rNameMap, bool bDump)
: maNameMap(rNameMap),
mbDump(bDump)
{
}
const std::map<std::string, std::string>& getNameMap()
{
return maNameMap;
}
bool getDump()
{
return mbDump;
}
};
class RenameVisitor : public clang::RecursiveASTVisitor<RenameVisitor>
{
RenameRewriter& mrRewriter;
// A set of handled locations, so in case a location would be handled
// multiple times due to macro usage, we only do the rewrite once.
// Otherwise an A -> BA replacement would be done twice.
std::set<clang::SourceLocation> maHandledLocations;
public:
explicit RenameVisitor(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
/*
* class C
* {
* public:
* int nX; <- Handles this declaration.
* };
*/
bool VisitFieldDecl(clang::FieldDecl* pDecl)
{
// Qualified name includes "C::" as a prefix, normal name does not.
std::string aName = pDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
mrRewriter.ReplaceText(pDecl->getLocation(), pDecl->getNameAsString().length(), it->second);
return true;
}
/*
* C::C()
* : nX(0) <- Handles this initializer.
* {
* }
*/
bool VisitCXXConstructorDecl(clang::CXXConstructorDecl* pDecl)
{
for (clang::CXXConstructorDecl::init_const_iterator itInit = pDecl->init_begin(); itInit != pDecl->init_end(); ++itInit)
{
const clang::CXXCtorInitializer* pInitializer = *itInit;
if (const clang::FieldDecl* pFieldDecl = pInitializer->getAnyMember())
{
std::string aName = pFieldDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
mrRewriter.ReplaceText(pInitializer->getSourceLocation(), pFieldDecl->getNameAsString().length(), it->second);
}
}
return true;
}
/*
* C aC;
* aC.nX = 1; <- Handles e.g. this...
* int y = aC.nX; <- ...and this.
*/
bool VisitMemberExpr(clang::MemberExpr* pExpr)
{
if (clang::ValueDecl* pDecl = pExpr->getMemberDecl())
{
std::string aName = pDecl->getQualifiedNameAsString();
const std::map<std::string, std::string>::const_iterator it = mrRewriter.getNameMap().find(aName);
if (it != mrRewriter.getNameMap().end())
{
clang::SourceLocation aLocation = pExpr->getMemberLoc();
if (pExpr->getMemberLoc().isMacroID())
/*
* int foo(int x);
* #define FOO(a) foo(a)
* FOO(aC.nX); <- Handles this.
*/
aLocation = mrRewriter.getSourceMgr().getSpellingLoc(aLocation);
if (maHandledLocations.find(aLocation) == maHandledLocations.end())
{
mrRewriter.ReplaceText(aLocation, pDecl->getNameAsString().length(), it->second);
maHandledLocations.insert(aLocation);
}
}
}
return true;
}
};
class RenameASTConsumer : public clang::ASTConsumer
{
RenameRewriter& mrRewriter;
std::string getNewName(const clang::FileEntry& rEntry)
{
std::stringstream ss;
ss << rEntry.getName();
ss << ".new";
return ss.str();
}
public:
RenameASTConsumer(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
virtual void HandleTranslationUnit(clang::ASTContext& rContext)
{
if (rContext.getDiagnostics().hasErrorOccurred())
return;
RenameVisitor aVisitor(mrRewriter);
mrRewriter.setSourceMgr(rContext.getSourceManager(), rContext.getLangOpts());
aVisitor.TraverseDecl(rContext.getTranslationUnitDecl());
for (clang::Rewriter::buffer_iterator it = mrRewriter.buffer_begin(); it != mrRewriter.buffer_end(); ++it)
{
if (mrRewriter.getDump())
it->second.write(llvm::errs());
else
{
const clang::FileEntry* pEntry = rContext.getSourceManager().getFileEntryForID(it->first);
if (!pEntry)
continue;
std::string aNewName = getNewName(*pEntry);
std::string aError;
std::unique_ptr<llvm::raw_fd_ostream> pStream(new llvm::raw_fd_ostream(aNewName.c_str(), aError, llvm::sys::fs::F_None));
if (aError.empty())
it->second.write(*pStream);
}
}
}
};
class RenameFrontendAction
{
RenameRewriter& mrRewriter;
public:
RenameFrontendAction(RenameRewriter& rRewriter)
: mrRewriter(rRewriter)
{
}
clang::ASTConsumer* newASTConsumer()
{
return new RenameASTConsumer(mrRewriter);
}
};
/// Parses rCsv and puts the first two column of it into rNameMap.
static void parseCsv(const std::string& rCsv, std::map<std::string, std::string>& rNameMap)
{
std::ifstream aStream(rCsv);
if (!aStream.is_open())
{
std::cerr << "parseCsv: failed to open " << rCsv << std::endl;
return;
}
std::string aLine;
while (std::getline(aStream, aLine))
{
std::stringstream ss(aLine);
std::string aOldName;
if (!std::getline(ss, aOldName, ','))
{
std::cerr << "parseCsv: first std::getline() failed for line '" << aLine << "'" << std::endl;
return;
}
std::string aNewName;
if (!std::getline(ss, aNewName, ','))
{
std::cerr << "parseCsv: second std::getline() failed for line '" << aLine << "'" << std::endl;
return;
}
rNameMap[aOldName] = aNewName;
}
aStream.close();
}
int main(int argc, const char** argv)
{
llvm::cl::OptionCategory aCategory("rename options");
llvm::cl::opt<std::string> aOldName("old-name",
llvm::cl::desc("Old, qualified name (Class::member)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<std::string> aNewName("new-name",
llvm::cl::desc("New, non-qualified name (without Class::)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<std::string> aCsv("csv",
llvm::cl::desc("Path to a CSV file, containing multiple renames -- seprator must be a comma (,)."),
llvm::cl::cat(aCategory));
llvm::cl::opt<bool> bDump("dump",
llvm::cl::desc("Dump output on the console instead of writing to .new files."),
llvm::cl::cat(aCategory));
clang::tooling::CommonOptionsParser aParser(argc, argv, aCategory);
std::map<std::string, std::string> aNameMap;
if (!aOldName.empty() && !aNewName.empty())
aNameMap[aOldName] = aNewName;
else if (!aCsv.empty())
parseCsv(aCsv, aNameMap);
else
{
std::cerr << "either -old-name + -new-name or -csv is required." << std::endl;
return 1;
}
clang::tooling::ClangTool aTool(aParser.getCompilations(), aParser.getSourcePathList());
RenameRewriter aRewriter(aNameMap, bDump);
RenameFrontendAction aAction(aRewriter);
std::unique_ptr<clang::tooling::FrontendActionFactory> pFactory = clang::tooling::newFrontendActionFactory(&aAction);
return aTool.run(pFactory.get());
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* mem_cache.cpp
*
* Created: 3/6/2013
* Author: Collin Kidder
*/
#ifdef __arm__ // Arduino Due specific implementation
#include "mem_cache.h"
extern volatile uint8_t AgingTimer;
//this function flushes the first dirty page it finds. It should try to wait until enough time as elapsed since
//a previous page has been written.
void CMEMCACHE::FlushSinglePage()
{
U8 c;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (pages[c].dirty) {
cache_writepage(c);
pages[c].dirty = false;
pages[c].age = 0; //freshly flushed!
return;
}
}
}
//Flush every dirty page. It will block for 7ms per page so maybe things will be blocked for a long, long time
//DO NOT USE THIS FUNCTION UNLESS YOU CAN ACCEPT THAT!
void CMEMCACHE::FlushAllPages()
{
U8 c;
for (c = 0; c < NUM_CACHED_PAGES;c++) {
if (pages[c].dirty) { //found a dirty page so flush it
cache_writepage(c);
pages[c].dirty = false;
delay(10); //10ms is longest it would take to write a page according to datasheet
}
}
}
void CMEMCACHE::FlushPage(uint8_t page) {
if (pages[page].dirty) {
cache_writepage(page);
pages[page].dirty = false;
pages[page].age = 0; //freshly flushed!
}
}
void CMEMCACHE::handleTick()
{
U8 c;
if (AgingTimer > AGING_PERIOD)
{
AgingTimer -= AGING_PERIOD;
cache_age();
for (c=0;c<NUM_CACHED_PAGES;c++) {
if ((pages[c].age == MAX_AGE) && (pages[c].dirty)) {
FlushPage(c);
return;
}
}
}
}
void CMEMCACHE::InvalidatePage(uint8_t page)
{
if (page > NUM_CACHED_PAGES - 1) return; //invalid page, buddy!
if (pages[page].dirty) {
cache_writepage(page);
}
pages[page].dirty = false;
pages[page].address = 0xFFFFFF;
pages[page].age = 0;
}
void CMEMCACHE::InvalidateAddress(uint32_t address)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c != 0xFF) InvalidatePage(c);
}
void CMEMCACHE::InvalidateAll()
{
uint8_t c;
for (c=0;c<NUM_CACHED_PAGES;c++) {
InvalidatePage(c);
}
}
void CMEMCACHE::AgeFullyPage(uint8_t page)
{
if (page < NUM_CACHED_PAGES) { //if we did indeed have that page in cache
pages[page].age = MAX_AGE;
}
}
void CMEMCACHE::AgeFullyAddress(uint32_t address)
{
uint8_t thisCache;
uint32_t page_addr;
page_addr = address >> 8; //kick it down to the page we're talking about
thisCache = cache_hit(page_addr);
if (thisCache != 0xFF) { //if we did indeed have that page in cache
pages[thisCache].age = MAX_AGE;
}
}
boolean CMEMCACHE::Write(uint32_t address, uint8_t valu)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) {
c = cache_findpage(); //try to free up a page
if (c != 0xFF) c = cache_readpage(addr); //and populate it with the existing data
}
if (c != 0xFF) {
pages[c].data[(uint16_t)(address & 0x00FF)] = valu;
pages[c].dirty = true;
pages[c].address = addr; //set this in case we actually are setting up a new cache page
return true;
}
return false;
}
boolean CMEMCACHE::Write(uint32_t address, uint16_t valu)
{
boolean result;
result = Write(address, &valu, 2);
return result;
}
boolean CMEMCACHE::Write(uint32_t address, uint32_t valu)
{
boolean result;
result = Write(address, &valu, 4);
return result;
}
boolean CMEMCACHE::Write(uint32_t address, void* data, uint16_t len)
{
uint32_t addr;
uint8_t c;
uint16_t count;
for (count = 0; count < len; count++) {
addr = (address+count) >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) {
c = cache_findpage(); //try to find a page that either isn't loaded or isn't dirty
if (c != 0xFF) c = cache_readpage(addr); //and populate it with the existing data
}
if (c != 0xFF) { //could we find a suitable cache page to write to?
pages[c].data[(uint16_t)((address+count) & 0x00FF)] = *(uint8_t *)(data + count);
pages[c].dirty = true;
pages[c].address = addr; //set this in case we actually are setting up a new cache page
}
else break;
}
if (c != 0xFF) return true; //all ok!
return false;
}
boolean CMEMCACHE::Read(uint32_t address, uint8_t* valu)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) { //page isn't cached. Search the cache, potentially dump a page and bring this one in
c = cache_readpage(addr);
}
if (c != 0xFF) {
*valu = pages[c].data[(uint16_t)(address & 0x00FF)];
if (!pages[c].dirty) pages[c].age = 0; //reset age since we just used it
return true; //all ok!
}
else {
return false;
}
}
boolean CMEMCACHE::Read(uint32_t address, uint16_t* valu)
{
boolean result;
result = Read(address, valu, 2);
return result;
}
boolean CMEMCACHE::Read(uint32_t address, uint32_t* valu)
{
boolean result;
result = Read(address, valu, 4);
return result;
}
boolean CMEMCACHE::Read(uint32_t address, void* data, uint16_t len)
{
uint32_t addr;
uint8_t c;
uint16_t count;
for (count = 0; count < len; count++) {
addr = (address + count) >> 8;
c = cache_hit(addr);
if (c == 0xFF) { //page isn't cached. Search the cache, potentially dump a page and bring this one in
c = cache_readpage(addr);
}
if (c != 0xFF) {
*(uint8_t *)(data + count) = pages[c].data[(uint16_t)((address+count) & 0x00FF)];
if (!pages[c].dirty) pages[c].age = 0; //reset age since we just used it
}
else break; //bust the for loop if we run into trouble
}
if (c != 0xFF) return true; //all ok!
return false;
}
CMEMCACHE::CMEMCACHE()
{
U8 c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
pages[c].address = 0xFFFFFF; //maximum number. This is way over what our chip will actually support so it signals unused
pages[c].age = 0;
pages[c].dirty = false;
}
//WriteTimer = 0;
AgingTimer = 0;
//digital pin 19 is connected to the write protect function of the EEPROM. It is active high so set it low to enable writes
pinMode(19, OUTPUT);
digitalWrite(19, LOW);
}
boolean CMEMCACHE::isWriting()
{
//if (WriteTimer) return true;
return false;
}
uint8_t CMEMCACHE::cache_hit(uint32_t address)
{
uint8_t c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
if (pages[c].address == address) {
return c;
}
}
return 0xFF;
}
void CMEMCACHE::cache_age()
{
uint8_t c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
if (pages[c].age < MAX_AGE) {
pages[c].age++;
}
}
}
//try to find an empty page or one that can be removed from cache
uint8_t CMEMCACHE::cache_findpage()
{
uint8_t c;
uint8_t old_c, old_v;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (pages[c].address == 0xFFFFFF) { //found an empty cache page so populate it and return its number
pages[c].age = 0;
pages[c].dirty = false;
return c;
}
}
//if we got here then there are no free pages so scan to find the oldest one which isn't dirty
old_c = 0xFF;
old_v = 0;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (!pages[c].dirty && pages[c].age >= old_v) {
old_c = c;
old_v = pages[c].age;
}
}
if (old_c == 0xFF) { //no pages were not dirty - try to free one up
FlushSinglePage(); //try to free up a page
//now try to find the free page (if one was freed)
old_v = 0;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (!pages[c].dirty && pages[c].age >= old_v) {
old_c = c;
old_v = pages[c].age;
}
}
if (old_c == 0xFF) return 0xFF; //if nothing worked then give up
}
//If we got to this point then we have a page to use
pages[old_c].age = 0;
pages[old_c].dirty = false;
pages[old_c].address = 0xFFFFFF; //mark it unused
return old_c;
}
uint8_t CMEMCACHE::cache_readpage(uint32_t addr)
{
uint16_t c,d,e;
uint32_t address = addr << 8;
uint8_t buffer[3];
uint8_t i2c_id;
c = cache_findpage();
SerialUSB.print("r");
if (c != 0xFF) {
buffer[0] = ((address & 0xFF00) >> 8);
//buffer[1] = (address & 0x00FF);
buffer[1] = 0; //the pages are 256 bytes so the start of a page is always 00 for the LSB
i2c_id = 0b01010000 + ((address >> 16) & 0x03); //10100 is the chip ID then the two upper bits of the address
Wire.beginTransmission(i2c_id);
Wire.write(buffer, 2);
Wire.endTransmission(false); //do NOT generate stop
//delayMicroseconds(50); //give TWI some time to send and chip some time to get page
Wire.requestFrom(i2c_id, (uint8_t)256); //this will generate stop though.
for (e = 0; e < 256; e++)
{
if(Wire.available())
{
d = Wire.read(); // receive a byte as character
pages[c].data[e] = d;
}
}
pages[c].address = addr;
pages[c].age = 0;
pages[c].dirty = false;
}
return c;
}
boolean CMEMCACHE::cache_writepage(uint8_t page)
{
uint16_t d;
uint32_t addr;
uint8_t buffer[258];
uint8_t i2c_id;
addr = pages[page].address << 8;
buffer[0] = ((addr & 0xFF00) >> 8);
//buffer[1] = (addr & 0x00FF);
buffer[1] = 0; //pages are 256 bytes so LSB is always 0 for the start of a page
i2c_id = 0b01010000 + ((addr >> 16) & 0x03); //10100 is the chip ID then the two upper bits of the address
for (d = 0; d < 256; d++) {
buffer[d + 2] = pages[page].data[d];
}
Wire.beginTransmission(i2c_id);
Wire.write(buffer, 258);
Wire.endTransmission(true);
}
CMEMCACHE MemCache;
#endif
<commit_msg>Removed improper cast in memcache page read<commit_after>/*
* mem_cache.cpp
*
* Created: 3/6/2013
* Author: Collin Kidder
*/
#ifdef __arm__ // Arduino Due specific implementation
#include "mem_cache.h"
extern volatile uint8_t AgingTimer;
//this function flushes the first dirty page it finds. It should try to wait until enough time as elapsed since
//a previous page has been written.
void CMEMCACHE::FlushSinglePage()
{
U8 c;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (pages[c].dirty) {
cache_writepage(c);
pages[c].dirty = false;
pages[c].age = 0; //freshly flushed!
return;
}
}
}
//Flush every dirty page. It will block for 7ms per page so maybe things will be blocked for a long, long time
//DO NOT USE THIS FUNCTION UNLESS YOU CAN ACCEPT THAT!
void CMEMCACHE::FlushAllPages()
{
U8 c;
for (c = 0; c < NUM_CACHED_PAGES;c++) {
if (pages[c].dirty) { //found a dirty page so flush it
cache_writepage(c);
pages[c].dirty = false;
delay(10); //10ms is longest it would take to write a page according to datasheet
}
}
}
void CMEMCACHE::FlushPage(uint8_t page) {
if (pages[page].dirty) {
cache_writepage(page);
pages[page].dirty = false;
pages[page].age = 0; //freshly flushed!
}
}
void CMEMCACHE::handleTick()
{
U8 c;
if (AgingTimer > AGING_PERIOD)
{
AgingTimer -= AGING_PERIOD;
cache_age();
for (c=0;c<NUM_CACHED_PAGES;c++) {
if ((pages[c].age == MAX_AGE) && (pages[c].dirty)) {
FlushPage(c);
return;
}
}
}
}
void CMEMCACHE::InvalidatePage(uint8_t page)
{
if (page > NUM_CACHED_PAGES - 1) return; //invalid page, buddy!
if (pages[page].dirty) {
cache_writepage(page);
}
pages[page].dirty = false;
pages[page].address = 0xFFFFFF;
pages[page].age = 0;
}
void CMEMCACHE::InvalidateAddress(uint32_t address)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c != 0xFF) InvalidatePage(c);
}
void CMEMCACHE::InvalidateAll()
{
uint8_t c;
for (c=0;c<NUM_CACHED_PAGES;c++) {
InvalidatePage(c);
}
}
void CMEMCACHE::AgeFullyPage(uint8_t page)
{
if (page < NUM_CACHED_PAGES) { //if we did indeed have that page in cache
pages[page].age = MAX_AGE;
}
}
void CMEMCACHE::AgeFullyAddress(uint32_t address)
{
uint8_t thisCache;
uint32_t page_addr;
page_addr = address >> 8; //kick it down to the page we're talking about
thisCache = cache_hit(page_addr);
if (thisCache != 0xFF) { //if we did indeed have that page in cache
pages[thisCache].age = MAX_AGE;
}
}
boolean CMEMCACHE::Write(uint32_t address, uint8_t valu)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) {
c = cache_findpage(); //try to free up a page
if (c != 0xFF) c = cache_readpage(addr); //and populate it with the existing data
}
if (c != 0xFF) {
pages[c].data[(uint16_t)(address & 0x00FF)] = valu;
pages[c].dirty = true;
pages[c].address = addr; //set this in case we actually are setting up a new cache page
return true;
}
return false;
}
boolean CMEMCACHE::Write(uint32_t address, uint16_t valu)
{
boolean result;
result = Write(address, &valu, 2);
return result;
}
boolean CMEMCACHE::Write(uint32_t address, uint32_t valu)
{
boolean result;
result = Write(address, &valu, 4);
return result;
}
boolean CMEMCACHE::Write(uint32_t address, void* data, uint16_t len)
{
uint32_t addr;
uint8_t c;
uint16_t count;
for (count = 0; count < len; count++) {
addr = (address+count) >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) {
c = cache_findpage(); //try to find a page that either isn't loaded or isn't dirty
if (c != 0xFF) c = cache_readpage(addr); //and populate it with the existing data
}
if (c != 0xFF) { //could we find a suitable cache page to write to?
pages[c].data[(uint16_t)((address+count) & 0x00FF)] = *(uint8_t *)(data + count);
pages[c].dirty = true;
pages[c].address = addr; //set this in case we actually are setting up a new cache page
}
else break;
}
if (c != 0xFF) return true; //all ok!
return false;
}
boolean CMEMCACHE::Read(uint32_t address, uint8_t* valu)
{
uint32_t addr;
uint8_t c;
addr = address >> 8; //kick it down to the page we're talking about
c = cache_hit(addr);
if (c == 0xFF) { //page isn't cached. Search the cache, potentially dump a page and bring this one in
c = cache_readpage(addr);
}
if (c != 0xFF) {
*valu = pages[c].data[(uint16_t)(address & 0x00FF)];
if (!pages[c].dirty) pages[c].age = 0; //reset age since we just used it
return true; //all ok!
}
else {
return false;
}
}
boolean CMEMCACHE::Read(uint32_t address, uint16_t* valu)
{
boolean result;
result = Read(address, valu, 2);
return result;
}
boolean CMEMCACHE::Read(uint32_t address, uint32_t* valu)
{
boolean result;
result = Read(address, valu, 4);
return result;
}
boolean CMEMCACHE::Read(uint32_t address, void* data, uint16_t len)
{
uint32_t addr;
uint8_t c;
uint16_t count;
for (count = 0; count < len; count++) {
addr = (address + count) >> 8;
c = cache_hit(addr);
if (c == 0xFF) { //page isn't cached. Search the cache, potentially dump a page and bring this one in
c = cache_readpage(addr);
}
if (c != 0xFF) {
*(uint8_t *)(data + count) = pages[c].data[(uint16_t)((address+count) & 0x00FF)];
if (!pages[c].dirty) pages[c].age = 0; //reset age since we just used it
}
else break; //bust the for loop if we run into trouble
}
if (c != 0xFF) return true; //all ok!
return false;
}
CMEMCACHE::CMEMCACHE()
{
U8 c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
pages[c].address = 0xFFFFFF; //maximum number. This is way over what our chip will actually support so it signals unused
pages[c].age = 0;
pages[c].dirty = false;
}
//WriteTimer = 0;
AgingTimer = 0;
//digital pin 19 is connected to the write protect function of the EEPROM. It is active high so set it low to enable writes
pinMode(19, OUTPUT);
digitalWrite(19, LOW);
}
boolean CMEMCACHE::isWriting()
{
//if (WriteTimer) return true;
return false;
}
uint8_t CMEMCACHE::cache_hit(uint32_t address)
{
uint8_t c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
if (pages[c].address == address) {
return c;
}
}
return 0xFF;
}
void CMEMCACHE::cache_age()
{
uint8_t c;
for (c = 0; c < NUM_CACHED_PAGES; c++) {
if (pages[c].age < MAX_AGE) {
pages[c].age++;
}
}
}
//try to find an empty page or one that can be removed from cache
uint8_t CMEMCACHE::cache_findpage()
{
uint8_t c;
uint8_t old_c, old_v;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (pages[c].address == 0xFFFFFF) { //found an empty cache page so populate it and return its number
pages[c].age = 0;
pages[c].dirty = false;
return c;
}
}
//if we got here then there are no free pages so scan to find the oldest one which isn't dirty
old_c = 0xFF;
old_v = 0;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (!pages[c].dirty && pages[c].age >= old_v) {
old_c = c;
old_v = pages[c].age;
}
}
if (old_c == 0xFF) { //no pages were not dirty - try to free one up
FlushSinglePage(); //try to free up a page
//now try to find the free page (if one was freed)
old_v = 0;
for (c=0;c<NUM_CACHED_PAGES;c++) {
if (!pages[c].dirty && pages[c].age >= old_v) {
old_c = c;
old_v = pages[c].age;
}
}
if (old_c == 0xFF) return 0xFF; //if nothing worked then give up
}
//If we got to this point then we have a page to use
pages[old_c].age = 0;
pages[old_c].dirty = false;
pages[old_c].address = 0xFFFFFF; //mark it unused
return old_c;
}
uint8_t CMEMCACHE::cache_readpage(uint32_t addr)
{
uint16_t c,d,e;
uint32_t address = addr << 8;
uint8_t buffer[3];
uint8_t i2c_id;
c = cache_findpage();
// SerialUSB.print("r");
if (c != 0xFF) {
buffer[0] = ((address & 0xFF00) >> 8);
//buffer[1] = (address & 0x00FF);
buffer[1] = 0; //the pages are 256 bytes so the start of a page is always 00 for the LSB
i2c_id = 0b01010000 + ((address >> 16) & 0x03); //10100 is the chip ID then the two upper bits of the address
Wire.beginTransmission(i2c_id);
Wire.write(buffer, 2);
Wire.endTransmission(false); //do NOT generate stop
//delayMicroseconds(50); //give TWI some time to send and chip some time to get page
Wire.requestFrom(i2c_id, 256); //this will generate stop though.
for (e = 0; e < 256; e++)
{
if(Wire.available())
{
d = Wire.read(); // receive a byte as character
pages[c].data[e] = d;
}
}
pages[c].address = addr;
pages[c].age = 0;
pages[c].dirty = false;
}
return c;
}
boolean CMEMCACHE::cache_writepage(uint8_t page)
{
uint16_t d;
uint32_t addr;
uint8_t buffer[258];
uint8_t i2c_id;
addr = pages[page].address << 8;
buffer[0] = ((addr & 0xFF00) >> 8);
//buffer[1] = (addr & 0x00FF);
buffer[1] = 0; //pages are 256 bytes so LSB is always 0 for the start of a page
i2c_id = 0b01010000 + ((addr >> 16) & 0x03); //10100 is the chip ID then the two upper bits of the address
for (d = 0; d < 256; d++) {
buffer[d + 2] = pages[page].data[d];
}
Wire.beginTransmission(i2c_id);
Wire.write(buffer, 258);
Wire.endTransmission(true);
}
CMEMCACHE MemCache;
#endif
<|endoftext|> |
<commit_before>#include <leddevice/LedDeviceWrapper.h>
#include <leddevice/LedDevice.h>
#include <leddevice/LedDeviceFactory.h>
// following file is auto generated by cmake! it contains all available leddevice headers
#include "LedDevice_headers.h"
// util
#include <hyperion/Hyperion.h>
#include <utils/JsonUtils.h>
// qt
#include <QThread>
#include <QDir>
LedDeviceRegistry LedDeviceWrapper::_ledDeviceMap = LedDeviceRegistry();
LedDeviceWrapper::LedDeviceWrapper(Hyperion* hyperion)
: QObject(hyperion)
, _hyperion(hyperion)
, _ledDevice(nullptr)
, _enabled(true)
{
// prepare the device constrcutor map
#define REGISTER(className) LedDeviceWrapper::addToDeviceMap(QString(#className).toLower(), LedDevice##className::construct);
// the REGISTER() calls are autogenerated by cmake.
#include "LedDevice_register.cpp"
#undef REGISTER
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, true);
}
LedDeviceWrapper::~LedDeviceWrapper()
{
stopDeviceThread();
}
void LedDeviceWrapper::createLedDevice(const QJsonObject& config)
{
if(_ledDevice != nullptr)
{
stopDeviceThread();
}
// create thread and device
QThread* thread = new QThread(this);
_ledDevice = LedDeviceFactory::construct(config);
_ledDevice->moveToThread(thread);
// setup thread management
connect(thread, &QThread::started, _ledDevice, &LedDevice::start);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
connect(thread, &QThread::finished, _ledDevice, &QObject::deleteLater);
// further signals
connect(this, &LedDeviceWrapper::write, _ledDevice, &LedDevice::write);
connect(_ledDevice, &LedDevice::enableStateChanged, this, &LedDeviceWrapper::handleInternalEnableState);
// start the thread
thread->start();
}
const QJsonObject LedDeviceWrapper::getLedDeviceSchemas()
{
// make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(LedDeviceSchemas);
// read the json schema from the resource
QDir d(":/leddevices/");
QStringList l = d.entryList();
QJsonObject result, schemaJson;
for(QString &item : l)
{
QString schemaPath(QString(":/leddevices/")+item);
QString devName = item.remove("schema-");
QString data;
if(!FileUtils::readFile(schemaPath, data, Logger::getInstance("LedDevice")))
{
throw std::runtime_error("ERROR: Schema not found: " + item.toStdString());
}
QJsonObject schema;
if(!JsonUtils::parse(schemaPath, data, schema, Logger::getInstance("LedDevice")))
{
throw std::runtime_error("ERROR: Json schema wrong of file: " + item.toStdString());
}
schemaJson = schema;
schemaJson["title"] = QString("edt_dev_spec_header_title");
result[devName] = schemaJson;
}
return result;
}
int LedDeviceWrapper::addToDeviceMap(QString name, LedDeviceCreateFuncType funcPtr)
{
_ledDeviceMap.emplace(name,funcPtr);
return 0;
}
const LedDeviceRegistry& LedDeviceWrapper::getDeviceMap()
{
return _ledDeviceMap;
}
int LedDeviceWrapper::getLatchTime()
{
return _ledDevice->getLatchTime();
}
const QString & LedDeviceWrapper::getActiveDevice()
{
return _ledDevice->getActiveDevice();
}
const QString & LedDeviceWrapper::getColorOrder()
{
return _ledDevice->getColorOrder();
}
void LedDeviceWrapper::handleComponentState(const hyperion::Components component, const bool state)
{
if(component == hyperion::COMP_LEDDEVICE)
{
_ledDevice->setEnable(state);
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, _ledDevice->componentState());
_enabled = state;
}
}
void LedDeviceWrapper::handleInternalEnableState(bool newState)
{
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, newState);
_enabled = newState;
}
void LedDeviceWrapper::stopDeviceThread()
{
_ledDevice->switchOff();
QThread* oldThread = _ledDevice->thread();
delete _ledDevice; // fast desctruction
oldThread->quit(); // non blocking
oldThread->wait();
}
<commit_msg>Fix LEDDeviceWrapper coredump when killing hyperiond<commit_after>#include <leddevice/LedDeviceWrapper.h>
#include <leddevice/LedDevice.h>
#include <leddevice/LedDeviceFactory.h>
// following file is auto generated by cmake! it contains all available leddevice headers
#include "LedDevice_headers.h"
// util
#include <hyperion/Hyperion.h>
#include <utils/JsonUtils.h>
// qt
#include <QThread>
#include <QDir>
LedDeviceRegistry LedDeviceWrapper::_ledDeviceMap = LedDeviceRegistry();
LedDeviceWrapper::LedDeviceWrapper(Hyperion* hyperion)
: QObject(hyperion)
, _hyperion(hyperion)
, _ledDevice(nullptr)
, _enabled(true)
{
// prepare the device constrcutor map
#define REGISTER(className) LedDeviceWrapper::addToDeviceMap(QString(#className).toLower(), LedDevice##className::construct);
// the REGISTER() calls are autogenerated by cmake.
#include "LedDevice_register.cpp"
#undef REGISTER
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, true);
}
LedDeviceWrapper::~LedDeviceWrapper()
{
stopDeviceThread();
}
void LedDeviceWrapper::createLedDevice(const QJsonObject& config)
{
if(_ledDevice != nullptr)
{
stopDeviceThread();
}
// create thread and device
QThread* thread = new QThread(this);
_ledDevice = LedDeviceFactory::construct(config);
_ledDevice->moveToThread(thread);
// setup thread management
connect(thread, &QThread::started, _ledDevice, &LedDevice::start);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
connect(thread, &QThread::finished, _ledDevice, &QObject::deleteLater);
// further signals
connect(this, &LedDeviceWrapper::write, _ledDevice, &LedDevice::write);
connect(_ledDevice, &LedDevice::enableStateChanged, this, &LedDeviceWrapper::handleInternalEnableState);
// start the thread
thread->start();
}
const QJsonObject LedDeviceWrapper::getLedDeviceSchemas()
{
// make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(LedDeviceSchemas);
// read the json schema from the resource
QDir d(":/leddevices/");
QStringList l = d.entryList();
QJsonObject result, schemaJson;
for(QString &item : l)
{
QString schemaPath(QString(":/leddevices/")+item);
QString devName = item.remove("schema-");
QString data;
if(!FileUtils::readFile(schemaPath, data, Logger::getInstance("LedDevice")))
{
throw std::runtime_error("ERROR: Schema not found: " + item.toStdString());
}
QJsonObject schema;
if(!JsonUtils::parse(schemaPath, data, schema, Logger::getInstance("LedDevice")))
{
throw std::runtime_error("ERROR: Json schema wrong of file: " + item.toStdString());
}
schemaJson = schema;
schemaJson["title"] = QString("edt_dev_spec_header_title");
result[devName] = schemaJson;
}
return result;
}
int LedDeviceWrapper::addToDeviceMap(QString name, LedDeviceCreateFuncType funcPtr)
{
_ledDeviceMap.emplace(name,funcPtr);
return 0;
}
const LedDeviceRegistry& LedDeviceWrapper::getDeviceMap()
{
return _ledDeviceMap;
}
int LedDeviceWrapper::getLatchTime()
{
return _ledDevice->getLatchTime();
}
const QString & LedDeviceWrapper::getActiveDevice()
{
return _ledDevice->getActiveDevice();
}
const QString & LedDeviceWrapper::getColorOrder()
{
return _ledDevice->getColorOrder();
}
void LedDeviceWrapper::handleComponentState(const hyperion::Components component, const bool state)
{
if(component == hyperion::COMP_LEDDEVICE)
{
_ledDevice->setEnable(state);
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, _ledDevice->componentState());
_enabled = state;
}
}
void LedDeviceWrapper::handleInternalEnableState(bool newState)
{
_hyperion->setNewComponentState(hyperion::COMP_LEDDEVICE, newState);
_enabled = newState;
}
void LedDeviceWrapper::stopDeviceThread()
{
_ledDevice->switchOff();
QThread* oldThread = _ledDevice->thread();
delete _ledDevice; // fast desctruction
oldThread->quit(); // non blocking
oldThread->wait();
}
<|endoftext|> |
<commit_before>/*
* Adding an application specific engine
* (C) 2004,2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/stream_cipher.h>
#include <botan/engine.h>
using namespace Botan;
class XOR_Cipher : public StreamCipher
{
public:
void clear() throw() { mask.clear(); mask_pos = 0; }
// what we want to call this cipher
std::string name() const { return "XOR"; }
// return a new object of this type
StreamCipher* clone() const { return new XOR_Cipher; }
XOR_Cipher() : StreamCipher(1, 32) { mask_pos = 0; }
private:
void cipher(const byte in[], byte out[], size_t length)
{
for(size_t j = 0; j != length; j++)
{
out[j] = in[j] ^ mask[mask_pos];
mask_pos = (mask_pos + 1) % mask.size();
}
}
void key_schedule(const byte key[], size_t length)
{
mask.set(key, length);
}
SecureVector<byte> mask;
u32bit mask_pos;
};
class Application_Engine : public Engine
{
public:
std::string provider_name() const { return "application"; }
StreamCipher* find_stream_cipher(const SCAN_Name& request,
Algorithm_Factory&) const
{
if(request.algo_name() == "XOR")
return new XOR_Cipher;
return 0;
}
};
#include <botan/botan.h>
#include <iostream>
#include <string>
int main()
{
Botan::LibraryInitializer init;
global_state().algorithm_factory().add_engine(
new Application_Engine);
// a hex key value
SymmetricKey key("010203040506070809101112AAFF");
/*
Since stream ciphers are typically additive, the encryption and
decryption ops are the same, so this isn't terribly interesting.
If this where a block cipher you would have to add a cipher mode and
padding method, such as "/CBC/PKCS7".
*/
Pipe enc(get_cipher("XOR", key, ENCRYPTION), new Hex_Encoder);
Pipe dec(new Hex_Decoder, get_cipher("XOR", key, DECRYPTION));
// I think the pigeons are actually asleep at midnight...
std::string secret = "The pigeon flys at midnight.";
std::cout << "The secret message is '" << secret << "'" << std::endl;
enc.process_msg(secret);
std::string cipher = enc.read_all_as_string();
std::cout << "The encrypted secret message is " << cipher << std::endl;
dec.process_msg(cipher);
secret = dec.read_all_as_string();
std::cout << "The decrypted secret message is '"
<< secret << "'" << std::endl;
return 0;
}
<commit_msg>New way of specifying key lengths<commit_after>/*
* Adding an application specific engine
* (C) 2004,2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/stream_cipher.h>
#include <botan/engine.h>
using namespace Botan;
class XOR_Cipher : public StreamCipher
{
public:
void clear() throw() { mask.clear(); mask_pos = 0; }
// what we want to call this cipher
std::string name() const { return "XOR"; }
// return a new object of this type
StreamCipher* clone() const { return new XOR_Cipher; }
Key_Length_Specification key_spec() const
{
return Key_Length_Specification(1, 32);
}
XOR_Cipher() : mask_pos(0) {}
private:
void cipher(const byte in[], byte out[], size_t length)
{
for(size_t j = 0; j != length; j++)
{
out[j] = in[j] ^ mask[mask_pos];
mask_pos = (mask_pos + 1) % mask.size();
}
}
void key_schedule(const byte key[], size_t length)
{
mask.set(key, length);
}
SecureVector<byte> mask;
u32bit mask_pos;
};
class Application_Engine : public Engine
{
public:
std::string provider_name() const { return "application"; }
StreamCipher* find_stream_cipher(const SCAN_Name& request,
Algorithm_Factory&) const
{
if(request.algo_name() == "XOR")
return new XOR_Cipher;
return 0;
}
};
#include <botan/botan.h>
#include <iostream>
#include <string>
int main()
{
Botan::LibraryInitializer init;
global_state().algorithm_factory().add_engine(
new Application_Engine);
// a hex key value
SymmetricKey key("010203040506070809101112AAFF");
/*
Since stream ciphers are typically additive, the encryption and
decryption ops are the same, so this isn't terribly interesting.
If this where a block cipher you would have to add a cipher mode and
padding method, such as "/CBC/PKCS7".
*/
Pipe enc(get_cipher("XOR", key, ENCRYPTION), new Hex_Encoder);
Pipe dec(new Hex_Decoder, get_cipher("XOR", key, DECRYPTION));
// I think the pigeons are actually asleep at midnight...
std::string secret = "The pigeon flys at midnight.";
std::cout << "The secret message is '" << secret << "'" << std::endl;
enc.process_msg(secret);
std::string cipher = enc.read_all_as_string();
std::cout << "The encrypted secret message is " << cipher << std::endl;
dec.process_msg(cipher);
secret = dec.read_all_as_string();
std::cout << "The decrypted secret message is '"
<< secret << "'" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLBFGSBOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkLBFGSBOptimizer.h"
#include "itkTextOutput.h"
#include <vnl/vnl_math.h>
#include <iostream>
/**
* The objective function is the quadratic form:
*
* f(x) = 1/2 x^T A x - b^T x subject to -1 <= x <= 10
*
* Where A is represented as an itkMatrix and
* b is represented as a itkVector
*
* The system in this example is:
*
* | 3 2 | | 2|
* A= | 2 6 | b = |-8|
*
* the solution is the vector | 4/3 -1 |
*
*/
class LBFGSBCostFunction : public itk::SingleValuedCostFunction
{
public:
typedef LBFGSBCostFunction Self;
typedef itk::SingleValuedCostFunction Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkNewMacro( Self );
itkTypeMacro( LBFGSBCostFunction, SingleValuedCostFunction );
enum { SpaceDimension=2 };
typedef Superclass::ParametersType ParametersType;
typedef Superclass::DerivativeType DerivativeType;
typedef vnl_vector<double> VectorType;
typedef vnl_matrix<double> MatrixType;
typedef double MeasureType ;
LBFGSBCostFunction()
{
}
double GetValue( const ParametersType & position ) const
{
double x = position[0];
double y = position[1];
std::cout << "GetValue ( " ;
std::cout << x << " , " << y;
std::cout << ") = ";
double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;
std::cout << val << std::endl;
return val;
}
void GetDerivative( const ParametersType & position,
DerivativeType & derivative ) const
{
double x = position[0];
double y = position[1];
std::cout << "GetDerivative ( " ;
std::cout << x << " , " << y;
std::cout << ") = ";
derivative = DerivativeType(SpaceDimension);
derivative[0] = 3*x + 2*y -2;
derivative[1] = 2*x + 6*y +8;
std::cout << "(" ;
std::cout << derivative[0] <<" , ";
std::cout << derivative[1] << ")" << std::endl;
}
unsigned int GetNumberOfParameters(void) const
{
return SpaceDimension;
}
private:
};
int itkLBFGSBOptimizerTest(int, char *[])
{
itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());
std::cout << "LBFGSB Optimizer Test \n \n";
typedef itk::LBFGSBOptimizer OptimizerType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
itkOptimizer->Print( std::cout );
// Declaration of the CostFunction adaptor
LBFGSBCostFunction::Pointer costFunction = LBFGSBCostFunction::New();
itkOptimizer->SetCostFunction( costFunction.GetPointer() );
const double F_Convergence_Factor = 1e+7; // Function value tolerance
const double Projected_G_Tolerance = 1e-5; // Proj gradient tolerance
const int Max_Iterations = 100; // Maximum number of iterations
itkOptimizer->SetCostFunctionConvergenceFactor( F_Convergence_Factor );
itkOptimizer->SetProjectedGradientTolerance( Projected_G_Tolerance );
itkOptimizer->SetMaximumNumberOfIterations( Max_Iterations );
itkOptimizer->SetMaximumNumberOfEvaluations( Max_Iterations );
const unsigned int SpaceDimension = 2;
OptimizerType::ParametersType initialValue(SpaceDimension);
// Starting point
initialValue[0] = 10;
initialValue[1] = 10;
OptimizerType::ParametersType currentValue(2);
currentValue = initialValue;
itkOptimizer->SetInitialPosition( currentValue );
// Set up boundary conditions
OptimizerType::BoundValueType lower(SpaceDimension);
OptimizerType::BoundValueType upper(SpaceDimension);
OptimizerType::BoundSelectionType select(SpaceDimension);
lower.Fill( -1 );
upper.Fill( 10 );
select.Fill( 2 );
itkOptimizer->SetLowerBound( lower );
itkOptimizer->SetUpperBound( upper );
itkOptimizer->SetBoundSelection( select );
itkOptimizer->Print( std::cout );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
const OptimizerType::ParametersType & finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = (";
std::cout << finalPosition[0] << "," ;
std::cout << finalPosition[1] << ")" << std::endl;
std::cout << "Final Function Value = ";
std::cout << itkOptimizer->GetValue() << std::endl;
std::cout << "Infinity Norm of Projected Gradient = ";
std::cout << itkOptimizer->GetInfinityNormOfProjectedGradient() << std::endl;
std::cout << "End condition = " << itkOptimizer->GetStopConditionDescription() << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
std::string errorIn;
double trueParameters[2] = { 4.0/3.0, -1.0 };
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
errorIn = "solution";
}
}
if( vnl_math_abs( itkOptimizer->GetValue() - -7.66667 ) > 0.01 )
{
pass = false;
errorIn = "final function value";
}
if( vnl_math_abs( itkOptimizer->GetInfinityNormOfProjectedGradient()
- 1.77636e-15 ) > 0.01 )
{
pass = false;
errorIn = "infinity norm of projected gradient";
}
if( !pass )
{
std::cout << "\nError in " << errorIn << ".\n";
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: more code coverage by exercising get methods<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLBFGSBOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkLBFGSBOptimizer.h"
#include "itkTextOutput.h"
#include <vnl/vnl_math.h>
#include <iostream>
/**
* The objective function is the quadratic form:
*
* f(x) = 1/2 x^T A x - b^T x subject to -1 <= x <= 10
*
* Where A is represented as an itkMatrix and
* b is represented as a itkVector
*
* The system in this example is:
*
* | 3 2 | | 2|
* A= | 2 6 | b = |-8|
*
* the solution is the vector | 4/3 -1 |
*
*/
class LBFGSBCostFunction : public itk::SingleValuedCostFunction
{
public:
typedef LBFGSBCostFunction Self;
typedef itk::SingleValuedCostFunction Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkNewMacro( Self );
itkTypeMacro( LBFGSBCostFunction, SingleValuedCostFunction );
enum { SpaceDimension=2 };
typedef Superclass::ParametersType ParametersType;
typedef Superclass::DerivativeType DerivativeType;
typedef vnl_vector<double> VectorType;
typedef vnl_matrix<double> MatrixType;
typedef double MeasureType ;
LBFGSBCostFunction()
{
}
double GetValue( const ParametersType & position ) const
{
double x = position[0];
double y = position[1];
std::cout << "GetValue ( " ;
std::cout << x << " , " << y;
std::cout << ") = ";
double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;
std::cout << val << std::endl;
return val;
}
void GetDerivative( const ParametersType & position,
DerivativeType & derivative ) const
{
double x = position[0];
double y = position[1];
std::cout << "GetDerivative ( " ;
std::cout << x << " , " << y;
std::cout << ") = ";
derivative = DerivativeType(SpaceDimension);
derivative[0] = 3*x + 2*y -2;
derivative[1] = 2*x + 6*y +8;
std::cout << "(" ;
std::cout << derivative[0] <<" , ";
std::cout << derivative[1] << ")" << std::endl;
}
unsigned int GetNumberOfParameters(void) const
{
return SpaceDimension;
}
private:
};
int itkLBFGSBOptimizerTest(int, char *[])
{
itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());
std::cout << "LBFGSB Optimizer Test \n \n";
typedef itk::LBFGSBOptimizer OptimizerType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
itkOptimizer->Print( std::cout );
// Declaration of the CostFunction adaptor
LBFGSBCostFunction::Pointer costFunction = LBFGSBCostFunction::New();
itkOptimizer->SetCostFunction( costFunction.GetPointer() );
const double F_Convergence_Factor = 1e+7; // Function value tolerance
const double Projected_G_Tolerance = 1e-5; // Proj gradient tolerance
const int Max_Iterations = 100; // Maximum number of iterations
itkOptimizer->SetCostFunctionConvergenceFactor( F_Convergence_Factor );
itkOptimizer->SetProjectedGradientTolerance( Projected_G_Tolerance );
itkOptimizer->SetMaximumNumberOfIterations( Max_Iterations );
itkOptimizer->SetMaximumNumberOfEvaluations( Max_Iterations );
const unsigned int SpaceDimension = 2;
OptimizerType::ParametersType initialValue(SpaceDimension);
// Starting point
initialValue[0] = 10;
initialValue[1] = 10;
OptimizerType::ParametersType currentValue(2);
currentValue = initialValue;
itkOptimizer->SetInitialPosition( currentValue );
// Set up boundary conditions
OptimizerType::BoundValueType lower(SpaceDimension);
OptimizerType::BoundValueType upper(SpaceDimension);
OptimizerType::BoundSelectionType select(SpaceDimension);
lower.Fill( -1 );
upper.Fill( 10 );
select.Fill( 2 );
itkOptimizer->SetLowerBound( lower );
itkOptimizer->SetUpperBound( upper );
itkOptimizer->SetBoundSelection( select );
itkOptimizer->Print( std::cout );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
const OptimizerType::ParametersType & finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = ("
<< finalPosition[0] << ","
<< finalPosition[1] << ")" << std::endl;
std::cout << "Final Function Value = "
<< itkOptimizer->GetValue() << std::endl;
std::cout << "Infinity Norm of Projected Gradient = "
<< itkOptimizer->GetInfinityNormOfProjectedGradient() << std::endl;
std::cout << "End condition = "
<< itkOptimizer->GetStopConditionDescription() << std::endl;
std::cout << "Trace = " << itkOptimizer->GetTrace() << std::endl;
std::cout << "CostFunctionConvergenceFactor = "
<< itkOptimizer->GetCostFunctionConvergenceFactor() << std::endl;
std::cout << "ProjectedGradientTolerance = "
<< itkOptimizer->GetProjectedGradientTolerance() << std::endl;
std::cout << "MaximumNumberOfIterations = "
<< itkOptimizer->GetMaximumNumberOfIterations() << std::endl;
std::cout << "MaximumNumberOfEvaluations = "
<< itkOptimizer->GetMaximumNumberOfEvaluations() << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
std::string errorIn;
double trueParameters[2] = { 4.0/3.0, -1.0 };
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
errorIn = "solution";
}
}
if( vnl_math_abs( itkOptimizer->GetValue() - -7.66667 ) > 0.01 )
{
pass = false;
errorIn = "final function value";
}
if( vnl_math_abs( itkOptimizer->GetInfinityNormOfProjectedGradient()
- 1.77636e-15 ) > 0.01 )
{
pass = false;
errorIn = "infinity norm of projected gradient";
}
if( !pass )
{
std::cout << "\nError in " << errorIn << ".\n";
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/qpointer.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qbasictimer.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qdebug.h>
#include <QtGui/qgraphicsscene.h>
#include <QtGui/qgraphicsview.h>
#include <QtGui/qscrollbar.h>
#include <QtGui/qx11info_x11.h>
#include "qgraphicsvideoitem.h"
#include <qmediaobject.h>
#include <qmediaservice.h>
#include <qvideowindowcontrol.h>
QT_BEGIN_NAMESPACE
#define DEBUG_GFX_VIDEO_ITEM
class QGraphicsVideoItemPrivate : public QObject
{
public:
QGraphicsVideoItemPrivate()
: q_ptr(0)
, mediaObject(0)
, service(0)
, windowControl(0)
, savedViewportUpdateMode(QGraphicsView::FullViewportUpdate)
, aspectRatioMode(Qt::KeepAspectRatio)
, rect(0.0, 0.0, 320, 240)
, videoWidget(0)
{
}
QGraphicsVideoItem *q_ptr;
QMediaObject *mediaObject;
QMediaService *service;
QVideoWindowControl *windowControl;
QPointer<QGraphicsView> currentView;
QGraphicsView::ViewportUpdateMode savedViewportUpdateMode;
Qt::AspectRatioMode aspectRatioMode;
QRectF rect;
QRectF boundingRect;
QRectF displayRect;
QSizeF nativeSize;
QWidget *videoWidget;
bool eventFilter(QObject *object, QEvent *event);
void setWidget(QWidget *widget);
void clearService();
void updateRects();
void updateLastFrame();
void _q_present();
void _q_updateNativeSize();
void _q_serviceDestroyed();
void _q_mediaObjectDestroyed();
};
void QGraphicsVideoItemPrivate::_q_present()
{
}
bool QGraphicsVideoItemPrivate::eventFilter(QObject *object, QEvent *event)
{
if (windowControl && object == videoWidget && QEvent::WinIdChange == event->type())
windowControl->setWinId(videoWidget->effectiveWinId());
return false;
}
void QGraphicsVideoItemPrivate::setWidget(QWidget *widget)
{
if (videoWidget != widget) {
videoWidget = widget;
if (widget) {
windowControl->setWinId(widget->winId());
widget->installEventFilter(this);
}
}
}
void QGraphicsVideoItemPrivate::clearService()
{
if (windowControl) {
QObject::disconnect(windowControl, SIGNAL(nativeSizeChanged()), q_ptr, SLOT(_q_updateNativeSize()));
service->releaseControl(windowControl);
windowControl = 0;
}
if (service) {
QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed()));
service = 0;
}
}
void QGraphicsVideoItemPrivate::updateRects()
{
q_ptr->prepareGeometryChange();
displayRect = rect;
if (nativeSize.isEmpty()) {
boundingRect = rect;
} else if (aspectRatioMode == Qt::IgnoreAspectRatio) {
boundingRect = rect;
} else if (aspectRatioMode == Qt::KeepAspectRatio) {
QSizeF size = nativeSize;
size.scale(rect.size(), Qt::KeepAspectRatio);
boundingRect = QRectF(0, 0, size.width(), size.height());
boundingRect.moveCenter(rect.center());
displayRect = boundingRect;
} else if (aspectRatioMode == Qt::KeepAspectRatioByExpanding) {
boundingRect = rect;
QSizeF size = rect.size();
size.scale(nativeSize, Qt::KeepAspectRatioByExpanding);
displayRect = QRectF(0, 0, size.width(), size.height());
displayRect.moveCenter(rect.center());
}
}
void QGraphicsVideoItemPrivate::updateLastFrame()
{
}
void QGraphicsVideoItemPrivate::_q_updateNativeSize()
{
const QSize size = windowControl->nativeSize();
if (nativeSize != size) {
nativeSize = size;
updateRects();
emit q_ptr->nativeSizeChanged(nativeSize);
}
}
void QGraphicsVideoItemPrivate::_q_serviceDestroyed()
{
windowControl = 0;
service = 0;
}
void QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed()
{
mediaObject = 0;
clearService();
}
QGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent)
: QGraphicsObject(parent)
, d_ptr(new QGraphicsVideoItemPrivate)
{
d_ptr->q_ptr = this;
setCacheMode(NoCache);
setFlag(QGraphicsItem::ItemIgnoresParentOpacity);
setFlag(QGraphicsItem::ItemSendsGeometryChanges);
setFlag(QGraphicsItem::ItemSendsScenePositionChanges);
}
QGraphicsVideoItem::~QGraphicsVideoItem()
{
if (d_ptr->windowControl) {
d_ptr->service->releaseControl(d_ptr->windowControl);
}
if (d_ptr->currentView)
d_ptr->currentView->setViewportUpdateMode(d_ptr->savedViewportUpdateMode);
delete d_ptr;
}
QMediaObject *QGraphicsVideoItem::mediaObject() const
{
return d_func()->mediaObject;
}
bool QGraphicsVideoItem::setMediaObject(QMediaObject *object)
{
Q_D(QGraphicsVideoItem);
if (object == d->mediaObject)
return true;
d->clearService();
d->mediaObject = object;
if (d->mediaObject) {
d->service = d->mediaObject->service();
if (d->service) {
d->windowControl = qobject_cast<QVideoWindowControl *>(
d->service->requestControl(QVideoWindowControl_iid));
if (d->windowControl != 0) {
connect(d->service, SIGNAL(destroyed()), SLOT(_q_serviceDestroyed()));
connect(d->windowControl, SIGNAL(nativeSizeChanged()), SLOT(_q_updateNativeSize()));
//d->windowControl->setProperty("colorKey", QVariant(QColor(16,7,2)));
d->windowControl->setProperty("autopaintColorKey", QVariant(false));
d->updateRects();
return true;
} else {
qWarning() << "Service doesn't support QVideoWindowControl, overlay item failed";
}
}
}
d->mediaObject = 0;
return false;
}
Qt::AspectRatioMode QGraphicsVideoItem::aspectRatioMode() const
{
return d_func()->aspectRatioMode;
}
void QGraphicsVideoItem::setAspectRatioMode(Qt::AspectRatioMode mode)
{
Q_D(QGraphicsVideoItem);
d->aspectRatioMode = mode;
d->updateRects();
}
QPointF QGraphicsVideoItem::offset() const
{
return d_func()->rect.topLeft();
}
void QGraphicsVideoItem::setOffset(const QPointF &offset)
{
Q_D(QGraphicsVideoItem);
d->rect.moveTo(offset);
d->updateRects();
}
QSizeF QGraphicsVideoItem::size() const
{
return d_func()->rect.size();
}
void QGraphicsVideoItem::setSize(const QSizeF &size)
{
Q_D(QGraphicsVideoItem);
d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));
d->updateRects();
}
QSizeF QGraphicsVideoItem::nativeSize() const
{
return d_func()->nativeSize;
}
QRectF QGraphicsVideoItem::boundingRect() const
{
return d_func()->boundingRect;
}
void QGraphicsVideoItem::paint(
QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
#ifdef DEBUG_GFX_VIDEO_ITEM
qDebug() << "QGraphicsVideoItem::paint";
#endif
Q_UNUSED(option);
Q_D(QGraphicsVideoItem);
QGraphicsView *view = 0;
if (scene() && !scene()->views().isEmpty())
view = scene()->views().first();
//it's necessary to switch vieport update mode to FullViewportUpdate
//otherwise the video item area can be just scrolled without notifying overlay
//about geometry changes
if (view != d->currentView) {
if (d->currentView) {
d->currentView->setViewportUpdateMode(d->savedViewportUpdateMode);
}
d->currentView = view;
if (view) {
d->savedViewportUpdateMode = view->viewportUpdateMode();
view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
}
}
QColor colorKey = Qt::black;
if (d->windowControl != 0 && widget != 0) {
d->setWidget(widget);
QTransform transform = painter->combinedTransform();
QRect overlayRect = transform.mapRect(d->displayRect).toRect();
QRect currentSurfaceRect = d->windowControl->displayRect();
if (currentSurfaceRect != overlayRect) {
#ifdef DEBUG_GFX_VIDEO_ITEM
qDebug() << "set video display rect:" << overlayRect;
#endif
d->windowControl->setDisplayRect(overlayRect);
}
colorKey = d->windowControl->property("colorKey").value<QColor>();
}
if (colorKey.alpha() != 255)
painter->setCompositionMode(QPainter::CompositionMode_Source);
painter->fillRect(d->boundingRect, colorKey);
}
QVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
Q_D(QGraphicsVideoItem);
switch (change) {
case ItemScenePositionHasChanged:
update(boundingRect());
break;
case ItemVisibleChange:
//move overlay out of the screen if video item becomes invisible
if (d->windowControl != 0 && !value.toBool())
d->windowControl->setDisplayRect(QRect(-1,-1,1,1));
break;
default:
break;
}
return QGraphicsItem::itemChange(change, value);
}
void QGraphicsVideoItem::timerEvent(QTimerEvent *event)
{
QGraphicsObject::timerEvent(event);
}
#include "moc_qgraphicsvideoitem.cpp"
QT_END_NAMESPACE
<commit_msg>Correct aspect ratio in overlay QGraphicsVideoItem<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/qpointer.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qbasictimer.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qdebug.h>
#include <QtGui/qgraphicsscene.h>
#include <QtGui/qgraphicsview.h>
#include <QtGui/qscrollbar.h>
#include <QtGui/qx11info_x11.h>
#include "qgraphicsvideoitem.h"
#include <qmediaobject.h>
#include <qmediaservice.h>
#include <qvideowindowcontrol.h>
QT_BEGIN_NAMESPACE
#define DEBUG_GFX_VIDEO_ITEM
class QGraphicsVideoItemPrivate : public QObject
{
public:
QGraphicsVideoItemPrivate()
: q_ptr(0)
, mediaObject(0)
, service(0)
, windowControl(0)
, savedViewportUpdateMode(QGraphicsView::FullViewportUpdate)
, aspectRatioMode(Qt::KeepAspectRatio)
, rect(0.0, 0.0, 320, 240)
, videoWidget(0)
{
}
QGraphicsVideoItem *q_ptr;
QMediaObject *mediaObject;
QMediaService *service;
QVideoWindowControl *windowControl;
QPointer<QGraphicsView> currentView;
QGraphicsView::ViewportUpdateMode savedViewportUpdateMode;
Qt::AspectRatioMode aspectRatioMode;
QRectF rect;
QRectF boundingRect;
QRectF displayRect;
QSizeF nativeSize;
QWidget *videoWidget;
bool eventFilter(QObject *object, QEvent *event);
void setWidget(QWidget *widget);
void clearService();
void updateRects();
void updateLastFrame();
void _q_present();
void _q_updateNativeSize();
void _q_serviceDestroyed();
void _q_mediaObjectDestroyed();
};
void QGraphicsVideoItemPrivate::_q_present()
{
}
bool QGraphicsVideoItemPrivate::eventFilter(QObject *object, QEvent *event)
{
if (windowControl && object == videoWidget && QEvent::WinIdChange == event->type())
windowControl->setWinId(videoWidget->effectiveWinId());
return false;
}
void QGraphicsVideoItemPrivate::setWidget(QWidget *widget)
{
if (videoWidget != widget) {
videoWidget = widget;
if (widget) {
windowControl->setWinId(widget->winId());
widget->installEventFilter(this);
}
}
}
void QGraphicsVideoItemPrivate::clearService()
{
if (windowControl) {
QObject::disconnect(windowControl, SIGNAL(nativeSizeChanged()), q_ptr, SLOT(_q_updateNativeSize()));
service->releaseControl(windowControl);
windowControl = 0;
}
if (service) {
QObject::disconnect(service, SIGNAL(destroyed()), q_ptr, SLOT(_q_serviceDestroyed()));
service = 0;
}
}
void QGraphicsVideoItemPrivate::updateRects()
{
q_ptr->prepareGeometryChange();
QSizeF videoSize;
if (nativeSize.isEmpty()) {
videoSize = rect.size();
} else if (aspectRatioMode == Qt::IgnoreAspectRatio) {
videoSize = rect.size();
} else {
// KeepAspectRatio or KeepAspectRatioByExpanding
videoSize = nativeSize;
videoSize.scale(rect.size(), aspectRatioMode);
}
displayRect = QRectF(QPointF(0, 0), videoSize);
displayRect.moveCenter(rect.center());
boundingRect = displayRect.intersected(rect);
}
void QGraphicsVideoItemPrivate::updateLastFrame()
{
}
void QGraphicsVideoItemPrivate::_q_updateNativeSize()
{
const QSize size = windowControl->nativeSize();
if (nativeSize != size) {
nativeSize = size;
updateRects();
emit q_ptr->nativeSizeChanged(nativeSize);
}
}
void QGraphicsVideoItemPrivate::_q_serviceDestroyed()
{
windowControl = 0;
service = 0;
}
void QGraphicsVideoItemPrivate::_q_mediaObjectDestroyed()
{
mediaObject = 0;
clearService();
}
QGraphicsVideoItem::QGraphicsVideoItem(QGraphicsItem *parent)
: QGraphicsObject(parent)
, d_ptr(new QGraphicsVideoItemPrivate)
{
d_ptr->q_ptr = this;
setCacheMode(NoCache);
setFlag(QGraphicsItem::ItemIgnoresParentOpacity);
setFlag(QGraphicsItem::ItemSendsGeometryChanges);
setFlag(QGraphicsItem::ItemSendsScenePositionChanges);
}
QGraphicsVideoItem::~QGraphicsVideoItem()
{
if (d_ptr->windowControl) {
d_ptr->service->releaseControl(d_ptr->windowControl);
}
if (d_ptr->currentView)
d_ptr->currentView->setViewportUpdateMode(d_ptr->savedViewportUpdateMode);
delete d_ptr;
}
QMediaObject *QGraphicsVideoItem::mediaObject() const
{
return d_func()->mediaObject;
}
bool QGraphicsVideoItem::setMediaObject(QMediaObject *object)
{
Q_D(QGraphicsVideoItem);
if (object == d->mediaObject)
return true;
d->clearService();
d->mediaObject = object;
if (d->mediaObject) {
d->service = d->mediaObject->service();
if (d->service) {
d->windowControl = qobject_cast<QVideoWindowControl *>(
d->service->requestControl(QVideoWindowControl_iid));
if (d->windowControl != 0) {
connect(d->service, SIGNAL(destroyed()), SLOT(_q_serviceDestroyed()));
connect(d->windowControl, SIGNAL(nativeSizeChanged()), SLOT(_q_updateNativeSize()));
d->windowControl->setAspectRatioMode(Qt::IgnoreAspectRatio);
//d->windowControl->setProperty("colorKey", QVariant(QColor(16,7,2)));
d->windowControl->setProperty("autopaintColorKey", QVariant(false));
d->updateRects();
return true;
} else {
qWarning() << "Service doesn't support QVideoWindowControl, overlay item failed";
}
}
}
d->mediaObject = 0;
return false;
}
Qt::AspectRatioMode QGraphicsVideoItem::aspectRatioMode() const
{
return d_func()->aspectRatioMode;
}
void QGraphicsVideoItem::setAspectRatioMode(Qt::AspectRatioMode mode)
{
Q_D(QGraphicsVideoItem);
d->aspectRatioMode = mode;
d->updateRects();
}
QPointF QGraphicsVideoItem::offset() const
{
return d_func()->rect.topLeft();
}
void QGraphicsVideoItem::setOffset(const QPointF &offset)
{
Q_D(QGraphicsVideoItem);
d->rect.moveTo(offset);
d->updateRects();
}
QSizeF QGraphicsVideoItem::size() const
{
return d_func()->rect.size();
}
void QGraphicsVideoItem::setSize(const QSizeF &size)
{
Q_D(QGraphicsVideoItem);
d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));
d->updateRects();
}
QSizeF QGraphicsVideoItem::nativeSize() const
{
return d_func()->nativeSize;
}
QRectF QGraphicsVideoItem::boundingRect() const
{
return d_func()->boundingRect;
}
void QGraphicsVideoItem::paint(
QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
#ifdef DEBUG_GFX_VIDEO_ITEM
qDebug() << "QGraphicsVideoItem::paint";
#endif
Q_UNUSED(option);
Q_D(QGraphicsVideoItem);
QGraphicsView *view = 0;
if (scene() && !scene()->views().isEmpty())
view = scene()->views().first();
//it's necessary to switch vieport update mode to FullViewportUpdate
//otherwise the video item area can be just scrolled without notifying overlay
//about geometry changes
if (view != d->currentView) {
if (d->currentView) {
d->currentView->setViewportUpdateMode(d->savedViewportUpdateMode);
}
d->currentView = view;
if (view) {
d->savedViewportUpdateMode = view->viewportUpdateMode();
view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
}
}
QColor colorKey = Qt::black;
if (d->windowControl != 0 && widget != 0) {
d->setWidget(widget);
QTransform transform = painter->combinedTransform();
QRect overlayRect = transform.mapRect(d->displayRect).toRect();
QRect currentSurfaceRect = d->windowControl->displayRect();
if (currentSurfaceRect != overlayRect) {
#ifdef DEBUG_GFX_VIDEO_ITEM
qDebug() << "set video display rect:" << overlayRect;
#endif
d->windowControl->setDisplayRect(overlayRect);
}
colorKey = d->windowControl->property("colorKey").value<QColor>();
}
if (colorKey.alpha() != 255)
painter->setCompositionMode(QPainter::CompositionMode_Source);
painter->fillRect(d->boundingRect, colorKey);
}
QVariant QGraphicsVideoItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
Q_D(QGraphicsVideoItem);
switch (change) {
case ItemScenePositionHasChanged:
update(boundingRect());
break;
case ItemVisibleChange:
//move overlay out of the screen if video item becomes invisible
if (d->windowControl != 0 && !value.toBool())
d->windowControl->setDisplayRect(QRect(-1,-1,1,1));
break;
default:
break;
}
return QGraphicsItem::itemChange(change, value);
}
void QGraphicsVideoItem::timerEvent(QTimerEvent *event)
{
QGraphicsObject::timerEvent(event);
}
#include "moc_qgraphicsvideoitem.cpp"
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: imapdlg.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: cl $ $Date: 2002-07-11 10:56:24 $
*
* 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 _IMAPDLG_HXX_
#define _IMAPDLG_HXX_
#ifndef _SVTOOLS_INETTBC_HXX
#include <svtools/inettbc.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _GOMISC_HXX
class ImageMap;
#endif
/*************************************************************************
|*
|* Ableitung vom SfxChildWindow als "Behaelter" fuer Float
|*
\************************************************************************/
class Graphic;
class TargetList;
class SvxIMapDlgChildWindow : public SfxChildWindow
{
public:
SvxIMapDlgChildWindow( Window*, USHORT, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxIMapDlgChildWindow );
static void UpdateIMapDlg( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
};
#ifndef _REDUCED_IMAPDLG_HXX_
#define _REDUCED_IMAPDLG_HXX_
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxIMapDlg;
class SvxIMapDlgItem : public SfxControllerItem
{
SvxIMapDlg& rIMap;
protected:
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
public:
SvxIMapDlgItem( USHORT nId, SvxIMapDlg& rIMapDlg, SfxBindings& rBindings );
};
/*************************************************************************
|*
|*
|*
\************************************************************************/
class IMapOwnData;
class SvxIMapDlg : public SfxModelessDialog // SfxFloatingWindow
{
friend class IMapOwnData;
friend class IMapWindow;
ToolBox aTbxIMapDlg1;
FixedText aFtURL;
SvtURLBox maURLBox;
FixedText aFtText;
Edit aEdtText;
FixedText maFtTarget;
ComboBox maCbbTarget;
StatusBar aStbStatus;
ImageList maImageList;
ImageList maImageListH;
Size aLastSize;
IMapWindow* pIMapWnd;
IMapOwnData* pOwnData;
void* pCheckObj;
SvxIMapDlgItem aIMapItem;
virtual void Resize();
virtual BOOL Close();
#ifdef _IMAPDLG_PRIVATE
DECL_LINK( TbxClickHdl, ToolBox* );
DECL_LINK( InfoHdl, IMapWindow* );
DECL_LINK( MousePosHdl, IMapWindow* );
DECL_LINK( GraphSizeHdl, IMapWindow* );
DECL_LINK( URLModifyHdl, void* );
DECL_LINK( URLLoseFocusHdl, void* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( TbxUpdateHdl, Timer* );
DECL_LINK( StateHdl, IMapWindow* );
DECL_LINK( MiscHdl, void* );
void DoOpen();
BOOL DoSave();
#endif
public:
SvxIMapDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxIMapDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
void SetImageMap( const ImageMap& rImageMap );
const ImageMap& GetImageMap() const;
void SetTargetList( const TargetList& rTargetList );
const TargetList& GetTargetList() const;
void Update( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void ApplyImageList();
};
/*************************************************************************
|*
|* Defines
|*
\************************************************************************/
#define SVXIMAPDLG() ( (SvxIMapDlg*) ( SfxViewFrame::Current()->GetChildWindow( \
SvxIMapDlgChildWindow::GetChildWindowId() )-> \
GetWindow() ) )
#endif // _REDUCED_IMAPDLG_HXX_
#endif // _IMAPDLG_HXX_
<commit_msg>INTEGRATION: CWS visibility01 (1.6.1010); FILE MERGED 2004/12/06 08:10:24 mnicel 1.6.1010.2: Part of symbol visibility markup - #i35758# 2004/11/19 12:54:18 mmeeks 1.6.1010.1: Issue number: #i35758# Submitted by: mnicel Reviewed by: mmeeks<commit_after>/*************************************************************************
*
* $RCSfile: imapdlg.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-01-21 14:47:38 $
*
* 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 _IMAPDLG_HXX_
#define _IMAPDLG_HXX_
#ifndef _SVTOOLS_INETTBC_HXX
#include <svtools/inettbc.hxx>
#endif
#ifndef _SFX_CHILDWIN_HXX //autogen
#include <sfx2/childwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#ifndef _GOMISC_HXX
class ImageMap;
#endif
/*************************************************************************
|*
|* Ableitung vom SfxChildWindow als "Behaelter" fuer Float
|*
\************************************************************************/
class Graphic;
class TargetList;
class SVX_DLLPUBLIC SvxIMapDlgChildWindow : public SfxChildWindow
{
public:
SvxIMapDlgChildWindow( Window*, USHORT, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxIMapDlgChildWindow );
static void UpdateIMapDlg( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
};
#ifndef _REDUCED_IMAPDLG_HXX_
#define _REDUCED_IMAPDLG_HXX_
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxIMapDlg;
class SvxIMapDlgItem : public SfxControllerItem
{
SvxIMapDlg& rIMap;
protected:
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
public:
SvxIMapDlgItem( USHORT nId, SvxIMapDlg& rIMapDlg, SfxBindings& rBindings );
};
/*************************************************************************
|*
|*
|*
\************************************************************************/
class IMapOwnData;
class SVX_DLLPUBLIC SvxIMapDlg : public SfxModelessDialog // SfxFloatingWindow
{
friend class IMapOwnData;
friend class IMapWindow;
ToolBox aTbxIMapDlg1;
FixedText aFtURL;
SvtURLBox maURLBox;
FixedText aFtText;
Edit aEdtText;
FixedText maFtTarget;
ComboBox maCbbTarget;
StatusBar aStbStatus;
ImageList maImageList;
ImageList maImageListH;
Size aLastSize;
IMapWindow* pIMapWnd;
IMapOwnData* pOwnData;
void* pCheckObj;
SvxIMapDlgItem aIMapItem;
virtual void Resize();
virtual BOOL Close();
#ifdef _IMAPDLG_PRIVATE
DECL_LINK( TbxClickHdl, ToolBox* );
DECL_LINK( InfoHdl, IMapWindow* );
DECL_LINK( MousePosHdl, IMapWindow* );
DECL_LINK( GraphSizeHdl, IMapWindow* );
DECL_LINK( URLModifyHdl, void* );
DECL_LINK( URLLoseFocusHdl, void* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( TbxUpdateHdl, Timer* );
DECL_LINK( StateHdl, IMapWindow* );
DECL_LINK( MiscHdl, void* );
void DoOpen();
BOOL DoSave();
#endif
public:
SvxIMapDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxIMapDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
void SetImageMap( const ImageMap& rImageMap );
const ImageMap& GetImageMap() const;
void SetTargetList( const TargetList& rTargetList );
const TargetList& GetTargetList() const;
void Update( const Graphic& rGraphic, const ImageMap* pImageMap = NULL,
const TargetList* pTargetList = NULL, void* pEditingObj = NULL );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
void ApplyImageList();
};
/*************************************************************************
|*
|* Defines
|*
\************************************************************************/
#define SVXIMAPDLG() ( (SvxIMapDlg*) ( SfxViewFrame::Current()->GetChildWindow( \
SvxIMapDlgChildWindow::GetChildWindowId() )-> \
GetWindow() ) )
#endif // _REDUCED_IMAPDLG_HXX_
#endif // _IMAPDLG_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtftntx.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:50:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FMTFTNTX_HXX
#define _FMTFTNTX_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
enum SwFtnEndPosEnum
{
FTNEND_ATPGORDOCEND, // at page or document end
FTNEND_ATTXTEND, // at end of the current text end
FTNEND_ATTXTEND_OWNNUMSEQ, // -""- and with own number sequence
FTNEND_ATTXTEND_OWNNUMANDFMT, // -""- and with onw numberformat
FTNEND_ATTXTEND_END
};
class SW_DLLPUBLIC SwFmtFtnEndAtTxtEnd : public SfxEnumItem
{
String sPrefix;
String sSuffix;
SvxNumberType aFmt;
USHORT nOffset;
protected:
SwFmtFtnEndAtTxtEnd( USHORT nWhich, SwFtnEndPosEnum ePos )
: SfxEnumItem( nWhich, ePos ), nOffset( 0 )
{}
SwFmtFtnEndAtTxtEnd( const SwFmtFtnEndAtTxtEnd& rAttr )
: SfxEnumItem( rAttr ), sPrefix( rAttr.sPrefix ),
sSuffix( rAttr.sSuffix ), aFmt( rAttr.aFmt ),
nOffset( rAttr.nOffset )
{}
public:
virtual USHORT GetValueCount() const;
virtual int operator==( const SfxPoolItem& ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// will be used at time??
// void FillVariable( SbxVariable &rVar,
// SfxMapUnit eCoreMetric,
// SfxMapUnit eUserMetric ) const;
// virtual SfxArgumentError SetVariable( const SbxVariable &rVal,
// SfxMapUnit eCoreMetric,
// SfxMapUnit eUserMetric );
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
inline BOOL IsAtEnd() const { return FTNEND_ATPGORDOCEND != GetValue(); }
SwFmtFtnEndAtTxtEnd & operator=( const SwFmtFtnEndAtTxtEnd & rAttr );
sal_Int16 GetNumType() const { return aFmt.GetNumberingType(); }
void SetNumType( sal_Int16 eType ) { aFmt.SetNumberingType(eType); }
const SvxNumberType& GetSwNumType() const { return aFmt; }
USHORT GetOffset() const { return nOffset; }
void SetOffset( USHORT nOff ) { nOffset = nOff; }
const String& GetPrefix() const { return sPrefix; }
void SetPrefix(const String& rSet) { sPrefix = rSet; }
const String& GetSuffix() const { return sSuffix; }
void SetSuffix(const String& rSet) { sSuffix = rSet; }
};
class SW_DLLPUBLIC SwFmtFtnAtTxtEnd : public SwFmtFtnEndAtTxtEnd
{
public:
SwFmtFtnAtTxtEnd( SwFtnEndPosEnum ePos = FTNEND_ATPGORDOCEND )
: SwFmtFtnEndAtTxtEnd( RES_FTN_AT_TXTEND, ePos )
{}
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
};
class SW_DLLPUBLIC SwFmtEndAtTxtEnd : public SwFmtFtnEndAtTxtEnd
{
public:
SwFmtEndAtTxtEnd( SwFtnEndPosEnum ePos = FTNEND_ATPGORDOCEND )
: SwFmtFtnEndAtTxtEnd( RES_END_AT_TXTEND, ePos )
{
SetNumType( SVX_NUM_ROMAN_LOWER );
}
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
};
inline const SwFmtFtnAtTxtEnd &SwAttrSet::GetFtnAtTxtEnd(BOOL bInP) const
{ return (const SwFmtFtnAtTxtEnd&)Get( RES_FTN_AT_TXTEND, bInP); }
inline const SwFmtEndAtTxtEnd &SwAttrSet::GetEndAtTxtEnd(BOOL bInP) const
{ return (const SwFmtEndAtTxtEnd&)Get( RES_END_AT_TXTEND, bInP); }
inline const SwFmtFtnAtTxtEnd &SwFmt::GetFtnAtTxtEnd(BOOL bInP) const
{ return aSet.GetFtnAtTxtEnd(bInP); }
inline const SwFmtEndAtTxtEnd &SwFmt::GetEndAtTxtEnd(BOOL bInP) const
{ return aSet.GetEndAtTxtEnd(bInP); }
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.10.710); FILE MERGED 2007/02/27 13:06:33 tl 1.10.710.2: #i69287# warning-free code 2007/02/22 15:05:37 tl 1.10.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtftntx.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:03:08 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FMTFTNTX_HXX
#define _FMTFTNTX_HXX
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
enum SwFtnEndPosEnum
{
FTNEND_ATPGORDOCEND, // at page or document end
FTNEND_ATTXTEND, // at end of the current text end
FTNEND_ATTXTEND_OWNNUMSEQ, // -""- and with own number sequence
FTNEND_ATTXTEND_OWNNUMANDFMT, // -""- and with onw numberformat
FTNEND_ATTXTEND_END
};
class SW_DLLPUBLIC SwFmtFtnEndAtTxtEnd : public SfxEnumItem
{
String sPrefix;
String sSuffix;
SvxNumberType aFmt;
USHORT nOffset;
protected:
SwFmtFtnEndAtTxtEnd( USHORT nWhichL, SwFtnEndPosEnum ePos )
: SfxEnumItem( nWhichL, sal::static_int_cast< USHORT >(ePos) ), nOffset( 0 )
{}
SwFmtFtnEndAtTxtEnd( const SwFmtFtnEndAtTxtEnd& rAttr )
: SfxEnumItem( rAttr ), sPrefix( rAttr.sPrefix ),
sSuffix( rAttr.sSuffix ), aFmt( rAttr.aFmt ),
nOffset( rAttr.nOffset )
{}
public:
virtual USHORT GetValueCount() const;
virtual int operator==( const SfxPoolItem& ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// will be used at time??
// void FillVariable( SbxVariable &rVar,
// SfxMapUnit eCoreMetric,
// SfxMapUnit eUserMetric ) const;
// virtual SfxArgumentError SetVariable( const SbxVariable &rVal,
// SfxMapUnit eCoreMetric,
// SfxMapUnit eUserMetric );
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
inline BOOL IsAtEnd() const { return FTNEND_ATPGORDOCEND != GetValue(); }
SwFmtFtnEndAtTxtEnd & operator=( const SwFmtFtnEndAtTxtEnd & rAttr );
sal_Int16 GetNumType() const { return aFmt.GetNumberingType(); }
void SetNumType( sal_Int16 eType ) { aFmt.SetNumberingType(eType); }
const SvxNumberType& GetSwNumType() const { return aFmt; }
USHORT GetOffset() const { return nOffset; }
void SetOffset( USHORT nOff ) { nOffset = nOff; }
const String& GetPrefix() const { return sPrefix; }
void SetPrefix(const String& rSet) { sPrefix = rSet; }
const String& GetSuffix() const { return sSuffix; }
void SetSuffix(const String& rSet) { sSuffix = rSet; }
};
class SW_DLLPUBLIC SwFmtFtnAtTxtEnd : public SwFmtFtnEndAtTxtEnd
{
public:
SwFmtFtnAtTxtEnd( SwFtnEndPosEnum ePos = FTNEND_ATPGORDOCEND )
: SwFmtFtnEndAtTxtEnd( RES_FTN_AT_TXTEND, ePos )
{}
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
};
class SW_DLLPUBLIC SwFmtEndAtTxtEnd : public SwFmtFtnEndAtTxtEnd
{
public:
SwFmtEndAtTxtEnd( SwFtnEndPosEnum ePos = FTNEND_ATPGORDOCEND )
: SwFmtFtnEndAtTxtEnd( RES_END_AT_TXTEND, ePos )
{
SetNumType( SVX_NUM_ROMAN_LOWER );
}
virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const;
};
inline const SwFmtFtnAtTxtEnd &SwAttrSet::GetFtnAtTxtEnd(BOOL bInP) const
{ return (const SwFmtFtnAtTxtEnd&)Get( RES_FTN_AT_TXTEND, bInP); }
inline const SwFmtEndAtTxtEnd &SwAttrSet::GetEndAtTxtEnd(BOOL bInP) const
{ return (const SwFmtEndAtTxtEnd&)Get( RES_END_AT_TXTEND, bInP); }
inline const SwFmtFtnAtTxtEnd &SwFmt::GetFtnAtTxtEnd(BOOL bInP) const
{ return aSet.GetFtnAtTxtEnd(bInP); }
inline const SwFmtEndAtTxtEnd &SwFmt::GetEndAtTxtEnd(BOOL bInP) const
{ return aSet.GetEndAtTxtEnd(bInP); }
#endif
<|endoftext|> |
<commit_before>//
// Created by Axel Naumann on 09/12/15.
//
//#include "cling/Interpreter/Jupyter/Kernel.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <string>
#include <cstring>
// FIXME: should be moved into a Jupyter interp struct that then gets returned
// from create.
int pipeToJupyterFD = -1;
namespace cling {
namespace Jupyter {
struct MIMEDataRef {
const char* m_Data;
const long m_Size;
MIMEDataRef(const std::string& str):
m_Data(str.c_str()), m_Size((long)str.length() + 1) {}
MIMEDataRef(const char* str):
MIMEDataRef(std::string(str)) {}
MIMEDataRef(const char* data, long size):
m_Data(data), m_Size(size) {}
};
/// Push MIME stuff to Jupyter. To be called from user code.
///\param contentDict - dictionary of MIME type versus content. E.g.
/// {{"text/html", {"<div></div>", }}
void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) {
// Pipe sees (all numbers are longs, except for the first:
// - num bytes in a long (sent as a single unsigned char!)
// - num elements of the MIME dictionary; Jupyter selects one to display.
// For each MIME dictionary element:
// - size of MIME type string (including the terminating 0)
// - MIME type as 0-terminated string
// - size of MIME data buffer (including the terminating 0 for
// 0-terminated strings)
// - MIME data buffer
// Write number of dictionary elements (and the size of that number in a
// char)
unsigned char sizeLong = sizeof(long);
write(pipeToJupyterFD, &sizeLong, 1);
long dictSize = contentDict.size();
write(pipeToJupyterFD, &dictSize, sizeof(long));
for (auto iContent: contentDict) {
const std::string& mimeType = iContent.first;
long mimeTypeSize = (long)mimeType.size();
write(pipeToJupyterFD, &mimeTypeSize, sizeof(long));
write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1);
const MIMEDataRef& mimeData = iContent.second;
write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long));
write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size);
}
}
} // namespace Jupyter
} // namespace cling
extern "C" {
///\{
///\name Cling4CTypes
/// The Python compatible view of cling
/// The Interpreter object cast to void*
using TheInterpreter = void ;
/// Create an interpreter object.
TheInterpreter*
cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) {
auto interp = new cling::Interpreter(argc, argv, llvmdir);
pipeToJupyterFD = pipefd;
return interp;
}
/// Destroy the interpreter.
void cling_destroy(TheInterpreter *interpVP) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
delete interp;
}
/// Stringify a cling::Value
static std::string ValueToString(const cling::Value& V) {
std::string valueString;
{
llvm::raw_string_ostream os(valueString);
V.print(os);
}
return valueString;
}
/// Evaluate a string of code. Returns nullptr on failure.
/// Returns a string representation of the expression (can be "") on success.
char* cling_eval(TheInterpreter *interpVP, const char *code) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
cling::Value V;
cling::Interpreter::CompilationResult Res = interp->process(code, &V);
if (Res != cling::Interpreter::kSuccess)
return nullptr;
cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}});
if (!V.isValid())
return strdup("");
return strdup(ValueToString(V).c_str());
}
void cling_eval_free(char* str) {
free(str);
}
/// Code completion interfaces.
/// Start completion of code. Returns a handle to be passed to
/// cling_complete_next() to iterate over the completion options. Returns nulptr
/// if no completions are known.
void* cling_complete_start(const char* code) {
return new int(42);
}
/// Grab the next completion of some code. Returns nullptr if none is left.
const char* cling_complete_next(void* completionHandle) {
int* counter = (int*) completionHandle;
if (++(*counter) > 43) {
delete counter;
return nullptr;
}
return "COMPLETE!";
}
///\}
} // extern "C"
<commit_msg>Use evaluate(); process prints the value.<commit_after>//
// Created by Axel Naumann on 09/12/15.
//
//#include "cling/Interpreter/Jupyter/Kernel.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <string>
#include <cstring>
// FIXME: should be moved into a Jupyter interp struct that then gets returned
// from create.
int pipeToJupyterFD = -1;
namespace cling {
namespace Jupyter {
struct MIMEDataRef {
const char* m_Data;
const long m_Size;
MIMEDataRef(const std::string& str):
m_Data(str.c_str()), m_Size((long)str.length() + 1) {}
MIMEDataRef(const char* str):
MIMEDataRef(std::string(str)) {}
MIMEDataRef(const char* data, long size):
m_Data(data), m_Size(size) {}
};
/// Push MIME stuff to Jupyter. To be called from user code.
///\param contentDict - dictionary of MIME type versus content. E.g.
/// {{"text/html", {"<div></div>", }}
void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) {
// Pipe sees (all numbers are longs, except for the first:
// - num bytes in a long (sent as a single unsigned char!)
// - num elements of the MIME dictionary; Jupyter selects one to display.
// For each MIME dictionary element:
// - size of MIME type string (including the terminating 0)
// - MIME type as 0-terminated string
// - size of MIME data buffer (including the terminating 0 for
// 0-terminated strings)
// - MIME data buffer
// Write number of dictionary elements (and the size of that number in a
// char)
unsigned char sizeLong = sizeof(long);
write(pipeToJupyterFD, &sizeLong, 1);
long dictSize = contentDict.size();
write(pipeToJupyterFD, &dictSize, sizeof(long));
for (auto iContent: contentDict) {
const std::string& mimeType = iContent.first;
long mimeTypeSize = (long)mimeType.size();
write(pipeToJupyterFD, &mimeTypeSize, sizeof(long));
write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1);
const MIMEDataRef& mimeData = iContent.second;
write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long));
write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size);
}
}
} // namespace Jupyter
} // namespace cling
extern "C" {
///\{
///\name Cling4CTypes
/// The Python compatible view of cling
/// The Interpreter object cast to void*
using TheInterpreter = void ;
/// Create an interpreter object.
TheInterpreter*
cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) {
auto interp = new cling::Interpreter(argc, argv, llvmdir);
pipeToJupyterFD = pipefd;
return interp;
}
/// Destroy the interpreter.
void cling_destroy(TheInterpreter *interpVP) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
delete interp;
}
/// Stringify a cling::Value
static std::string ValueToString(const cling::Value& V) {
std::string valueString;
{
llvm::raw_string_ostream os(valueString);
V.print(os);
}
return valueString;
}
/// Evaluate a string of code. Returns nullptr on failure.
/// Returns a string representation of the expression (can be "") on success.
char* cling_eval(TheInterpreter *interpVP, const char *code) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
cling::Value V;
cling::Interpreter::CompilationResult Res = interp->evaluate(code, V);
if (Res != cling::Interpreter::kSuccess)
return nullptr;
cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}});
if (!V.isValid())
return strdup("");
return strdup(ValueToString(V).c_str());
}
void cling_eval_free(char* str) {
free(str);
}
/// Code completion interfaces.
/// Start completion of code. Returns a handle to be passed to
/// cling_complete_next() to iterate over the completion options. Returns nulptr
/// if no completions are known.
void* cling_complete_start(const char* code) {
return new int(42);
}
/// Grab the next completion of some code. Returns nullptr if none is left.
const char* cling_complete_next(void* completionHandle) {
int* counter = (int*) completionHandle;
if (++(*counter) > 43) {
delete counter;
return nullptr;
}
return "COMPLETE!";
}
///\}
} // extern "C"
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/spalart_allmaras_spgsm_stab.h"
// GRINS
#include "grins/assembly_context.h"
#include "grins/constant_viscosity.h"
#include "grins/parsed_viscosity.h"
#include "grins/spalart_allmaras_viscosity.h"
#include "grins/turbulence_models_macro.h"
//libMesh
#include "libmesh/quadrature.h"
namespace GRINS
{
template<class Mu>
SpalartAllmarasSPGSMStabilization<Mu>::SpalartAllmarasSPGSMStabilization( const std::string& physics_name,
const GetPot& input )
: SpalartAllmarasStabilizationBase<Mu>(physics_name,input)
{
this->read_input_options(input);
return;
}
template<class Mu>
SpalartAllmarasSPGSMStabilization<Mu>::~SpalartAllmarasSPGSMStabilization()
{
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::init_variables( libMesh::FEMSystem* system )
{
// Init base class variables for stab_helper and distance function initialization
SpalartAllmarasStabilizationBase<Mu>::init_variables(system);
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("SpalartAllmarasSPGSMStabilization::element_time_derivative");
#endif
// Get a pointer to the current element, we need this for computing the distance to wall for the
// quadrature points
libMesh::Elem &elem_pointer = context.get_elem();
// The number of local degrees of freedom in each variable.
const unsigned int n_nu_dofs = context.get_dof_indices(this->_turbulence_vars.nu_var()).size();
// Element Jacobian * quadrature weights for interior integration.
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_JxW();
// The viscosity shape function gradients (in global coords.)
// at interior quadrature points.
const std::vector<std::vector<libMesh::RealGradient> >& nu_gradphi =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_dphi();
// Quadrature point locations
//const std::vector<libMesh::Point>& nu_qpoint =
//context.get_element_fe(this->_turbulence_vars.nu_var())->get_xyz();
//libMesh::DenseSubMatrix<libMesh::Number> &Knunu = context.get_elem_jacobian(this->_turbulence_vars.nu_var(), this->_turbulence_vars.nu_var()); // R_{nu},{nu}
libMesh::DenseSubVector<libMesh::Number> &Fnu = context.get_elem_residual(this->_turbulence_vars.nu_var()); // R_{nu}
libMesh::FEBase* fe = context.get_element_fe(this->_turbulence_vars.nu_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Auto pointer to distance fcn evaluated at quad points
libMesh::AutoPtr< libMesh::DenseVector<libMesh::Real> > distance_qp;
// Fill the vector of distances to quadrature points
distance_qp = this->distance_function->interpolate(&elem_pointer, context.get_element_qrule().get_points());
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::Gradient grad_nu;
grad_nu = context.interior_gradient(this->_turbulence_vars.nu_var(), qp);
libMesh::Real jac = JxW[qp];
// The physical viscosity
libMesh::Real _mu_qp = this->_mu(context, qp);
// To be fixed
// For the channel flow we will just set the distance function analytically
//(*distance_qp)(qp) = std::min(fabs(y),fabs(1 - y));
// The flow velocity
libMesh::Number u,v;
u = context.interior_value(this->_flow_vars.u_var(), qp);
v = context.interior_value(this->_flow_vars.v_var(), qp);
libMesh::NumberVectorValue U(u,v);
if (this->_dim == 3)
U(2) = context.interior_value(this->_flow_vars.w_var(), qp);
// Stabilization terms
libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );
libMesh::Real tau_spalart = this->_stab_helper.compute_tau_spalart( context, qp, g, G, this->_rho, U, _mu_qp, this->_is_steady );
libMesh::Number RM_spalart = this->_stab_helper.compute_res_spalart_steady( context, qp, this->_rho, _mu_qp, (*distance_qp)(qp) );
for (unsigned int i=0; i != n_nu_dofs; i++)
{
Fnu(i) += jac*( -tau_spalart*RM_spalart*this->_rho*(U*nu_gradphi[i][qp]) );
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("SpalartAllmarasSPGSMStabilization::element_time_derivative");
#endif
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::mass_residual( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("SpalartAllmarasSPGSMStabilization::mass_residual");
#endif
// Get a pointer to the current element, we need this for computing the distance to wall for the
// quadrature points
libMesh::Elem &elem_pointer = context.get_elem();
// The number of local degrees of freedom in each variable.
const unsigned int n_nu_dofs = context.get_dof_indices(this->_turbulence_vars.nu_var()).size();
// Element Jacobian * quadrature weights for interior integration.
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_JxW();
// The pressure shape functions at interior quadrature points.
const std::vector<std::vector<libMesh::RealGradient> >& nu_gradphi =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_dphi();
libMesh::DenseSubVector<libMesh::Number> &Fnu = context.get_elem_residual(this->_turbulence_vars.nu_var()); // R_{nu}
libMesh::FEBase* fe = context.get_element_fe(this->_turbulence_vars.nu_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Auto pointer to distance fcn evaluated at quad points
libMesh::AutoPtr< libMesh::DenseVector<libMesh::Real> > distance_qp;
// Fill the vector of distances to quadrature points
distance_qp = this->distance_function->interpolate(&elem_pointer, context.get_element_qrule().get_points());
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );
libMesh::RealGradient U( context.fixed_interior_value( this->_flow_vars.u_var(), qp ),
context.fixed_interior_value( this->_flow_vars.v_var(), qp ) );
// Compute the viscosity at this qp
libMesh::Real _mu_qp = this->_mu(context, qp);
if( this->_dim == 3 )
{
U(2) = context.fixed_interior_value( this->_flow_vars.w_var(), qp );
}
libMesh::Real tau_spalart = this->_stab_helper.compute_tau_spalart( context, qp, g, G, this->_rho, U, _mu_qp, this->_is_steady );
libMesh::Real RM_spalart = this->_stab_helper.compute_res_spalart_transient( context, qp, this->_rho );
for (unsigned int i=0; i != n_nu_dofs; i++)
{
Fnu(i) += -JxW[qp]*tau_spalart*RM_spalart*this->_rho*(U*nu_gradphi[i][qp]);
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("SpalartAllmarasSPGSMStabilization::mass_residual");
#endif
return;
}
} // end namespace GRINS
// Instantiate
INSTANTIATE_TURBULENCE_MODELS_SUBCLASS(SpalartAllmarasSPGSMStabilization);
<commit_msg>Untabify/whitespace<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
// This class
#include "grins/spalart_allmaras_spgsm_stab.h"
// GRINS
#include "grins/assembly_context.h"
#include "grins/constant_viscosity.h"
#include "grins/parsed_viscosity.h"
#include "grins/spalart_allmaras_viscosity.h"
#include "grins/turbulence_models_macro.h"
//libMesh
#include "libmesh/quadrature.h"
namespace GRINS
{
template<class Mu>
SpalartAllmarasSPGSMStabilization<Mu>::SpalartAllmarasSPGSMStabilization( const std::string& physics_name,
const GetPot& input )
: SpalartAllmarasStabilizationBase<Mu>(physics_name,input)
{
this->read_input_options(input);
return;
}
template<class Mu>
SpalartAllmarasSPGSMStabilization<Mu>::~SpalartAllmarasSPGSMStabilization()
{
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::init_variables( libMesh::FEMSystem* system )
{
// Init base class variables for stab_helper and distance function initialization
SpalartAllmarasStabilizationBase<Mu>::init_variables(system);
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::element_time_derivative( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("SpalartAllmarasSPGSMStabilization::element_time_derivative");
#endif
// Get a pointer to the current element, we need this for computing the distance to wall for the
// quadrature points
libMesh::Elem &elem_pointer = context.get_elem();
// The number of local degrees of freedom in each variable.
const unsigned int n_nu_dofs = context.get_dof_indices(this->_turbulence_vars.nu_var()).size();
// Element Jacobian * quadrature weights for interior integration.
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_JxW();
// The viscosity shape function gradients (in global coords.)
// at interior quadrature points.
const std::vector<std::vector<libMesh::RealGradient> >& nu_gradphi =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_dphi();
// Quadrature point locations
//const std::vector<libMesh::Point>& nu_qpoint =
//context.get_element_fe(this->_turbulence_vars.nu_var())->get_xyz();
//libMesh::DenseSubMatrix<libMesh::Number> &Knunu = context.get_elem_jacobian(this->_turbulence_vars.nu_var(), this->_turbulence_vars.nu_var()); // R_{nu},{nu}
libMesh::DenseSubVector<libMesh::Number> &Fnu = context.get_elem_residual(this->_turbulence_vars.nu_var()); // R_{nu}
libMesh::FEBase* fe = context.get_element_fe(this->_turbulence_vars.nu_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Auto pointer to distance fcn evaluated at quad points
libMesh::AutoPtr< libMesh::DenseVector<libMesh::Real> > distance_qp;
// Fill the vector of distances to quadrature points
distance_qp = this->distance_function->interpolate(&elem_pointer, context.get_element_qrule().get_points());
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::Gradient grad_nu;
grad_nu = context.interior_gradient(this->_turbulence_vars.nu_var(), qp);
libMesh::Real jac = JxW[qp];
// The physical viscosity
libMesh::Real _mu_qp = this->_mu(context, qp);
// To be fixed
// For the channel flow we will just set the distance function analytically
//(*distance_qp)(qp) = std::min(fabs(y),fabs(1 - y));
// The flow velocity
libMesh::Number u,v;
u = context.interior_value(this->_flow_vars.u_var(), qp);
v = context.interior_value(this->_flow_vars.v_var(), qp);
libMesh::NumberVectorValue U(u,v);
if (this->_dim == 3)
U(2) = context.interior_value(this->_flow_vars.w_var(), qp);
// Stabilization terms
libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );
libMesh::Real tau_spalart = this->_stab_helper.compute_tau_spalart( context, qp, g, G, this->_rho, U, _mu_qp, this->_is_steady );
libMesh::Number RM_spalart = this->_stab_helper.compute_res_spalart_steady( context, qp, this->_rho, _mu_qp, (*distance_qp)(qp) );
for (unsigned int i=0; i != n_nu_dofs; i++)
{
Fnu(i) += jac*( -tau_spalart*RM_spalart*this->_rho*(U*nu_gradphi[i][qp]) );
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("SpalartAllmarasSPGSMStabilization::element_time_derivative");
#endif
return;
}
template<class Mu>
void SpalartAllmarasSPGSMStabilization<Mu>::mass_residual( bool compute_jacobian,
AssemblyContext& context,
CachedValues& /*cache*/ )
{
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->BeginTimer("SpalartAllmarasSPGSMStabilization::mass_residual");
#endif
// Get a pointer to the current element, we need this for computing the distance to wall for the
// quadrature points
libMesh::Elem &elem_pointer = context.get_elem();
// The number of local degrees of freedom in each variable.
const unsigned int n_nu_dofs = context.get_dof_indices(this->_turbulence_vars.nu_var()).size();
// Element Jacobian * quadrature weights for interior integration.
const std::vector<libMesh::Real> &JxW =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_JxW();
// The pressure shape functions at interior quadrature points.
const std::vector<std::vector<libMesh::RealGradient> >& nu_gradphi =
context.get_element_fe(this->_turbulence_vars.nu_var())->get_dphi();
libMesh::DenseSubVector<libMesh::Number> &Fnu = context.get_elem_residual(this->_turbulence_vars.nu_var()); // R_{nu}
libMesh::FEBase* fe = context.get_element_fe(this->_turbulence_vars.nu_var());
unsigned int n_qpoints = context.get_element_qrule().n_points();
// Auto pointer to distance fcn evaluated at quad points
libMesh::AutoPtr< libMesh::DenseVector<libMesh::Real> > distance_qp;
// Fill the vector of distances to quadrature points
distance_qp = this->distance_function->interpolate(&elem_pointer, context.get_element_qrule().get_points());
for (unsigned int qp=0; qp != n_qpoints; qp++)
{
libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );
libMesh::RealGradient U( context.fixed_interior_value( this->_flow_vars.u_var(), qp ),
context.fixed_interior_value( this->_flow_vars.v_var(), qp ) );
// Compute the viscosity at this qp
libMesh::Real _mu_qp = this->_mu(context, qp);
if( this->_dim == 3 )
{
U(2) = context.fixed_interior_value( this->_flow_vars.w_var(), qp );
}
libMesh::Real tau_spalart = this->_stab_helper.compute_tau_spalart( context, qp, g, G, this->_rho, U, _mu_qp, this->_is_steady );
libMesh::Real RM_spalart = this->_stab_helper.compute_res_spalart_transient( context, qp, this->_rho );
for (unsigned int i=0; i != n_nu_dofs; i++)
{
Fnu(i) += -JxW[qp]*tau_spalart*RM_spalart*this->_rho*(U*nu_gradphi[i][qp]);
}
if( compute_jacobian )
{
libmesh_not_implemented();
}
}
#ifdef GRINS_USE_GRVY_TIMERS
this->_timer->EndTimer("SpalartAllmarasSPGSMStabilization::mass_residual");
#endif
return;
}
} // end namespace GRINS
// Instantiate
INSTANTIATE_TURBULENCE_MODELS_SUBCLASS(SpalartAllmarasSPGSMStabilization);
<|endoftext|> |
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "circles.h"
#include "debug.h"
#include "const.h"
#include "camera.h"
#include "calibrate.h"
using namespace cv;
namespace cal{
void wait_for_key();
vector<Point> find_smallest_square(const vector<vector<Point> >& squares);
void findSquares(const Mat& image, vector<vector<Point> >& squares);
Mat src, out;
void drawSquare(Mat& image, const vector<Point>& square, Scalar color){
const Point* p = &square[0];
int n = (int)square.size();
polylines(image, &p, &n, 1, true, color, 3);
}
// the function draws all the squares in the image
void drawSquares(Mat& image, const vector<vector<Point> >& squares, Scalar color)
{
for (size_t i = 0; i < squares.size(); i++)
{
drawSquare(image, squares[i], color);
}
}
void calibrate(Camera& cam){
namedWindow(CAL_WIN, CV_WINDOW_AUTOSIZE);
out = Mat::zeros(OUT_HEIGHT, OUT_WIDTH, CV_8UC3);
imshow(CAL_WIN, out);
wait_for_key();
out = Scalar(CAL_COLOR);
imshow(CAL_WIN, out);
wait_for_key();
cam.get_raw_frame();
cam.get_raw_frame();
vector<vector<Point>> squares;
findSquares(cam.src, squares);
drawSquares(cam.src, squares, Scalar(0, 255, 0));
vector<Point> smallest_square = find_smallest_square(squares);
drawSquare(cam.src, smallest_square, Scalar(255, 0, 0));
imshow(CAL_WIN, cam.src);
wait_for_key();
cam.aoi = boundingRect(Mat(smallest_square));
cam.y_scale = (float)OUT_HEIGHT / cam.aoi.height;
cam.x_scale = (float)OUT_WIDTH / cam.aoi.width;
destroyWindow(CAL_WIN);
}
void wait_for_key(){
while (waitKey(10) < 0);
}
vector<Point> find_smallest_square(const vector<vector<Point> >& squares)
{
vector<Point> biggest_square;
int min_area = 65535;
int max_square_idx = 0;
const int n_points = 4;
for (size_t i = 0; i < squares.size(); i++)
{
// Convert a set of 4 unordered Points into a meaningful cv::Rect structure.
Rect rectangle = boundingRect(Mat(squares[i]));
// cout << "find_largest_square: #" << i << " rectangle x:" << rectangle.x << " y:" << rectangle.y << " " << rectangle.width << "x" << rectangle.height << endl;
// Store the index position of the biggest square found
if (rectangle.area() < min_area)
{
min_area = rectangle.area();
max_square_idx = i;
}
}
biggest_square = squares[max_square_idx];
return biggest_square;
}
// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle(Point pt1, Point pt2, Point pt0)
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2) / sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
static void findSquares(const Mat& image, vector<vector<Point> >& squares)
{
squares.clear();
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols / 2, image.rows / 2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; c++)
{
int ch[] = { c, 0 };
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for (int l = 0; l < CAL_ITER; l++)
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if (l == 0)
{
// apply Canny. Take the upper threshold from slider
// and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, SQ_THRESH, 5);
// dilate canny output to remove potential
// holes between edge segments
dilate(gray, gray, Mat(), Point(-1, -1));
}
else
{
// apply threshold if l!=0:
// tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l + 1) * 255 / CAL_ITER;
}
// find contours and store them all as a list
findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
vector<Point> approx;
// test each contour
for (size_t i = 0; i < contours.size(); i++)
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
// find the maximum cosine of the angle between joint edges
double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
maxCosine = MAX(maxCosine, cosine);
}
// if cosines of all angles are small
// (all angles are ~90 degree) then write quandrange
// vertices to resultant sequence
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
}
}<commit_msg>Remove step from calibration<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "circles.h"
#include "debug.h"
#include "const.h"
#include "camera.h"
#include "calibrate.h"
using namespace cv;
namespace cal{
void wait_for_key();
vector<Point> find_smallest_square(const vector<vector<Point> >& squares);
void findSquares(const Mat& image, vector<vector<Point> >& squares);
Mat src, out;
void drawSquare(Mat& image, const vector<Point>& square, Scalar color){
const Point* p = &square[0];
int n = (int)square.size();
polylines(image, &p, &n, 1, true, color, 3);
}
// the function draws all the squares in the image
void drawSquares(Mat& image, const vector<vector<Point> >& squares, Scalar color)
{
for (size_t i = 0; i < squares.size(); i++)
{
drawSquare(image, squares[i], color);
}
}
void calibrate(Camera& cam){
namedWindow(CAL_WIN, CV_WINDOW_AUTOSIZE);
out = Mat::zeros(OUT_HEIGHT, OUT_WIDTH, CV_8UC3);
out = Scalar(CAL_COLOR);
imshow(CAL_WIN, out);
wait_for_key();
cam.get_raw_frame();
cam.get_raw_frame();
vector<vector<Point>> squares;
findSquares(cam.src, squares);
drawSquares(cam.src, squares, Scalar(0, 255, 0));
vector<Point> smallest_square = find_smallest_square(squares);
drawSquare(cam.src, smallest_square, Scalar(255, 0, 0));
imshow(CAL_WIN, cam.src);
wait_for_key();
cam.aoi = boundingRect(Mat(smallest_square));
cam.y_scale = (float)OUT_HEIGHT / cam.aoi.height;
cam.x_scale = (float)OUT_WIDTH / cam.aoi.width;
destroyWindow(CAL_WIN);
}
void wait_for_key(){
while (waitKey(10) < 0);
}
vector<Point> find_smallest_square(const vector<vector<Point> >& squares)
{
vector<Point> biggest_square;
int min_area = 65535;
int max_square_idx = 0;
const int n_points = 4;
for (size_t i = 0; i < squares.size(); i++)
{
// Convert a set of 4 unordered Points into a meaningful cv::Rect structure.
Rect rectangle = boundingRect(Mat(squares[i]));
// cout << "find_largest_square: #" << i << " rectangle x:" << rectangle.x << " y:" << rectangle.y << " " << rectangle.width << "x" << rectangle.height << endl;
// Store the index position of the biggest square found
if (rectangle.area() < min_area)
{
min_area = rectangle.area();
max_square_idx = i;
}
}
biggest_square = squares[max_square_idx];
return biggest_square;
}
// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle(Point pt1, Point pt2, Point pt0)
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2) / sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
static void findSquares(const Mat& image, vector<vector<Point> >& squares)
{
squares.clear();
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols / 2, image.rows / 2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; c++)
{
int ch[] = { c, 0 };
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for (int l = 0; l < CAL_ITER; l++)
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if (l == 0)
{
// apply Canny. Take the upper threshold from slider
// and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, SQ_THRESH, 5);
// dilate canny output to remove potential
// holes between edge segments
dilate(gray, gray, Mat(), Point(-1, -1));
}
else
{
// apply threshold if l!=0:
// tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l + 1) * 255 / CAL_ITER;
}
// find contours and store them all as a list
findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
vector<Point> approx;
// test each contour
for (size_t i = 0; i < contours.size(); i++)
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
// find the maximum cosine of the angle between joint edges
double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
maxCosine = MAX(maxCosine, cosine);
}
// if cosines of all angles are small
// (all angles are ~90 degree) then write quandrange
// vertices to resultant sequence
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
}
}<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ioutputparser.h"
#include "utils/qtcassert.h"
namespace ProjectExplorer {
IOutputParser::IOutputParser() : m_parser(0)
{
}
IOutputParser::~IOutputParser()
{
delete m_parser;
}
void IOutputParser::appendOutputParser(IOutputParser *parser)
{
QTC_ASSERT(parser, return);
if (m_parser) {
m_parser->appendOutputParser(parser);
return;
}
m_parser = parser;
connect(parser, SIGNAL(addOutput(QString)),
this, SLOT(outputAdded(QString)));
connect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)));
}
IOutputParser *IOutputParser::takeOutputParserChain()
{
IOutputParser *parser = m_parser;
m_parser = 0;
return parser;
}
IOutputParser *IOutputParser::childParser() const
{
return m_parser;
}
void IOutputParser::stdOutput(const QString &line)
{
if (m_parser)
m_parser->stdOutput(line);
}
void IOutputParser::stdError(const QString &line)
{
if (m_parser)
m_parser->stdError(line);
}
void IOutputParser::outputAdded(const QString &string)
{
emit addOutput(string);
}
void IOutputParser::taskAdded(const ProjectExplorer::Task &task)
{
emit addTask(task);
}
}
<commit_msg>Direct connection for build parsers<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ioutputparser.h"
#include "utils/qtcassert.h"
namespace ProjectExplorer {
IOutputParser::IOutputParser() : m_parser(0)
{
}
IOutputParser::~IOutputParser()
{
delete m_parser;
}
void IOutputParser::appendOutputParser(IOutputParser *parser)
{
QTC_ASSERT(parser, return);
if (m_parser) {
m_parser->appendOutputParser(parser);
return;
}
m_parser = parser;
connect(parser, SIGNAL(addOutput(QString)),
this, SLOT(outputAdded(QString)), Qt::DirectConnection);
connect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)), Qt::DirectConnection);
}
IOutputParser *IOutputParser::takeOutputParserChain()
{
IOutputParser *parser = m_parser;
m_parser = 0;
return parser;
}
IOutputParser *IOutputParser::childParser() const
{
return m_parser;
}
void IOutputParser::stdOutput(const QString &line)
{
if (m_parser)
m_parser->stdOutput(line);
}
void IOutputParser::stdError(const QString &line)
{
if (m_parser)
m_parser->stdError(line);
}
void IOutputParser::outputAdded(const QString &string)
{
emit addOutput(string);
}
void IOutputParser::taskAdded(const ProjectExplorer::Task &task)
{
emit addTask(task);
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ioutputparser.h"
#include "utils/qtcassert.h"
namespace ProjectExplorer {
IOutputParser::IOutputParser() : m_parser(0)
{
}
IOutputParser::~IOutputParser()
{
delete m_parser;
}
void IOutputParser::appendOutputParser(IOutputParser *parser)
{
QTC_ASSERT(parser, return);
if (m_parser) {
m_parser->appendOutputParser(parser);
return;
}
m_parser = parser;
connect(parser, SIGNAL(addOutput(QString, ProjectExplorer::BuildStep::OutputFormat)),
this, SLOT(outputAdded(QString, ProjectExplorer::BuildStep::OutputFormat)), Qt::DirectConnection);
connect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)), Qt::DirectConnection);
}
IOutputParser *IOutputParser::takeOutputParserChain()
{
IOutputParser *parser = m_parser;
disconnect(parser, SIGNAL(addOutput(QString, QTextCharFormat)),
this, SLOT(outputAdded(QString, QTextCharFormat)));
disconnect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)));
m_parser = 0;
return parser;
}
IOutputParser *IOutputParser::childParser() const
{
return m_parser;
}
void IOutputParser::stdOutput(const QString &line)
{
if (m_parser)
m_parser->stdOutput(line);
}
void IOutputParser::stdError(const QString &line)
{
if (m_parser)
m_parser->stdError(line);
}
void IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format)
{
emit addOutput(string, format);
}
void IOutputParser::taskAdded(const ProjectExplorer::Task &task)
{
emit addTask(task);
}
}
<commit_msg>Use cannonical form in SIGNAL/SLOT macros<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "ioutputparser.h"
#include "utils/qtcassert.h"
namespace ProjectExplorer {
IOutputParser::IOutputParser() : m_parser(0)
{
}
IOutputParser::~IOutputParser()
{
delete m_parser;
}
void IOutputParser::appendOutputParser(IOutputParser *parser)
{
QTC_ASSERT(parser, return);
if (m_parser) {
m_parser->appendOutputParser(parser);
return;
}
m_parser = parser;
connect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)),
this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat)), Qt::DirectConnection);
connect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)), Qt::DirectConnection);
}
IOutputParser *IOutputParser::takeOutputParserChain()
{
IOutputParser *parser = m_parser;
disconnect(parser, SIGNAL(addOutput(QString, QTextCharFormat)),
this, SLOT(outputAdded(QString, QTextCharFormat)));
disconnect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)));
m_parser = 0;
return parser;
}
IOutputParser *IOutputParser::childParser() const
{
return m_parser;
}
void IOutputParser::stdOutput(const QString &line)
{
if (m_parser)
m_parser->stdOutput(line);
}
void IOutputParser::stdError(const QString &line)
{
if (m_parser)
m_parser->stdError(line);
}
void IOutputParser::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format)
{
emit addOutput(string, format);
}
void IOutputParser::taskAdded(const ProjectExplorer::Task &task)
{
emit addTask(task);
}
}
<|endoftext|> |
<commit_before>// Umar Arshad
// Copyright 2014
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
using namespace std;
typedef map<string, string> opt_t;
void print_usage() {
cout << R"delimiter(BIN2CPP
Converts files from a binary file to C++ headers. It is similar to bin2c and
xxd but adds support for namespaces.
| --name | name of the variable (default: var) |
| --file | input file |
| --output | output file (If no output is specified then it prints to stdout |
| --type | Type of variable (default: char) |
| --namespace | A space seperated list of namespaces |
| --formatted | Tabs for formatting |
| --version | Prints my name |
| --help | Prints usage info |
Example
-------
Command:
./bin2cpp --file blah.txt --namespace blah detail --formatted --name blah_var
Will produce:
#include <cstddef>
namespace blah {
namespace detail {
static const char blah_var[] = {
0x2f, 0x2f, 0x20, 0x62, 0x6c, 0x61, 0x68, 0x2e, 0x74, 0x78,
0x74, 0xa, 0x62, 0x6c, 0x61, 0x68, 0x20, 0x62, 0x6c, 0x61,
0x68, 0x20, 0x62, 0x6c, 0x61, 0x68, 0xa, };
static const size_t blah_var_len = 27;
}
})delimiter";
exit(0);
}
static bool formatted;
void add_tabs(const int level ){
if(formatted) {
for(int i =0; i < level; i++) {
cout << "\t";
}
}
}
opt_t
parse_options(const vector<string>& args) {
opt_t options;
options["--name"] = "";
options["--type"] = "";
options["--file"] = "";
options["--output"] = "";
options["--namespace"] = "";
options["--eof"] = "0";
//Parse Arguments
string curr_opt;
bool verbose = false;
for(auto arg : args) {
if(arg == "--verbose") {
verbose = true;
}
else if(arg == "--formatted") {
formatted = true;
}
else if(arg == "--version") {
cout << args[0] << " By Umar Arshad" << endl;
}
else if(arg == "--help") {
print_usage();
}
else if(options.find(arg) != options.end()) {
curr_opt = arg;
}
else if(curr_opt.empty()) {
//cerr << "Invalid Argument: " << arg << endl;
}
else {
if(options[curr_opt] != "") {
options[curr_opt] += " " + arg;
}
else {
options[curr_opt] += arg;
}
}
}
if(verbose) {
for(auto opts : options) {
cout << get<0>(opts) << " " << get<1>(opts) << endl;
}
}
return options;
}
int main(int argc, const char * const * const argv)
{
vector<string> args(argv, argv+argc);
opt_t&& options = parse_options(args);
//Save default cout buffer. Need this to prevent crash.
auto bak = cout.rdbuf();
unique_ptr<ofstream> outfile;
// Set defaults
if(options["--name"] == "") { options["--name"] = "var"; }
if(options["--output"] != "") {
//redirect stream if output file is specified
outfile.reset(new ofstream(options["--output"]));
cout.rdbuf(outfile->rdbuf());
}
cout << "#pragma once\n";
cout << "#include <cstddef>\n"; // defines size_t
int ns_cnt = 0;
int level = 0;
if(options["--namespace"] != "") {
std::stringstream namespaces(options["--namespace"]);
string name;
namespaces >> name;
do {
add_tabs(level++);
cout << "namespace " << name << " { \n";
ns_cnt++;
namespaces >> name;
} while(!namespaces.fail());
}
if(options["--type"] == "") {
options["--type"] = "char";
}
add_tabs(level);
cout << "static const " << options["--type"] << " " << options["--name"] << "[] = {\n";
ifstream input(options["--file"]);
size_t char_cnt = 0;
add_tabs(++level);
for(char i; input.get(i);) {
cout << "0x" << std::hex << static_cast<int>(i & 0xff) << ",\t";
char_cnt++;
if(!(char_cnt % 10)) {
cout << endl;
add_tabs(level);
}
}
if (options["--eof"].c_str()[0] == '1') {
// Add end of file character
cout << "0x0";
char_cnt++;
}
cout << "};\n";
add_tabs(--level);
cout << "static const size_t " << options["--name"] << "_len" << " = " << std::dec << char_cnt << ";\n";
while(ns_cnt--) {
add_tabs(--level);
cout << "}\n";
}
cout.rdbuf(bak);
}
<commit_msg>Fixing bin2cpp to avoid narrowing<commit_after>// Umar Arshad
// Copyright 2014
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <memory>
using namespace std;
typedef map<string, string> opt_t;
void print_usage() {
cout << R"delimiter(BIN2CPP
Converts files from a binary file to C++ headers. It is similar to bin2c and
xxd but adds support for namespaces.
| --name | name of the variable (default: var) |
| --file | input file |
| --output | output file (If no output is specified then it prints to stdout |
| --type | Type of variable (default: char) |
| --namespace | A space seperated list of namespaces |
| --formatted | Tabs for formatting |
| --version | Prints my name |
| --help | Prints usage info |
Example
-------
Command:
./bin2cpp --file blah.txt --namespace blah detail --formatted --name blah_var
Will produce:
#include <cstddef>
namespace blah {
namespace detail {
static const char blah_var[] = {
0x2f, 0x2f, 0x20, 0x62, 0x6c, 0x61, 0x68, 0x2e, 0x74, 0x78,
0x74, 0xa, 0x62, 0x6c, 0x61, 0x68, 0x20, 0x62, 0x6c, 0x61,
0x68, 0x20, 0x62, 0x6c, 0x61, 0x68, 0xa, };
static const size_t blah_var_len = 27;
}
})delimiter";
exit(0);
}
static bool formatted;
void add_tabs(const int level ){
if(formatted) {
for(int i =0; i < level; i++) {
cout << "\t";
}
}
}
opt_t
parse_options(const vector<string>& args) {
opt_t options;
options["--name"] = "";
options["--type"] = "";
options["--file"] = "";
options["--output"] = "";
options["--namespace"] = "";
options["--eof"] = "0";
//Parse Arguments
string curr_opt;
bool verbose = false;
for(auto arg : args) {
if(arg == "--verbose") {
verbose = true;
}
else if(arg == "--formatted") {
formatted = true;
}
else if(arg == "--version") {
cout << args[0] << " By Umar Arshad" << endl;
}
else if(arg == "--help") {
print_usage();
}
else if(options.find(arg) != options.end()) {
curr_opt = arg;
}
else if(curr_opt.empty()) {
//cerr << "Invalid Argument: " << arg << endl;
}
else {
if(options[curr_opt] != "") {
options[curr_opt] += " " + arg;
}
else {
options[curr_opt] += arg;
}
}
}
if(verbose) {
for(auto opts : options) {
cout << get<0>(opts) << " " << get<1>(opts) << endl;
}
}
return options;
}
int main(int argc, const char * const * const argv)
{
vector<string> args(argv, argv+argc);
opt_t&& options = parse_options(args);
//Save default cout buffer. Need this to prevent crash.
auto bak = cout.rdbuf();
unique_ptr<ofstream> outfile;
// Set defaults
if(options["--name"] == "") { options["--name"] = "var"; }
if(options["--output"] != "") {
//redirect stream if output file is specified
outfile.reset(new ofstream(options["--output"]));
cout.rdbuf(outfile->rdbuf());
}
cout << "#pragma once\n";
cout << "#include <cstddef>\n"; // defines size_t
int ns_cnt = 0;
int level = 0;
if(options["--namespace"] != "") {
std::stringstream namespaces(options["--namespace"]);
string name;
namespaces >> name;
do {
add_tabs(level++);
cout << "namespace " << name << " { \n";
ns_cnt++;
namespaces >> name;
} while(!namespaces.fail());
}
if(options["--type"] == "") {
options["--type"] = "char";
}
add_tabs(level);
// Always create unsigned char to avoid narrowing
cout << "static const " << "unsigned char" << " " << options["--name"] << "_uchar [] = {\n";
ifstream input(options["--file"]);
size_t char_cnt = 0;
add_tabs(++level);
for(char i; input.get(i);) {
cout << "0x" << std::hex << static_cast<int>(i & 0xff) << ",\t";
char_cnt++;
if(!(char_cnt % 10)) {
cout << endl;
add_tabs(level);
}
}
if (options["--eof"].c_str()[0] == '1') {
// Add end of file character
cout << "0x0";
char_cnt++;
}
cout << "};\n";
add_tabs(--level);
// Cast to proper output type
cout << "static const "
<< options["--type"] << " *"
<< options["--name"] << " = (const "
<< options["--type"] << " *)"
<< options["--name"] << "_uchar;\n";
cout << "static const size_t " << options["--name"] << "_len" << " = " << std::dec << char_cnt << ";\n";
while(ns_cnt--) {
add_tabs(--level);
cout << "}\n";
}
cout.rdbuf(bak);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilerengine.h"
#include "localqmlprofilerrunner.h"
#include "remotelinuxqmlprofilerrunner.h"
#include <analyzerbase/analyzermanager.h>
#include <coreplugin/icore.h>
#include <debugger/debuggerrunconfigurationaspect.h>
#include <utils/qtcassert.h>
#include <coreplugin/helpmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
#include <qmlprojectmanager/qmlprojectplugin.h>
#include <projectexplorer/environmentaspect.h>
#include <projectexplorer/localapplicationruncontrol.h>
#include <projectexplorer/localapplicationrunconfiguration.h>
#include <qmldebug/qmloutputparser.h>
#include <remotelinux/remotelinuxrunconfiguration.h>
#include <QMainWindow>
#include <QMessageBox>
#include <QTimer>
#include <QTcpServer>
using namespace Analyzer;
using namespace ProjectExplorer;
namespace QmlProfiler {
namespace Internal {
//
// QmlProfilerEnginePrivate
//
class QmlProfilerEngine::QmlProfilerEnginePrivate
{
public:
QmlProfilerEnginePrivate(QmlProfilerEngine *qq, const AnalyzerStartParameters &sp) : q(qq), m_runner(0), sp(sp) {}
~QmlProfilerEnginePrivate() { delete m_runner; }
bool attach(const QString &address, uint port);
AbstractQmlProfilerRunner *createRunner(ProjectExplorer::RunConfiguration *runConfiguration,
QObject *parent);
QmlProfilerEngine *q;
QmlProfilerStateManager *m_profilerState;
AbstractQmlProfilerRunner *m_runner;
QTimer m_noDebugOutputTimer;
QmlDebug::QmlOutputParser m_outputParser;
const AnalyzerStartParameters sp;
};
AbstractQmlProfilerRunner *
QmlProfilerEngine::QmlProfilerEnginePrivate::createRunner(ProjectExplorer::RunConfiguration *runConfiguration,
QObject *parent)
{
AbstractQmlProfilerRunner *runner = 0;
if (!runConfiguration) // attaching
return 0;
ProjectExplorer::EnvironmentAspect *environment
= runConfiguration->extraAspect<ProjectExplorer::EnvironmentAspect>();
QTC_ASSERT(environment, return 0);
if (RemoteLinux::RemoteLinuxRunConfiguration *rmConfig =
qobject_cast<RemoteLinux::RemoteLinuxRunConfiguration *>(runConfiguration)) {
runner = new RemoteLinuxQmlProfilerRunner(rmConfig, parent);
} else {
LocalQmlProfilerRunner::Configuration conf;
if (QmlProjectManager::QmlProjectRunConfiguration *rc1 =
qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration)) {
// This is a "plain" .qmlproject.
conf.executable = rc1->observerPath();
conf.executableArguments = rc1->viewerArguments();
conf.workingDirectory = rc1->workingDirectory();
conf.environment = environment->environment();
} else if (LocalApplicationRunConfiguration *rc2 =
qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
// FIXME: Check.
conf.executable = rc2->executable();
conf.executableArguments = rc2->commandLineArguments();
conf.workingDirectory = rc2->workingDirectory();
conf.environment = environment->environment();
} else {
QTC_CHECK(false);
}
const ProjectExplorer::IDevice::ConstPtr device =
ProjectExplorer::DeviceKitInformation::device(runConfiguration->target()->kit());
QTC_ASSERT(device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE, return 0);
conf.port = sp.analyzerPort;
runner = new LocalQmlProfilerRunner(conf, parent);
}
return runner;
}
//
// QmlProfilerEngine
//
QmlProfilerEngine::QmlProfilerEngine(IAnalyzerTool *tool,
const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
: IAnalyzerEngine(tool, sp, runConfiguration)
, d(new QmlProfilerEnginePrivate(this, sp))
{
d->m_profilerState = 0;
// Only wait 4 seconds for the 'Waiting for connection' on application ouput, then just try to connect
// (application output might be redirected / blocked)
d->m_noDebugOutputTimer.setSingleShot(true);
d->m_noDebugOutputTimer.setInterval(4000);
connect(&d->m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(processIsRunning()));
d->m_outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
connect(&d->m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
this, SLOT(processIsRunning(quint16)));
connect(&d->m_outputParser, SIGNAL(noOutputMessage()),
this, SLOT(processIsRunning()));
connect(&d->m_outputParser, SIGNAL(errorMessage(QString)),
this, SLOT(wrongSetupMessageBox(QString)));
}
QmlProfilerEngine::~QmlProfilerEngine()
{
if (d->m_profilerState && d->m_profilerState->currentState() == QmlProfilerStateManager::AppRunning)
stop();
delete d;
}
bool QmlProfilerEngine::start()
{
QTC_ASSERT(d->m_profilerState, return false);
if (d->m_runner) {
delete d->m_runner;
d->m_runner = 0;
}
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStarting);
if (QmlProjectManager::QmlProjectRunConfiguration *rc =
qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration())) {
if (rc->observerPath().isEmpty()) {
QmlProjectManager::QmlProjectPlugin::showQmlObserverToolWarning();
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
AnalyzerManager::stopTool();
return false;
}
}
d->m_runner = d->createRunner(runConfiguration(), this);
if (LocalQmlProfilerRunner *qmlRunner = qobject_cast<LocalQmlProfilerRunner *>(d->m_runner)) {
if (!qmlRunner->hasExecutable()) {
showNonmodalWarning(tr("No executable file to launch."));
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
AnalyzerManager::stopTool();
return false;
}
}
if (d->m_runner) {
connect(d->m_runner, SIGNAL(stopped()), this, SLOT(processEnded()));
connect(d->m_runner, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
this, SLOT(logApplicationMessage(QString,Utils::OutputFormat)));
d->m_runner->start();
d->m_noDebugOutputTimer.start();
} else {
emit processRunning(startParameters().analyzerPort);
}
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppRunning);
emit starting(this);
return true;
}
void QmlProfilerEngine::stop()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStopRequested);
break;
}
case QmlProfilerStateManager::AppReadyToStop : {
cancelProcess();
break;
}
case QmlProfilerStateManager::AppDying :
// valid, but no further action is needed
break;
default: {
const QString message = QString::fromLatin1("Unexpected engine stop from state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
}
break;
}
}
void QmlProfilerEngine::processEnded()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
AnalyzerManager::stopTool();
emit finished();
break;
}
case QmlProfilerStateManager::AppStopped :
case QmlProfilerStateManager::AppKilled :
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
break;
default: {
const QString message = QString::fromLatin1("Process died unexpectedly from state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
}
break;
}
}
void QmlProfilerEngine::cancelProcess()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppReadyToStop : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStopped);
break;
}
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
break;
}
default: {
const QString message = QString::fromLatin1("Unexpected process termination requested with state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
return;
}
}
if (d->m_runner)
d->m_runner->stop();
emit finished();
}
void QmlProfilerEngine::logApplicationMessage(const QString &msg, Utils::OutputFormat format)
{
emit outputReceived(msg, format);
d->m_outputParser.processOutput(msg);
}
void QmlProfilerEngine::wrongSetupMessageBox(const QString &errorMessage)
{
QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
infoBox->setIcon(QMessageBox::Critical);
infoBox->setWindowTitle(tr("Qt Creator"));
//: %1 is detailed error message
infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
.arg(errorMessage));
infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
infoBox->setDefaultButton(QMessageBox::Ok);
infoBox->setModal(true);
connect(infoBox, SIGNAL(finished(int)),
this, SLOT(wrongSetupMessageBoxFinished(int)));
infoBox->show();
// KILL
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
AnalyzerManager::stopTool();
emit finished();
}
void QmlProfilerEngine::wrongSetupMessageBoxFinished(int button)
{
if (button == QMessageBox::Help) {
Core::HelpManager *helpManager = Core::HelpManager::instance();
helpManager->handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"
"#setting-up-qml-debugging"));
}
}
void QmlProfilerEngine::showNonmodalWarning(const QString &warningMsg)
{
QMessageBox *noExecWarning = new QMessageBox(Core::ICore::mainWindow());
noExecWarning->setIcon(QMessageBox::Warning);
noExecWarning->setWindowTitle(tr("QML Profiler"));
noExecWarning->setText(warningMsg);
noExecWarning->setStandardButtons(QMessageBox::Ok);
noExecWarning->setDefaultButton(QMessageBox::Ok);
noExecWarning->setModal(false);
noExecWarning->show();
}
void QmlProfilerEngine::processIsRunning(quint16 port)
{
d->m_noDebugOutputTimer.stop();
QTC_ASSERT(port == 0
|| port == d->m_runner->debugPort(),
qWarning() << "Port " << port << "from application output does not match"
<< startParameters().connParams.port << "from start parameters.");
if (port > 0)
emit processRunning(port);
else
emit processRunning(d->m_runner->debugPort());
}
////////////////////////////////////////////////////////////////
// Profiler State
void QmlProfilerEngine::registerProfilerStateManager( QmlProfilerStateManager *profilerState )
{
// disconnect old
if (d->m_profilerState)
disconnect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
d->m_profilerState = profilerState;
// connect
if (d->m_profilerState)
connect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
}
void QmlProfilerEngine::profilerStateChanged()
{
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppReadyToStop : {
if (d->m_runner)
cancelProcess();
break;
}
case QmlProfilerStateManager::Idle : {
// When all the profiling is done, delete the profiler runner
// (a new one will be created at start)
d->m_noDebugOutputTimer.stop();
if (d->m_runner) {
delete d->m_runner;
d->m_runner = 0;
}
break;
}
default:
break;
}
}
} // namespace Internal
} // namespace QmlProfiler
<commit_msg>QmlProfilerEngine: Use local variables within scope<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilerengine.h"
#include "localqmlprofilerrunner.h"
#include "remotelinuxqmlprofilerrunner.h"
#include <analyzerbase/analyzermanager.h>
#include <coreplugin/icore.h>
#include <debugger/debuggerrunconfigurationaspect.h>
#include <utils/qtcassert.h>
#include <coreplugin/helpmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
#include <qmlprojectmanager/qmlprojectplugin.h>
#include <projectexplorer/environmentaspect.h>
#include <projectexplorer/localapplicationruncontrol.h>
#include <projectexplorer/localapplicationrunconfiguration.h>
#include <qmldebug/qmloutputparser.h>
#include <remotelinux/remotelinuxrunconfiguration.h>
#include <QMainWindow>
#include <QMessageBox>
#include <QTimer>
#include <QTcpServer>
using namespace Analyzer;
using namespace ProjectExplorer;
namespace QmlProfiler {
namespace Internal {
//
// QmlProfilerEnginePrivate
//
class QmlProfilerEngine::QmlProfilerEnginePrivate
{
public:
QmlProfilerEnginePrivate(QmlProfilerEngine *qq, const AnalyzerStartParameters &sp) : q(qq), m_runner(0), sp(sp) {}
~QmlProfilerEnginePrivate() { delete m_runner; }
bool attach(const QString &address, uint port);
AbstractQmlProfilerRunner *createRunner(ProjectExplorer::RunConfiguration *runConfiguration,
QObject *parent);
QmlProfilerEngine *q;
QmlProfilerStateManager *m_profilerState;
AbstractQmlProfilerRunner *m_runner;
QTimer m_noDebugOutputTimer;
QmlDebug::QmlOutputParser m_outputParser;
const AnalyzerStartParameters sp;
};
AbstractQmlProfilerRunner *
QmlProfilerEngine::QmlProfilerEnginePrivate::createRunner(ProjectExplorer::RunConfiguration *runConfiguration,
QObject *parent)
{
AbstractQmlProfilerRunner *runner = 0;
if (!runConfiguration) // attaching
return 0;
if (RemoteLinux::RemoteLinuxRunConfiguration *rmConfig =
qobject_cast<RemoteLinux::RemoteLinuxRunConfiguration *>(runConfiguration)) {
runner = new RemoteLinuxQmlProfilerRunner(rmConfig, parent);
} else {
ProjectExplorer::EnvironmentAspect *environment
= runConfiguration->extraAspect<ProjectExplorer::EnvironmentAspect>();
QTC_ASSERT(environment, return 0);
LocalQmlProfilerRunner::Configuration conf;
if (QmlProjectManager::QmlProjectRunConfiguration *rc1 =
qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration)) {
// This is a "plain" .qmlproject.
conf.executable = rc1->observerPath();
conf.executableArguments = rc1->viewerArguments();
conf.workingDirectory = rc1->workingDirectory();
conf.environment = environment->environment();
} else if (LocalApplicationRunConfiguration *rc2 =
qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
// FIXME: Check.
conf.executable = rc2->executable();
conf.executableArguments = rc2->commandLineArguments();
conf.workingDirectory = rc2->workingDirectory();
conf.environment = environment->environment();
} else {
QTC_CHECK(false);
}
const ProjectExplorer::IDevice::ConstPtr device =
ProjectExplorer::DeviceKitInformation::device(runConfiguration->target()->kit());
QTC_ASSERT(device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE, return 0);
conf.port = sp.analyzerPort;
runner = new LocalQmlProfilerRunner(conf, parent);
}
return runner;
}
//
// QmlProfilerEngine
//
QmlProfilerEngine::QmlProfilerEngine(IAnalyzerTool *tool,
const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
: IAnalyzerEngine(tool, sp, runConfiguration)
, d(new QmlProfilerEnginePrivate(this, sp))
{
d->m_profilerState = 0;
// Only wait 4 seconds for the 'Waiting for connection' on application ouput, then just try to connect
// (application output might be redirected / blocked)
d->m_noDebugOutputTimer.setSingleShot(true);
d->m_noDebugOutputTimer.setInterval(4000);
connect(&d->m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(processIsRunning()));
d->m_outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
connect(&d->m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
this, SLOT(processIsRunning(quint16)));
connect(&d->m_outputParser, SIGNAL(noOutputMessage()),
this, SLOT(processIsRunning()));
connect(&d->m_outputParser, SIGNAL(errorMessage(QString)),
this, SLOT(wrongSetupMessageBox(QString)));
}
QmlProfilerEngine::~QmlProfilerEngine()
{
if (d->m_profilerState && d->m_profilerState->currentState() == QmlProfilerStateManager::AppRunning)
stop();
delete d;
}
bool QmlProfilerEngine::start()
{
QTC_ASSERT(d->m_profilerState, return false);
if (d->m_runner) {
delete d->m_runner;
d->m_runner = 0;
}
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStarting);
if (QmlProjectManager::QmlProjectRunConfiguration *rc =
qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration())) {
if (rc->observerPath().isEmpty()) {
QmlProjectManager::QmlProjectPlugin::showQmlObserverToolWarning();
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
AnalyzerManager::stopTool();
return false;
}
}
d->m_runner = d->createRunner(runConfiguration(), this);
if (LocalQmlProfilerRunner *qmlRunner = qobject_cast<LocalQmlProfilerRunner *>(d->m_runner)) {
if (!qmlRunner->hasExecutable()) {
showNonmodalWarning(tr("No executable file to launch."));
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
AnalyzerManager::stopTool();
return false;
}
}
if (d->m_runner) {
connect(d->m_runner, SIGNAL(stopped()), this, SLOT(processEnded()));
connect(d->m_runner, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
this, SLOT(logApplicationMessage(QString,Utils::OutputFormat)));
d->m_runner->start();
d->m_noDebugOutputTimer.start();
} else {
emit processRunning(startParameters().analyzerPort);
}
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppRunning);
emit starting(this);
return true;
}
void QmlProfilerEngine::stop()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStopRequested);
break;
}
case QmlProfilerStateManager::AppReadyToStop : {
cancelProcess();
break;
}
case QmlProfilerStateManager::AppDying :
// valid, but no further action is needed
break;
default: {
const QString message = QString::fromLatin1("Unexpected engine stop from state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
}
break;
}
}
void QmlProfilerEngine::processEnded()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
AnalyzerManager::stopTool();
emit finished();
break;
}
case QmlProfilerStateManager::AppStopped :
case QmlProfilerStateManager::AppKilled :
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
break;
default: {
const QString message = QString::fromLatin1("Process died unexpectedly from state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
}
break;
}
}
void QmlProfilerEngine::cancelProcess()
{
QTC_ASSERT(d->m_profilerState, return);
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppReadyToStop : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStopped);
break;
}
case QmlProfilerStateManager::AppRunning : {
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
break;
}
default: {
const QString message = QString::fromLatin1("Unexpected process termination requested with state %1 in %2:%3")
.arg(d->m_profilerState->currentStateAsString(), QString::fromLatin1(__FILE__), QString::number(__LINE__));
qWarning("%s", qPrintable(message));
return;
}
}
if (d->m_runner)
d->m_runner->stop();
emit finished();
}
void QmlProfilerEngine::logApplicationMessage(const QString &msg, Utils::OutputFormat format)
{
emit outputReceived(msg, format);
d->m_outputParser.processOutput(msg);
}
void QmlProfilerEngine::wrongSetupMessageBox(const QString &errorMessage)
{
QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
infoBox->setIcon(QMessageBox::Critical);
infoBox->setWindowTitle(tr("Qt Creator"));
//: %1 is detailed error message
infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
.arg(errorMessage));
infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
infoBox->setDefaultButton(QMessageBox::Ok);
infoBox->setModal(true);
connect(infoBox, SIGNAL(finished(int)),
this, SLOT(wrongSetupMessageBoxFinished(int)));
infoBox->show();
// KILL
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
AnalyzerManager::stopTool();
emit finished();
}
void QmlProfilerEngine::wrongSetupMessageBoxFinished(int button)
{
if (button == QMessageBox::Help) {
Core::HelpManager *helpManager = Core::HelpManager::instance();
helpManager->handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"
"#setting-up-qml-debugging"));
}
}
void QmlProfilerEngine::showNonmodalWarning(const QString &warningMsg)
{
QMessageBox *noExecWarning = new QMessageBox(Core::ICore::mainWindow());
noExecWarning->setIcon(QMessageBox::Warning);
noExecWarning->setWindowTitle(tr("QML Profiler"));
noExecWarning->setText(warningMsg);
noExecWarning->setStandardButtons(QMessageBox::Ok);
noExecWarning->setDefaultButton(QMessageBox::Ok);
noExecWarning->setModal(false);
noExecWarning->show();
}
void QmlProfilerEngine::processIsRunning(quint16 port)
{
d->m_noDebugOutputTimer.stop();
QTC_ASSERT(port == 0
|| port == d->m_runner->debugPort(),
qWarning() << "Port " << port << "from application output does not match"
<< startParameters().connParams.port << "from start parameters.");
if (port > 0)
emit processRunning(port);
else
emit processRunning(d->m_runner->debugPort());
}
////////////////////////////////////////////////////////////////
// Profiler State
void QmlProfilerEngine::registerProfilerStateManager( QmlProfilerStateManager *profilerState )
{
// disconnect old
if (d->m_profilerState)
disconnect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
d->m_profilerState = profilerState;
// connect
if (d->m_profilerState)
connect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
}
void QmlProfilerEngine::profilerStateChanged()
{
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppReadyToStop : {
if (d->m_runner)
cancelProcess();
break;
}
case QmlProfilerStateManager::Idle : {
// When all the profiling is done, delete the profiler runner
// (a new one will be created at start)
d->m_noDebugOutputTimer.stop();
if (d->m_runner) {
delete d->m_runner;
d->m_runner = 0;
}
break;
}
default:
break;
}
}
} // namespace Internal
} // namespace QmlProfiler
<|endoftext|> |
<commit_before>#include "AbstractCameraQueue.hpp"
#include <ros/console.h>
void AbstractCameraQueue::enqueue(std::vector<CameraData> data)
{
for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {
enqueue(*it);
}
}
void AbstractCameraQueue::enqueue(CameraData data)
{
enqueueInternal(data);
if (getSize() > 15) {
ROS_WARN("Camera queue running full. Removing 10 entries");
while (getSize() > 5) {
dequeue();
}
}
}
CameraData AbstractCameraQueue::getInvalidCameraData()
{
CameraData data;
data.valid = false;
return data;
}
std::vector<CameraData> AbstractCameraQueue::getInvalidCameraDataVector()
{
return toVector(getInvalidCameraData());
}
std::vector<CameraData> AbstractCameraQueue::toVector(CameraData data)
{
std::vector<CameraData> result;
result.push_back(data);
return result;
}<commit_msg>Removed autoremoval from camera queue<commit_after>#include "AbstractCameraQueue.hpp"
#include <ros/console.h>
void AbstractCameraQueue::enqueue(std::vector<CameraData> data)
{
for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {
enqueue(*it);
}
}
void AbstractCameraQueue::enqueue(CameraData data)
{
enqueueInternal(data);
if (getSize() > 15) {
ROS_WARN("Camera queue running full. Quadcopter id: %d", data.quadcopterId);
}
}
CameraData AbstractCameraQueue::getInvalidCameraData()
{
CameraData data;
data.valid = false;
return data;
}
std::vector<CameraData> AbstractCameraQueue::getInvalidCameraDataVector()
{
return toVector(getInvalidCameraData());
}
std::vector<CameraData> AbstractCameraQueue::toVector(CameraData data)
{
std::vector<CameraData> result;
result.push_back(data);
return result;
}<|endoftext|> |
<commit_before>#include "Utils/Testing.hpp"
#include "Messaging/MessageQueue.hpp"
using namespace Core;
using namespace Messaging;
using namespace fakeit;
using namespace std::placeholders;
namespace {
class Content : public Core::IEntity {
TYPE_INFO(Content, Core::IEntity, "content")
};
struct EventSink {
virtual Core::IEntity::Unique onRequest(const Content&) = 0;
virtual void onResponse(const Response&) = 0;
virtual void onResponseContent(const Content&) = 0;
virtual void onEvent(const Event&) const = 0;
virtual void onEventContent(const Content&) const = 0;
};
}
TEST_CASE("message queue is routing an event to a generic client", "[MessageQueue]") {
auto content = Content::makeShared();
Mock<EventSink> eventSink;
When(Method(eventSink, onEvent)).Do([=](const Event& event) {
REQUIRE(event.getEventType() == "created");
REQUIRE(event.getResource() == "resource");
REQUIRE(event.getContent() == content.get());
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createGenericClient("clientId");
client->setOnEvent(std::bind(&EventSink::onEvent, &eventSink.get(), _1));
auto event = Event::makeShared("created", "resource", content);
queue->addEvent(event);
queue->idle();
Verify(Method(eventSink, onEvent));
}
TEST_CASE("message queue is routing a response to a generic client", "[MessageQueue]") {
auto requestContent = Content::makeShared();
auto responseContent = Content::makeUnique();
auto responseContentPtr = responseContent.get();
Mock<EventSink> eventSink;
When(Method(eventSink, onRequest)).Do([&](const Content& param) {
REQUIRE(¶m == requestContent.get());
return std::move(responseContent);
});
When(Method(eventSink, onResponse)).Do([=](const Response& response) {
REQUIRE(response.getRequestType() == "get");
REQUIRE(response.getReceiver() == "clientId");
REQUIRE(response.getResource() == "resource");
REQUIRE(&response.getContent() == responseContentPtr);
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createGenericClient("clientId");
client->setOnResponse(std::bind(&EventSink::onResponse, &eventSink.get(), _1));
auto controller = queue->createResourceController("resource");
controller->addOnRequest<Content>("get", std::bind(&EventSink::onRequest, &eventSink.get(), _1));
client->sendRequest("get", "resource", requestContent);
queue->idle();
Verify(Method(eventSink, onRequest));
Verify(Method(eventSink, onResponse));
}
TEST_CASE("message queue is routing an event to a resource client", "[MessageQueue]") {
auto content = Content::makeShared();
Mock<EventSink> eventSink;
When(Method(eventSink, onEventContent)).Do([=](const Content& param) {
REQUIRE(¶m == content.get());
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createResourceClient("clientId", "resource");
client->addOnEvent<Content>("created", std::bind(&EventSink::onEventContent, &eventSink.get(), _1));
auto event = Event::makeShared("created", "resource", content);
queue->addEvent(event);
queue->idle();
Verify(Method(eventSink, onEventContent));
}
TEST_CASE("message queue is routing a response to a resource client", "[MessageQueue]") {
auto requestContent = Content::makeShared();
auto responseContent = Content::makeUnique();
auto responseContentPtr = responseContent.get();
Mock<EventSink> eventSink;
When(Method(eventSink, onRequest)).Do([&](const Content& param) {
REQUIRE(¶m == requestContent.get());
return std::move(responseContent);
});
When(Method(eventSink, onResponseContent)).Do([=](const Content& param) {
REQUIRE(¶m == responseContentPtr);
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createResourceClient("clientId", "resource");
client->addOnResponse<Content>("get", std::bind(&EventSink::onResponseContent, &eventSink.get(), _1));
auto controller = queue->createResourceController("resource");
controller->addOnRequest<Content>("get", std::bind(&EventSink::onRequest, &eventSink.get(), _1));
client->sendRequest("get", requestContent);
queue->idle();
Verify(Method(eventSink, onRequest));
Verify(Method(eventSink, onResponseContent));
}
<commit_msg>Improviing message queue unit tests<commit_after>#include "Utils/Testing.hpp"
#include "Messaging/MessageQueue.hpp"
using namespace Core;
using namespace Messaging;
using namespace fakeit;
using namespace std::placeholders;
namespace {
class Content : public Core::IEntity {
TYPE_INFO(Content, Core::IEntity, "content")
};
struct EventSink {
virtual Core::IEntity::Unique onRequest(const Content&) = 0;
virtual void onResponse(const Response&) = 0;
virtual void onResponseContent(const Content&) = 0;
virtual void onResponseStatus(const Status&) = 0;
virtual void onEvent(const Event&) const = 0;
virtual void onEventContent(const Content&) const = 0;
};
}
TEST_CASE("message queue is routing an event to a generic client", "[MessageQueue]") {
auto content = Content::makeShared();
Mock<EventSink> eventSink;
When(Method(eventSink, onEvent)).Do([=](const Event& event) {
REQUIRE(event.getEventType() == "created");
REQUIRE(event.getResource() == "resource");
REQUIRE(event.getContent() == content.get());
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createGenericClient("clientId");
client->setOnEvent(std::bind(&EventSink::onEvent, &eventSink.get(), _1));
auto event = Event::makeShared("created", "resource", content);
queue->addEvent(event);
queue->idle();
Verify(Method(eventSink, onEvent));
}
TEST_CASE("message queue is routing a response to a generic client", "[MessageQueue]") {
auto requestContent = Content::makeShared();
auto responseContent = Content::makeUnique();
auto responseContentPtr = responseContent.get();
Mock<EventSink> eventSink;
When(Method(eventSink, onRequest)).Do([&](const Content& param) {
REQUIRE(¶m == requestContent.get());
return std::move(responseContent);
});
When(Method(eventSink, onResponse)).Do([=](const Response& response) {
REQUIRE(response.getRequestType() == "get");
REQUIRE(response.getReceiver() == "clientId");
REQUIRE(response.getResource() == "resource");
REQUIRE(&response.getContent() == responseContentPtr);
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createGenericClient("clientId");
client->setOnResponse(std::bind(&EventSink::onResponse, &eventSink.get(), _1));
auto controller = queue->createResourceController("resource");
controller->addOnRequest<Content>("get", std::bind(&EventSink::onRequest, &eventSink.get(), _1));
client->sendRequest("get", "resource", requestContent);
queue->idle();
Verify(Method(eventSink, onRequest));
Verify(Method(eventSink, onResponse));
}
TEST_CASE("message queue is routing an event to a resource client", "[MessageQueue]") {
auto content = Content::makeShared();
Mock<EventSink> eventSink;
When(Method(eventSink, onEventContent)).Do([=](const Content& param) {
REQUIRE(¶m == content.get());
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createResourceClient("clientId", "resource");
client->addOnEvent<Content>("created", std::bind(&EventSink::onEventContent, &eventSink.get(), _1));
auto event = Event::makeShared("created", "resource", content);
queue->addEvent(event);
queue->idle();
Verify(Method(eventSink, onEventContent));
}
TEST_CASE("message queue is routing a response to a resource client", "[MessageQueue]") {
auto requestContent = Content::makeShared();
auto responseContent = Content::makeUnique();
auto responseContentPtr = responseContent.get();
Mock<EventSink> eventSink;
When(Method(eventSink, onRequest)).Do([&](const Content& param) {
REQUIRE(¶m == requestContent.get());
return std::move(responseContent);
});
When(Method(eventSink, onResponseContent)).Do([=](const Content& param) {
REQUIRE(¶m == responseContentPtr);
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createResourceClient("clientId", "resource");
client->addOnResponse<Content>("get", std::bind(&EventSink::onResponseContent, &eventSink.get(), _1));
auto controller = queue->createResourceController("resource");
controller->addOnRequest<Content>("get", std::bind(&EventSink::onRequest, &eventSink.get(), _1));
client->sendRequest("get", requestContent);
queue->idle();
Verify(Method(eventSink, onRequest));
Verify(Method(eventSink, onResponseContent));
}
TEST_CASE("message queue is failing to route a request in there is no controller to handle it", "[MessageQueue]") {
auto requestContent = Content::makeShared();
Mock<EventSink> eventSink;
When(Method(eventSink, onResponseStatus)).Do([=](const Status& status) {
REQUIRE(status.getStatusCode() == StatusCode::NotFound);
return Status::OK();
});
Mock<ILogger> loggerInstanse;
When(Dtor(loggerInstanse)).Do([](){});
Fake(Method(loggerInstanse, message));
Fake(Method(loggerInstanse, error));
ILogger::Shared logger(&loggerInstanse.get());
auto queue = MessageQueue::makeUnique(logger);
auto client = queue->createResourceClient("clientId", "resource");
client->addOnResponse<Status>("get", std::bind(&EventSink::onResponseStatus, &eventSink.get(), _1));
client->sendRequest("get", requestContent);
queue->idle();
Verify(Method(eventSink, onResponseStatus));
}
<|endoftext|> |
<commit_before>// RUN: clang-cc -fsyntax-only -verify %s
struct add_pointer {
template<typename T>
struct apply {
typedef T* type;
};
};
struct add_reference {
template<typename T>
struct apply {
typedef T& type; // expected-error{{cannot form a reference to 'void'}}
};
};
template<typename MetaFun, typename T>
struct apply1 {
typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}}
};
int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}
void test() {
apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
// FIXME: expected-error{{unexpected type name 'type': expected expression}}
}
<commit_msg>Improve the dependent nested-name-specifier test a bit<commit_after>// RUN: clang-cc -fsyntax-only -verify %s
struct add_pointer {
template<typename T>
struct apply {
typedef T* type;
};
};
struct add_reference {
template<typename T>
struct apply {
typedef T& type; // expected-error{{cannot form a reference to 'void'}}
};
};
struct bogus {
struct apply {
typedef int type;
};
};
template<typename MetaFun, typename T>
struct apply1 {
typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}} \
// expected-error{{'apply' following the 'template' keyword does not refer to a template}} \
// FIXME: expected-error{{type 'MetaFun::template apply<int>' cannot be used prior to '::' because it has no members}}
};
int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}
void test() {
apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
// FIXME: expected-error{{unexpected type name 'type': expected expression}}
apply1<bogus, int>::type t2; // expected-note{{in instantiation of template class 'struct apply1<struct bogus, int>' requested here}} \
// FIXME: expected-error{{unexpected type name 'type': expected expression}}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <string>
#include <vector>
#include <testHelpers.hpp>
#include <cmath>
using std::string;
using std::vector;
using af::dim4;
template<typename T>
class Bilateral : public ::testing::Test
{
public:
virtual void SetUp() {}
};
// create a list of types to be tested
// FIXME: since af_load_image returns only f32 type arrays
// only float, double, int data types test are enabledpassing
// Note: compareArraysRMSD is handling upcasting while working
// with two different type of types
//
//typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes;
typedef ::testing::Types<float, double, int> TestTypes;
// register the type list
TYPED_TEST_CASE(Bilateral, TestTypes);
TYPED_TEST(Bilateral, InvalidArgs)
{
vector<TypeParam> in(100,1);
af_array inArray = 0;
af_array outArray = 0;
// check for gray scale bilateral
af::dim4 dims(5,5,2,2);
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(),
dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type));
ASSERT_EQ(AF_ERR_ARG, af_bilateral(&outArray, inArray, 0.12f, 0.34f, false));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
// check for color image bilateral
dims = af::dim4(100,1,1,1);
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(),
dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type));
ASSERT_EQ(AF_ERR_ARG, af_bilateral(&outArray, inArray, 0.12f, 0.34f, true));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
}
template<typename T, bool isColor>
void bilateralTest(string pTestFile)
{
vector<dim4> inDims;
vector<string> inFiles;
vector<dim_type> outSizes;
vector<string> outFiles;
readImageTests(pTestFile, inDims, inFiles, outSizes, outFiles);
size_t testCount = inDims.size();
for (size_t testId=0; testId<testCount; ++testId) {
af_array inArray = 0;
af_array outArray = 0;
af_array goldArray= 0;
dim_type nElems = 0;
inFiles[testId].insert(0,string(TEST_DIR"/bilateral/"));
outFiles[testId].insert(0,string(TEST_DIR"/bilateral/"));
ASSERT_EQ(AF_SUCCESS, af_load_image(&inArray, inFiles[testId].c_str(), isColor));
ASSERT_EQ(AF_SUCCESS, af_load_image(&goldArray, outFiles[testId].c_str(), isColor));
ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems, goldArray));
ASSERT_EQ(AF_SUCCESS, af_bilateral(&outArray, inArray, 2.25f, 25.56f, isColor));
T * outData = new T[nElems];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
T * goldData= new T[nElems];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)goldData, goldArray));
ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.02f));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(goldArray));
}
}
TYPED_TEST(Bilateral, Grayscale)
{
bilateralTest<TypeParam, false>(string(TEST_DIR"/bilateral/gray.test"));
}
TYPED_TEST(Bilateral, Color)
{
bilateralTest<TypeParam, true>(string(TEST_DIR"/bilateral/color.test"));
}
<commit_msg>Disable unit test for int type in bilateral<commit_after>#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <string>
#include <vector>
#include <testHelpers.hpp>
#include <cmath>
using std::string;
using std::vector;
using af::dim4;
template<typename T>
class Bilateral : public ::testing::Test
{
public:
virtual void SetUp() {}
};
// create a list of types to be tested
// FIXME: since af_load_image returns only f32 type arrays
// only float, double data types test are enabled & passing
// Note: compareArraysRMSD is handling upcasting while working
// with two different type of types
//
//typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes;
typedef ::testing::Types<float, double> TestTypes;
// register the type list
TYPED_TEST_CASE(Bilateral, TestTypes);
TYPED_TEST(Bilateral, InvalidArgs)
{
vector<TypeParam> in(100,1);
af_array inArray = 0;
af_array outArray = 0;
// check for gray scale bilateral
af::dim4 dims(5,5,2,2);
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(),
dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type));
ASSERT_EQ(AF_ERR_ARG, af_bilateral(&outArray, inArray, 0.12f, 0.34f, false));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
// check for color image bilateral
dims = af::dim4(100,1,1,1);
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(),
dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type));
ASSERT_EQ(AF_ERR_ARG, af_bilateral(&outArray, inArray, 0.12f, 0.34f, true));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
}
template<typename T, bool isColor>
void bilateralTest(string pTestFile)
{
vector<dim4> inDims;
vector<string> inFiles;
vector<dim_type> outSizes;
vector<string> outFiles;
readImageTests(pTestFile, inDims, inFiles, outSizes, outFiles);
size_t testCount = inDims.size();
for (size_t testId=0; testId<testCount; ++testId) {
af_array inArray = 0;
af_array outArray = 0;
af_array goldArray= 0;
dim_type nElems = 0;
inFiles[testId].insert(0,string(TEST_DIR"/bilateral/"));
outFiles[testId].insert(0,string(TEST_DIR"/bilateral/"));
ASSERT_EQ(AF_SUCCESS, af_load_image(&inArray, inFiles[testId].c_str(), isColor));
ASSERT_EQ(AF_SUCCESS, af_load_image(&goldArray, outFiles[testId].c_str(), isColor));
ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems, goldArray));
ASSERT_EQ(AF_SUCCESS, af_bilateral(&outArray, inArray, 2.25f, 25.56f, isColor));
T * outData = new T[nElems];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
T * goldData= new T[nElems];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)goldData, goldArray));
ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.02f));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray));
ASSERT_EQ(AF_SUCCESS, af_destroy_array(goldArray));
}
}
TYPED_TEST(Bilateral, Grayscale)
{
bilateralTest<TypeParam, false>(string(TEST_DIR"/bilateral/gray.test"));
}
TYPED_TEST(Bilateral, Color)
{
bilateralTest<TypeParam, true>(string(TEST_DIR"/bilateral/color.test"));
}
<|endoftext|> |
<commit_before>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "test/cctest/cctest.h"
#include "src/api.h"
#include "src/debug.h"
#include "src/execution.h"
#include "src/factory.h"
#include "src/global-handles.h"
#include "src/macro-assembler.h"
#include "src/objects.h"
using namespace v8::internal;
namespace {
TEST(VectorStructure) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
// Empty vectors are the empty fixed array.
Handle<TypeFeedbackVector> vector = factory->NewTypeFeedbackVector(0, 0);
CHECK(Handle<FixedArray>::cast(vector)
.is_identical_to(factory->empty_fixed_array()));
// Which can nonetheless be queried.
CHECK_EQ(0, vector->ic_with_type_info_count());
CHECK_EQ(0, vector->ic_generic_count());
CHECK_EQ(0, vector->Slots());
CHECK_EQ(0, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(1, 0);
CHECK_EQ(1, vector->Slots());
CHECK_EQ(0, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(0, 1);
CHECK_EQ(0, vector->Slots());
CHECK_EQ(1, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(3, 5);
CHECK_EQ(3, vector->Slots());
CHECK_EQ(5, vector->ICSlots());
int metadata_length = vector->ic_metadata_length();
if (!FLAG_vector_ics) {
CHECK_EQ(0, metadata_length);
} else {
CHECK(metadata_length > 0);
}
int index = vector->GetIndex(FeedbackVectorSlot(0));
CHECK_EQ(TypeFeedbackVector::kReservedIndexCount + metadata_length, index);
CHECK(FeedbackVectorSlot(0) == vector->ToSlot(index));
index = vector->GetIndex(FeedbackVectorICSlot(0));
CHECK_EQ(index,
TypeFeedbackVector::kReservedIndexCount + metadata_length + 3);
CHECK(FeedbackVectorICSlot(0) == vector->ToICSlot(index));
CHECK_EQ(TypeFeedbackVector::kReservedIndexCount + metadata_length + 3 + 5,
vector->length());
}
// IC slots need an encoding to recognize what is in there.
TEST(VectorICMetadata) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
if (!FLAG_vector_ics) {
// If FLAG_vector_ics is false, we only store CALL_ICs in the vector, so
// there is no need for metadata to describe the slots.
return;
}
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Handle<TypeFeedbackVector> vector =
factory->NewTypeFeedbackVector(10, 3 * 10);
CHECK_EQ(10, vector->Slots());
CHECK_EQ(3 * 10, vector->ICSlots());
// Set metadata.
for (int i = 0; i < 30; i++) {
Code::Kind kind;
if (i % 3 == 0)
kind = Code::CALL_IC;
else if (i % 3 == 1)
kind = Code::LOAD_IC;
else if (i % 3 == 2)
kind = Code::KEYED_LOAD_IC;
vector->SetKind(FeedbackVectorICSlot(i), kind);
}
// Meanwhile set some feedback values and type feedback values to
// verify the data structure remains intact.
vector->change_ic_with_type_info_count(100);
vector->change_ic_generic_count(3333);
vector->Set(FeedbackVectorSlot(0), *vector);
// Verify the metadata remains the same.
for (int i = 0; i < 30; i++) {
Code::Kind kind = vector->GetKind(FeedbackVectorICSlot(i));
if (i % 3 == 0) {
CHECK_EQ(Code::CALL_IC, kind);
} else if (i % 3 == 1) {
CHECK_EQ(Code::LOAD_IC, kind);
} else {
CHECK_EQ(Code::KEYED_LOAD_IC, kind);
}
}
}
TEST(VectorSlotClearing) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
// We only test clearing FeedbackVectorSlots, not FeedbackVectorICSlots.
// The reason is that FeedbackVectorICSlots need a full code environment
// to fully test (See VectorICProfilerStatistics test below).
Handle<TypeFeedbackVector> vector = factory->NewTypeFeedbackVector(5, 0);
// Fill with information
vector->Set(FeedbackVectorSlot(0), Smi::FromInt(1));
vector->Set(FeedbackVectorSlot(1), *factory->fixed_array_map());
Handle<AllocationSite> site = factory->NewAllocationSite();
vector->Set(FeedbackVectorSlot(2), *site);
vector->ClearSlots(NULL);
// The feedback vector slots are cleared. AllocationSites are granted
// an exemption from clearing, as are smis.
CHECK_EQ(Smi::FromInt(1), vector->Get(FeedbackVectorSlot(0)));
CHECK_EQ(*TypeFeedbackVector::UninitializedSentinel(isolate),
vector->Get(FeedbackVectorSlot(1)));
CHECK(vector->Get(FeedbackVectorSlot(2))->IsAllocationSite());
}
TEST(VectorICProfilerStatistics) {
if (i::FLAG_always_opt) return;
CcTest::InitializeVM();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Heap* heap = isolate->heap();
// Make sure function f has a call that uses a type feedback slot.
CompileRun(
"function fun() {};"
"function f(a) { a(); } f(fun);");
Handle<JSFunction> f = v8::Utils::OpenHandle(
*v8::Handle<v8::Function>::Cast(CcTest::global()->Get(v8_str("f"))));
// There should be one IC.
Code* code = f->shared()->code();
TypeFeedbackInfo* feedback_info =
TypeFeedbackInfo::cast(code->type_feedback_info());
CHECK_EQ(1, feedback_info->ic_total_count());
CHECK_EQ(0, feedback_info->ic_with_type_info_count());
CHECK_EQ(0, feedback_info->ic_generic_count());
TypeFeedbackVector* feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
// Now send the information generic.
CompileRun("f(Object);");
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(0, feedback_vector->ic_with_type_info_count());
CHECK_EQ(1, feedback_vector->ic_generic_count());
// A collection will make the site uninitialized again.
heap->CollectAllGarbage(i::Heap::kNoGCFlags);
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(0, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
// The Array function is special. A call to array remains monomorphic
// and isn't cleared by gc because an AllocationSite is being held.
CompileRun("f(Array);");
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
int ic_slot = FLAG_vector_ics ? 1 : 0;
CHECK(
feedback_vector->Get(FeedbackVectorICSlot(ic_slot))->IsAllocationSite());
heap->CollectAllGarbage(i::Heap::kNoGCFlags);
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
CHECK(
feedback_vector->Get(FeedbackVectorICSlot(ic_slot))->IsAllocationSite());
}
}
<commit_msg>Fix for the cctest compilation issue on Mac after r24911.<commit_after>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "test/cctest/cctest.h"
#include "src/api.h"
#include "src/debug.h"
#include "src/execution.h"
#include "src/factory.h"
#include "src/global-handles.h"
#include "src/macro-assembler.h"
#include "src/objects.h"
using namespace v8::internal;
namespace {
TEST(VectorStructure) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
// Empty vectors are the empty fixed array.
Handle<TypeFeedbackVector> vector = factory->NewTypeFeedbackVector(0, 0);
CHECK(Handle<FixedArray>::cast(vector)
.is_identical_to(factory->empty_fixed_array()));
// Which can nonetheless be queried.
CHECK_EQ(0, vector->ic_with_type_info_count());
CHECK_EQ(0, vector->ic_generic_count());
CHECK_EQ(0, vector->Slots());
CHECK_EQ(0, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(1, 0);
CHECK_EQ(1, vector->Slots());
CHECK_EQ(0, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(0, 1);
CHECK_EQ(0, vector->Slots());
CHECK_EQ(1, vector->ICSlots());
vector = factory->NewTypeFeedbackVector(3, 5);
CHECK_EQ(3, vector->Slots());
CHECK_EQ(5, vector->ICSlots());
int metadata_length = vector->ic_metadata_length();
if (!FLAG_vector_ics) {
CHECK_EQ(0, metadata_length);
} else {
CHECK(metadata_length > 0);
}
int index = vector->GetIndex(FeedbackVectorSlot(0));
CHECK_EQ(TypeFeedbackVector::kReservedIndexCount + metadata_length, index);
CHECK(FeedbackVectorSlot(0) == vector->ToSlot(index));
index = vector->GetIndex(FeedbackVectorICSlot(0));
CHECK_EQ(index,
TypeFeedbackVector::kReservedIndexCount + metadata_length + 3);
CHECK(FeedbackVectorICSlot(0) == vector->ToICSlot(index));
CHECK_EQ(TypeFeedbackVector::kReservedIndexCount + metadata_length + 3 + 5,
vector->length());
}
// IC slots need an encoding to recognize what is in there.
TEST(VectorICMetadata) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
if (!FLAG_vector_ics) {
// If FLAG_vector_ics is false, we only store CALL_ICs in the vector, so
// there is no need for metadata to describe the slots.
return;
}
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Handle<TypeFeedbackVector> vector =
factory->NewTypeFeedbackVector(10, 3 * 10);
CHECK_EQ(10, vector->Slots());
CHECK_EQ(3 * 10, vector->ICSlots());
// Set metadata.
for (int i = 0; i < 30; i++) {
Code::Kind kind;
if (i % 3 == 0)
kind = Code::CALL_IC;
else if (i % 3 == 1)
kind = Code::LOAD_IC;
else
kind = Code::KEYED_LOAD_IC;
vector->SetKind(FeedbackVectorICSlot(i), kind);
}
// Meanwhile set some feedback values and type feedback values to
// verify the data structure remains intact.
vector->change_ic_with_type_info_count(100);
vector->change_ic_generic_count(3333);
vector->Set(FeedbackVectorSlot(0), *vector);
// Verify the metadata remains the same.
for (int i = 0; i < 30; i++) {
Code::Kind kind = vector->GetKind(FeedbackVectorICSlot(i));
if (i % 3 == 0) {
CHECK_EQ(Code::CALL_IC, kind);
} else if (i % 3 == 1) {
CHECK_EQ(Code::LOAD_IC, kind);
} else {
CHECK_EQ(Code::KEYED_LOAD_IC, kind);
}
}
}
TEST(VectorSlotClearing) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
// We only test clearing FeedbackVectorSlots, not FeedbackVectorICSlots.
// The reason is that FeedbackVectorICSlots need a full code environment
// to fully test (See VectorICProfilerStatistics test below).
Handle<TypeFeedbackVector> vector = factory->NewTypeFeedbackVector(5, 0);
// Fill with information
vector->Set(FeedbackVectorSlot(0), Smi::FromInt(1));
vector->Set(FeedbackVectorSlot(1), *factory->fixed_array_map());
Handle<AllocationSite> site = factory->NewAllocationSite();
vector->Set(FeedbackVectorSlot(2), *site);
vector->ClearSlots(NULL);
// The feedback vector slots are cleared. AllocationSites are granted
// an exemption from clearing, as are smis.
CHECK_EQ(Smi::FromInt(1), vector->Get(FeedbackVectorSlot(0)));
CHECK_EQ(*TypeFeedbackVector::UninitializedSentinel(isolate),
vector->Get(FeedbackVectorSlot(1)));
CHECK(vector->Get(FeedbackVectorSlot(2))->IsAllocationSite());
}
TEST(VectorICProfilerStatistics) {
if (i::FLAG_always_opt) return;
CcTest::InitializeVM();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Isolate* isolate = CcTest::i_isolate();
Heap* heap = isolate->heap();
// Make sure function f has a call that uses a type feedback slot.
CompileRun(
"function fun() {};"
"function f(a) { a(); } f(fun);");
Handle<JSFunction> f = v8::Utils::OpenHandle(
*v8::Handle<v8::Function>::Cast(CcTest::global()->Get(v8_str("f"))));
// There should be one IC.
Code* code = f->shared()->code();
TypeFeedbackInfo* feedback_info =
TypeFeedbackInfo::cast(code->type_feedback_info());
CHECK_EQ(1, feedback_info->ic_total_count());
CHECK_EQ(0, feedback_info->ic_with_type_info_count());
CHECK_EQ(0, feedback_info->ic_generic_count());
TypeFeedbackVector* feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
// Now send the information generic.
CompileRun("f(Object);");
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(0, feedback_vector->ic_with_type_info_count());
CHECK_EQ(1, feedback_vector->ic_generic_count());
// A collection will make the site uninitialized again.
heap->CollectAllGarbage(i::Heap::kNoGCFlags);
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(0, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
// The Array function is special. A call to array remains monomorphic
// and isn't cleared by gc because an AllocationSite is being held.
CompileRun("f(Array);");
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
int ic_slot = FLAG_vector_ics ? 1 : 0;
CHECK(
feedback_vector->Get(FeedbackVectorICSlot(ic_slot))->IsAllocationSite());
heap->CollectAllGarbage(i::Heap::kNoGCFlags);
feedback_vector = f->shared()->feedback_vector();
CHECK_EQ(1, feedback_vector->ic_with_type_info_count());
CHECK_EQ(0, feedback_vector->ic_generic_count());
CHECK(
feedback_vector->Get(FeedbackVectorICSlot(ic_slot))->IsAllocationSite());
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChart.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 "vtkChart.h"
#include "vtkAxis.h"
#include "vtkBrush.h"
#include "vtkTransform2D.h"
#include "vtkContextMouseEvent.h"
#include "vtkAnnotationLink.h"
#include "vtkContextScene.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkChart::MouseActions::MouseActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::MIDDLE_BUTTON;
this->Data[2] = vtkContextMouseEvent::RIGHT_BUTTON;
this->Data[3] = -1;
}
//-----------------------------------------------------------------------------
vtkChart::MouseClickActions::MouseClickActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::RIGHT_BUTTON;
}
//-----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkChart, AnnotationLink, vtkAnnotationLink);
//-----------------------------------------------------------------------------
vtkChart::vtkChart()
{
this->Geometry[0] = 0;
this->Geometry[1] = 0;
this->Point1[0] = 0;
this->Point1[1] = 0;
this->Point2[0] = 0;
this->Point2[1] = 0;
this->Size.Set(0, 0, 0, 0);
this->ShowLegend = false;
this->TitleProperties = vtkTextProperty::New();
this->TitleProperties->SetJustificationToCentered();
this->TitleProperties->SetColor(0.0, 0.0, 0.0);
this->TitleProperties->SetFontSize(12);
this->TitleProperties->SetFontFamilyToArial();
this->AnnotationLink = NULL;
this->LayoutStrategy = vtkChart::FILL_SCENE;
this->RenderEmpty = false;
this->BackgroundBrush = vtkSmartPointer<vtkBrush>::New();
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
this->SelectionMode = vtkContextScene::SELECTION_NONE;
this->SelectionMethod = vtkChart::SELECTION_ROWS;
}
//-----------------------------------------------------------------------------
vtkChart::~vtkChart()
{
for(int i=0; i < 4; i++)
{
if(this->GetAxis(i))
{
this->GetAxis(i)->RemoveObservers(vtkChart::UpdateRange);
}
}
this->TitleProperties->Delete();
if (this->AnnotationLink)
{
this->AnnotationLink->Delete();
}
}
//-----------------------------------------------------------------------------
vtkPlot * vtkChart::AddPlot(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::AddPlot(vtkPlot*)
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlot(vtkIdType)
{
return false;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlotInstance(vtkPlot* plot)
{
if (plot)
{
vtkIdType numberOfPlots = this->GetNumberOfPlots();
for (vtkIdType i = 0; i < numberOfPlots; ++i)
{
if (this->GetPlot(i) == plot)
{
return this->RemovePlot(i);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
void vtkChart::ClearPlots()
{
}
//-----------------------------------------------------------------------------
vtkPlot* vtkChart::GetPlot(vtkIdType)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfPlots()
{
return 0;
}
//-----------------------------------------------------------------------------
vtkAxis* vtkChart::GetAxis(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfAxes()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::RecalculateBounds()
{
return;
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMethod(int method)
{
if (method == this->SelectionMethod)
{
return;
}
this->SelectionMethod = method;
this->Modified();
}
//-----------------------------------------------------------------------------
int vtkChart::GetSelectionMethod()
{
return this->SelectionMethod;
}
//-----------------------------------------------------------------------------
void vtkChart::SetShowLegend(bool visible)
{
if (this->ShowLegend != visible)
{
this->ShowLegend = visible;
this->Modified();
}
}
//-----------------------------------------------------------------------------
bool vtkChart::GetShowLegend()
{
return this->ShowLegend;
}
vtkChartLegend * vtkChart::GetLegend()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::SetTitle(const vtkStdString &title)
{
if (this->Title != title)
{
this->Title = title;
this->Modified();
}
}
//-----------------------------------------------------------------------------
vtkStdString vtkChart::GetTitle()
{
return this->Title;
}
//-----------------------------------------------------------------------------
bool vtkChart::CalculatePlotTransform(vtkAxis *x, vtkAxis *y,
vtkTransform2D *transform)
{
if (!x || !y || !transform)
{
vtkWarningMacro("Called with null arguments.");
return false;
}
vtkVector2d scale(x->GetMaximum() - x->GetMinimum(),
y->GetMaximum() - y->GetMinimum());
vtkVector2d factor(1.0, 1.0);
for (int i = 0; i < 2; ++i)
{
if (fabs(log10(scale[i])) > 10)
{
// We need to scale the transform to show all data, do this in blocks.
factor[i] = pow(10, floor(log10(scale[i]) / 10.0) * -10.0);
scale[i] = scale[i] * factor[i];
}
}
x->SetScalingFactor(factor[0]);
y->SetScalingFactor(factor[1]);
// Get the scale for the plot area from the x and y axes
float *min = x->GetPoint1();
float *max = x->GetPoint2();
if (fabs(max[0] - min[0]) == 0.0f)
{
return false;
}
float xScale = scale[0] / (max[0] - min[0]);
// Now the y axis
min = y->GetPoint1();
max = y->GetPoint2();
if (fabs(max[1] - min[1]) == 0.0f)
{
return false;
}
float yScale = scale[1] / (max[1] - min[1]);
transform->Identity();
transform->Translate(this->Point1[0], this->Point1[1]);
// Get the scale for the plot area from the x and y axes
transform->Scale(1.0 / xScale, 1.0 / yScale);
transform->Translate(-x->GetMinimum() * factor[0],
-y->GetMinimum() * factor[1]);
return true;
}
//-----------------------------------------------------------------------------
void vtkChart::SetBottomBorder(int border)
{
this->Point1[1] = border >= 0 ? border : 0;
this->Point1[1] += static_cast<int>(this->Size.GetY());
}
//-----------------------------------------------------------------------------
void vtkChart::SetTopBorder(int border)
{
this->Point2[1] = border >=0 ?
this->Geometry[1] - border :
this->Geometry[1];
this->Point2[1] += static_cast<int>(this->Size.GetY());
}
//-----------------------------------------------------------------------------
void vtkChart::SetLeftBorder(int border)
{
this->Point1[0] = border >= 0 ? border : 0;
this->Point1[0] += static_cast<int>(this->Size.GetX());
}
//-----------------------------------------------------------------------------
void vtkChart::SetRightBorder(int border)
{
this->Point2[0] = border >=0 ?
this->Geometry[0] - border :
this->Geometry[0];
this->Point2[0] += static_cast<int>(this->Size.GetX());
}
//-----------------------------------------------------------------------------
void vtkChart::SetBorders(int left, int bottom, int right, int top)
{
this->SetLeftBorder(left);
this->SetRightBorder(right);
this->SetTopBorder(top);
this->SetBottomBorder(bottom);
}
void vtkChart::SetSize(const vtkRectf &rect)
{
this->Size = rect;
this->Geometry[0] = static_cast<int>(rect.GetWidth());
this->Geometry[1] = static_cast<int>(rect.GetHeight());
}
vtkRectf vtkChart::GetSize()
{
return this->Size;
}
void vtkChart::SetActionToButton(int action, int button)
{
if (action < -1 || action >= MouseActions::MaxAction)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action] = button;
for (int i = 0; i < MouseActions::MaxAction; ++i)
{
if (this->Actions[i] == button && i != action)
{
this->Actions[i] = -1;
}
}
}
int vtkChart::GetActionToButton(int action)
{
return this->Actions[action];
}
void vtkChart::SetClickActionToButton(int action, int button)
{
if (action < vtkChart::SELECT || action > vtkChart::NOTIFY)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action - 2] = button;
}
int vtkChart::GetClickActionToButton(int action)
{
return this->Actions[action - 2];
}
//-----------------------------------------------------------------------------
void vtkChart::SetBackgroundBrush(vtkBrush *brush)
{
if(brush == NULL)
{
// set to transparent white if brush is null
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
}
else
{
this->BackgroundBrush = brush;
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkBrush* vtkChart::GetBackgroundBrush()
{
return this->BackgroundBrush.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkChart::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
// Print out the chart's geometry if it has been set
os << indent << "Point1: " << this->Point1[0] << "\t" << this->Point1[1]
<< endl;
os << indent << "Point2: " << this->Point2[0] << "\t" << this->Point2[1]
<< endl;
os << indent << "Width: " << this->Geometry[0] << endl
<< indent << "Height: " << this->Geometry[1] << endl;
os << indent << "SelectionMode: " << this->SelectionMode << endl;
}
//-----------------------------------------------------------------------------
void vtkChart::AttachAxisRangeListener(vtkAxis* axis)
{
axis->AddObserver(vtkChart::UpdateRange, this, &vtkChart::AxisRangeForwarderCallback);
}
//-----------------------------------------------------------------------------
void vtkChart::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*)
{
double fullAxisRange[8];
for(int i=0; i < 4; i++)
{
this->GetAxis(i)->GetRange(&fullAxisRange[i*2]);
}
this->InvokeEvent(vtkChart::UpdateRange, fullAxisRange);
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMode(int selMode)
{
if (this->SelectionMode == selMode ||
selMode < vtkContextScene::SELECTION_NONE ||
selMode > vtkContextScene::SELECTION_TOGGLE)
{
return;
}
this->SelectionMode = selMode;
this->Modified();
}
<commit_msg>COMP: Fixed ambiguous overload seen on Windows<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChart.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 "vtkChart.h"
#include "vtkAxis.h"
#include "vtkBrush.h"
#include "vtkTransform2D.h"
#include "vtkContextMouseEvent.h"
#include "vtkAnnotationLink.h"
#include "vtkContextScene.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkChart::MouseActions::MouseActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::MIDDLE_BUTTON;
this->Data[2] = vtkContextMouseEvent::RIGHT_BUTTON;
this->Data[3] = -1;
}
//-----------------------------------------------------------------------------
vtkChart::MouseClickActions::MouseClickActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::RIGHT_BUTTON;
}
//-----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkChart, AnnotationLink, vtkAnnotationLink);
//-----------------------------------------------------------------------------
vtkChart::vtkChart()
{
this->Geometry[0] = 0;
this->Geometry[1] = 0;
this->Point1[0] = 0;
this->Point1[1] = 0;
this->Point2[0] = 0;
this->Point2[1] = 0;
this->Size.Set(0, 0, 0, 0);
this->ShowLegend = false;
this->TitleProperties = vtkTextProperty::New();
this->TitleProperties->SetJustificationToCentered();
this->TitleProperties->SetColor(0.0, 0.0, 0.0);
this->TitleProperties->SetFontSize(12);
this->TitleProperties->SetFontFamilyToArial();
this->AnnotationLink = NULL;
this->LayoutStrategy = vtkChart::FILL_SCENE;
this->RenderEmpty = false;
this->BackgroundBrush = vtkSmartPointer<vtkBrush>::New();
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
this->SelectionMode = vtkContextScene::SELECTION_NONE;
this->SelectionMethod = vtkChart::SELECTION_ROWS;
}
//-----------------------------------------------------------------------------
vtkChart::~vtkChart()
{
for(int i=0; i < 4; i++)
{
if(this->GetAxis(i))
{
this->GetAxis(i)->RemoveObservers(vtkChart::UpdateRange);
}
}
this->TitleProperties->Delete();
if (this->AnnotationLink)
{
this->AnnotationLink->Delete();
}
}
//-----------------------------------------------------------------------------
vtkPlot * vtkChart::AddPlot(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::AddPlot(vtkPlot*)
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlot(vtkIdType)
{
return false;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlotInstance(vtkPlot* plot)
{
if (plot)
{
vtkIdType numberOfPlots = this->GetNumberOfPlots();
for (vtkIdType i = 0; i < numberOfPlots; ++i)
{
if (this->GetPlot(i) == plot)
{
return this->RemovePlot(i);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
void vtkChart::ClearPlots()
{
}
//-----------------------------------------------------------------------------
vtkPlot* vtkChart::GetPlot(vtkIdType)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfPlots()
{
return 0;
}
//-----------------------------------------------------------------------------
vtkAxis* vtkChart::GetAxis(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfAxes()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::RecalculateBounds()
{
return;
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMethod(int method)
{
if (method == this->SelectionMethod)
{
return;
}
this->SelectionMethod = method;
this->Modified();
}
//-----------------------------------------------------------------------------
int vtkChart::GetSelectionMethod()
{
return this->SelectionMethod;
}
//-----------------------------------------------------------------------------
void vtkChart::SetShowLegend(bool visible)
{
if (this->ShowLegend != visible)
{
this->ShowLegend = visible;
this->Modified();
}
}
//-----------------------------------------------------------------------------
bool vtkChart::GetShowLegend()
{
return this->ShowLegend;
}
vtkChartLegend * vtkChart::GetLegend()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::SetTitle(const vtkStdString &title)
{
if (this->Title != title)
{
this->Title = title;
this->Modified();
}
}
//-----------------------------------------------------------------------------
vtkStdString vtkChart::GetTitle()
{
return this->Title;
}
//-----------------------------------------------------------------------------
bool vtkChart::CalculatePlotTransform(vtkAxis *x, vtkAxis *y,
vtkTransform2D *transform)
{
if (!x || !y || !transform)
{
vtkWarningMacro("Called with null arguments.");
return false;
}
vtkVector2d scale(x->GetMaximum() - x->GetMinimum(),
y->GetMaximum() - y->GetMinimum());
vtkVector2d factor(1.0, 1.0);
for (int i = 0; i < 2; ++i)
{
if (fabs(log10(scale[i])) > 10)
{
// We need to scale the transform to show all data, do this in blocks.
factor[i] = pow(10.0, floor(log10(scale[i]) / 10.0) * -10.0);
scale[i] = scale[i] * factor[i];
}
}
x->SetScalingFactor(factor[0]);
y->SetScalingFactor(factor[1]);
// Get the scale for the plot area from the x and y axes
float *min = x->GetPoint1();
float *max = x->GetPoint2();
if (fabs(max[0] - min[0]) == 0.0f)
{
return false;
}
float xScale = scale[0] / (max[0] - min[0]);
// Now the y axis
min = y->GetPoint1();
max = y->GetPoint2();
if (fabs(max[1] - min[1]) == 0.0f)
{
return false;
}
float yScale = scale[1] / (max[1] - min[1]);
transform->Identity();
transform->Translate(this->Point1[0], this->Point1[1]);
// Get the scale for the plot area from the x and y axes
transform->Scale(1.0 / xScale, 1.0 / yScale);
transform->Translate(-x->GetMinimum() * factor[0],
-y->GetMinimum() * factor[1]);
return true;
}
//-----------------------------------------------------------------------------
void vtkChart::SetBottomBorder(int border)
{
this->Point1[1] = border >= 0 ? border : 0;
this->Point1[1] += static_cast<int>(this->Size.GetY());
}
//-----------------------------------------------------------------------------
void vtkChart::SetTopBorder(int border)
{
this->Point2[1] = border >=0 ?
this->Geometry[1] - border :
this->Geometry[1];
this->Point2[1] += static_cast<int>(this->Size.GetY());
}
//-----------------------------------------------------------------------------
void vtkChart::SetLeftBorder(int border)
{
this->Point1[0] = border >= 0 ? border : 0;
this->Point1[0] += static_cast<int>(this->Size.GetX());
}
//-----------------------------------------------------------------------------
void vtkChart::SetRightBorder(int border)
{
this->Point2[0] = border >=0 ?
this->Geometry[0] - border :
this->Geometry[0];
this->Point2[0] += static_cast<int>(this->Size.GetX());
}
//-----------------------------------------------------------------------------
void vtkChart::SetBorders(int left, int bottom, int right, int top)
{
this->SetLeftBorder(left);
this->SetRightBorder(right);
this->SetTopBorder(top);
this->SetBottomBorder(bottom);
}
void vtkChart::SetSize(const vtkRectf &rect)
{
this->Size = rect;
this->Geometry[0] = static_cast<int>(rect.GetWidth());
this->Geometry[1] = static_cast<int>(rect.GetHeight());
}
vtkRectf vtkChart::GetSize()
{
return this->Size;
}
void vtkChart::SetActionToButton(int action, int button)
{
if (action < -1 || action >= MouseActions::MaxAction)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action] = button;
for (int i = 0; i < MouseActions::MaxAction; ++i)
{
if (this->Actions[i] == button && i != action)
{
this->Actions[i] = -1;
}
}
}
int vtkChart::GetActionToButton(int action)
{
return this->Actions[action];
}
void vtkChart::SetClickActionToButton(int action, int button)
{
if (action < vtkChart::SELECT || action > vtkChart::NOTIFY)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action - 2] = button;
}
int vtkChart::GetClickActionToButton(int action)
{
return this->Actions[action - 2];
}
//-----------------------------------------------------------------------------
void vtkChart::SetBackgroundBrush(vtkBrush *brush)
{
if(brush == NULL)
{
// set to transparent white if brush is null
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
}
else
{
this->BackgroundBrush = brush;
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkBrush* vtkChart::GetBackgroundBrush()
{
return this->BackgroundBrush.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkChart::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
// Print out the chart's geometry if it has been set
os << indent << "Point1: " << this->Point1[0] << "\t" << this->Point1[1]
<< endl;
os << indent << "Point2: " << this->Point2[0] << "\t" << this->Point2[1]
<< endl;
os << indent << "Width: " << this->Geometry[0] << endl
<< indent << "Height: " << this->Geometry[1] << endl;
os << indent << "SelectionMode: " << this->SelectionMode << endl;
}
//-----------------------------------------------------------------------------
void vtkChart::AttachAxisRangeListener(vtkAxis* axis)
{
axis->AddObserver(vtkChart::UpdateRange, this, &vtkChart::AxisRangeForwarderCallback);
}
//-----------------------------------------------------------------------------
void vtkChart::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*)
{
double fullAxisRange[8];
for(int i=0; i < 4; i++)
{
this->GetAxis(i)->GetRange(&fullAxisRange[i*2]);
}
this->InvokeEvent(vtkChart::UpdateRange, fullAxisRange);
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMode(int selMode)
{
if (this->SelectionMode == selMode ||
selMode < vtkContextScene::SELECTION_NONE ||
selMode > vtkContextScene::SELECTION_TOGGLE)
{
return;
}
this->SelectionMode = selMode;
this->Modified();
}
<|endoftext|> |
<commit_before>#include "Player.h"
#include <SFML\Graphics\CircleShape.hpp>
#include <SFML\Graphics\RenderTarget.hpp>
#include "..\..\Common\GeneralMath.h"
#include <iostream>
Player::Player(std::string p_name, sf::Font& p_font, bool p_remote)
:
m_remote(p_remote),
nameText(p_name, p_font, 14),
m_radius(20),
m_dead(false),
m_health(100),
m_score()
{
std::cout << "Called constructor for: " << p_name << "\n";
nameText.setPosition(-nameText.getLocalBounds().width/2, 24);
nameText.setStyle(sf::Text::Bold);
nameText.setColor(sf::Color::Black);
}
Player::~Player()
{
}
void Player::update(sf::Time p_deltaTime, int p_elapsedGameTime)
{
float t = (float)(p_elapsedGameTime) / (float)(targetTime - prevTime);
sf::Vector2i pos = (sf::Vector2i)math::interpolateVector(prevPos, targetPos, t);
setPosition(sf::Vector2f(pos));
std::cout << m_health << "\n";
}
void Player::setTargetTime(int p_targetTime)
{
prevTime = targetTime;
targetTime = p_targetTime;
}
void Player::setTargetPosition(sf::Vector2f p_targetPosition)
{
prevPos = targetPos;
targetPos = p_targetPosition;
}
bool Player::isRemote() const
{
return m_remote;
}
float Player::getRadius() const{
return m_radius;
}
void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
sf::CircleShape player(m_radius);
player.setFillColor(sf::Color::Red);
player.setOrigin(m_radius, m_radius);
sf::RectangleShape healthBackground(sf::Vector2<float>(40.f, 5));
sf::RectangleShape health(sf::Vector2<float>(40.f*((float)getHealth()/100), 5));
healthBackground.setFillColor(sf::Color(20, 20, 20));
health.setFillColor(sf::Color(200, 200, 200));
healthBackground.setOrigin(m_radius, m_radius + 10);
health.setOrigin(m_radius, m_radius + 10);
target.draw(player, states);
target.draw(healthBackground, states);
target.draw(health, states);
target.draw(nameText, states);
}
int Player::getHealth() const{
return m_health;
}
void Player::setHealth(const int & p_health){
m_health = p_health;
if (m_health <= 0)
{
m_dead = true;
}
}
bool Player::isDead() const{
return m_dead;
}<commit_msg>Removed print hp.<commit_after>#include "Player.h"
#include <SFML\Graphics\CircleShape.hpp>
#include <SFML\Graphics\RenderTarget.hpp>
#include "..\..\Common\GeneralMath.h"
#include <iostream>
Player::Player(std::string p_name, sf::Font& p_font, bool p_remote)
:
m_remote(p_remote),
nameText(p_name, p_font, 14),
m_radius(20),
m_dead(false),
m_health(100),
m_score()
{
std::cout << "Called constructor for: " << p_name << "\n";
nameText.setPosition(-nameText.getLocalBounds().width/2, 24);
nameText.setStyle(sf::Text::Bold);
nameText.setColor(sf::Color::Black);
}
Player::~Player()
{
}
void Player::update(sf::Time p_deltaTime, int p_elapsedGameTime)
{
float t = (float)(p_elapsedGameTime) / (float)(targetTime - prevTime);
sf::Vector2i pos = (sf::Vector2i)math::interpolateVector(prevPos, targetPos, t);
setPosition(sf::Vector2f(pos));
}
void Player::setTargetTime(int p_targetTime)
{
prevTime = targetTime;
targetTime = p_targetTime;
}
void Player::setTargetPosition(sf::Vector2f p_targetPosition)
{
prevPos = targetPos;
targetPos = p_targetPosition;
}
bool Player::isRemote() const
{
return m_remote;
}
float Player::getRadius() const{
return m_radius;
}
void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
sf::CircleShape player(m_radius);
player.setFillColor(sf::Color::Red);
player.setOrigin(m_radius, m_radius);
sf::RectangleShape healthBackground(sf::Vector2<float>(40.f, 5));
sf::RectangleShape health(sf::Vector2<float>(40.f*((float)getHealth()/100), 5));
healthBackground.setFillColor(sf::Color(20, 20, 20));
health.setFillColor(sf::Color(200, 200, 200));
healthBackground.setOrigin(m_radius, m_radius + 10);
health.setOrigin(m_radius, m_radius + 10);
target.draw(player, states);
target.draw(healthBackground, states);
target.draw(health, states);
target.draw(nameText, states);
}
int Player::getHealth() const{
return m_health;
}
void Player::setHealth(const int & p_health){
m_health = p_health;
if (m_health <= 0)
{
m_dead = true;
}
}
bool Player::isDead() const{
return m_dead;
}<|endoftext|> |
<commit_before>// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests code in gmock.cc.
#include "gmock/gmock.h"
#include <string>
#include "gtest/gtest.h"
using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock;
using testing::internal::g_init_gtest_count;
// Verifies that calling InitGoogleMock() on argv results in new_argv,
// and the gmock_verbose flag's value is set to expected_gmock_verbose.
template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose);
int argc = M;
InitGoogleMock(&argc, const_cast<Char**>(argv));
ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";
for (int i = 0; i < N; i++) {
EXPECT_STREQ(new_argv[i], argv[i]);
}
EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
GMOCK_FLAG(verbose) = old_verbose; // Restores the gmock_verbose flag.
}
TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
const char* argv[] = {
NULL
};
const char* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
const char* argv[] = {
"foo.exe",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesSingleFlag) {
const char* argv[] = {
"foo.exe",
"--gmock_verbose=info",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
"--gmock_verbose=error",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
TEST(InitGoogleMockTest, CallsInitGoogleTest) {
const int old_init_gtest_count = g_init_gtest_count;
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
"--gmock_verbose=error",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
EXPECT_EQ(old_init_gtest_count + 1, g_init_gtest_count);
}
TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
const wchar_t* argv[] = {
NULL
};
const wchar_t* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
const wchar_t* argv[] = {
L"foo.exe",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--gmock_verbose=info",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
L"--gmock_verbose=error",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
TEST(WideInitGoogleMockTest, CallsInitGoogleTest) {
const int old_init_gtest_count = g_init_gtest_count;
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
L"--gmock_verbose=error",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
EXPECT_EQ(old_init_gtest_count + 1, g_init_gtest_count);
}
// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
testing::GMOCK_FLAG(verbose) == "";
(void)dummy; // Avoids the "unused local variable" warning.
}
<commit_msg>Missing diff that should have gone along with the pull of gtest 738.<commit_after>// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests code in gmock.cc.
#include "gmock/gmock.h"
#include <string>
#include "gtest/gtest.h"
using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock;
// Verifies that calling InitGoogleMock() on argv results in new_argv,
// and the gmock_verbose flag's value is set to expected_gmock_verbose.
template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose);
int argc = M;
InitGoogleMock(&argc, const_cast<Char**>(argv));
ASSERT_EQ(N, argc) << "The new argv has wrong number of elements.";
for (int i = 0; i < N; i++) {
EXPECT_STREQ(new_argv[i], argv[i]);
}
EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
GMOCK_FLAG(verbose) = old_verbose; // Restores the gmock_verbose flag.
}
TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
const char* argv[] = {
NULL
};
const char* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
const char* argv[] = {
"foo.exe",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesSingleFlag) {
const char* argv[] = {
"foo.exe",
"--gmock_verbose=info",
NULL
};
const char* new_argv[] = {
"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const char* argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
"--gmock_verbose=error",
NULL
};
const char* new_argv[] = {
"foo.exe",
"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
const wchar_t* argv[] = {
NULL
};
const wchar_t* new_argv[] = {
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
const wchar_t* argv[] = {
L"foo.exe",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--gmock_verbose=info",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
NULL
};
TestInitGoogleMock(argv, new_argv, "info");
}
TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
}
TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
const wchar_t* argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
L"--gmock_verbose=error",
NULL
};
const wchar_t* new_argv[] = {
L"foo.exe",
L"--non_gmock_flag=blah",
NULL
};
TestInitGoogleMock(argv, new_argv, "error");
}
// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
testing::GMOCK_FLAG(verbose) == "";
(void)dummy; // Avoids the "unused local variable" warning.
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// A vector-like container that uses discontiguous storage. Provides fast random access,
// the ability to append at the end, and limited contiguous allocations.
//
// std::deque would be a good fit, except the backing array can grow quite large.
#include "utils/small_vector.hh"
#include <boost/range/algorithm/equal.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/version.hpp>
#include <memory>
#include <type_traits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <stdexcept>
namespace utils {
struct chunked_vector_free_deleter {
void operator()(void* x) const { ::free(x); }
};
template <typename T, size_t max_contiguous_allocation = 128*1024>
class chunked_vector {
static_assert(std::is_nothrow_move_constructible<T>::value, "T must be nothrow move constructible");
using chunk_ptr = std::unique_ptr<T[], chunked_vector_free_deleter>;
// Each chunk holds max_chunk_capacity() items, except possibly the last
utils::small_vector<chunk_ptr, 1> _chunks;
size_t _size = 0;
size_t _capacity = 0;
private:
static size_t max_chunk_capacity() {
return std::max(max_contiguous_allocation / sizeof(T), size_t(1));
}
void reserve_for_push_back() {
if (_size == _capacity) {
do_reserve_for_push_back();
}
}
void do_reserve_for_push_back();
void make_room(size_t n);
chunk_ptr new_chunk(size_t n);
T* addr(size_t i) const {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
void check_bounds(size_t i) const {
if (i >= _size) {
throw std::out_of_range("chunked_vector out of range access");
}
}
static void migrate(T* begin, T* end, T* result);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ssize_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
public:
chunked_vector() = default;
chunked_vector(const chunked_vector& x);
chunked_vector(chunked_vector&& x) noexcept;
template <typename Iterator>
chunked_vector(Iterator begin, Iterator end);
explicit chunked_vector(size_t n, const T& value = T());
~chunked_vector();
chunked_vector& operator=(const chunked_vector& x);
chunked_vector& operator=(chunked_vector&& x) noexcept;
bool empty() const {
return !_size;
}
size_t size() const {
return _size;
}
T& operator[](size_t i) {
return *addr(i);
}
const T& operator[](size_t i) const {
return *addr(i);
}
T& at(size_t i) {
check_bounds(i);
return *addr(i);
}
const T& at(size_t i) const {
check_bounds(i);
return *addr(i);
}
void push_back(const T& x) {
reserve_for_push_back();
new (addr(_size)) T(x);
++_size;
}
void push_back(T&& x) {
reserve_for_push_back();
new (addr(_size)) T(std::move(x));
++_size;
}
template <typename... Args>
T& emplace_back(Args&&... args) {
reserve_for_push_back();
auto& ret = *new (addr(_size)) T(std::forward<Args>(args)...);
++_size;
return ret;
}
void pop_back() {
--_size;
addr(_size)->~T();
}
const T& back() const {
return *addr(_size - 1);
}
T& back() {
return *addr(_size - 1);
}
void clear();
void shrink_to_fit();
void resize(size_t n);
void reserve(size_t n) {
if (n > _capacity) {
make_room(n);
}
}
size_t memory_size() const {
return _capacity * sizeof(T);
}
public:
template <class ValueType>
class iterator_type {
const chunk_ptr* _chunks;
size_t _i;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = ValueType;
using difference_type = ssize_t;
using pointer = ValueType*;
using reference = ValueType&;
private:
pointer addr() const {
return &_chunks[_i / max_chunk_capacity()][_i % max_chunk_capacity()];
}
iterator_type(const chunk_ptr* chunks, size_t i) : _chunks(chunks), _i(i) {}
public:
iterator_type() = default;
iterator_type(const iterator_type<std::remove_const_t<ValueType>>& x) : _chunks(x._chunks), _i(x._i) {} // needed for iterator->const_iterator conversion
reference operator*() const {
return *addr();
}
pointer operator->() const {
return addr();
}
reference operator[](ssize_t n) const {
return *(*this + n);
}
iterator_type& operator++() {
++_i;
return *this;
}
iterator_type operator++(int) {
auto x = *this;
++_i;
return x;
}
iterator_type& operator--() {
--_i;
return *this;
}
iterator_type operator--(int) {
auto x = *this;
--_i;
return x;
}
iterator_type& operator+=(ssize_t n) {
_i += n;
return *this;
}
iterator_type& operator-=(ssize_t n) {
_i -= n;
return *this;
}
iterator_type operator+(ssize_t n) const {
auto x = *this;
return x += n;
}
iterator_type operator-(ssize_t n) const {
auto x = *this;
return x -= n;
}
friend iterator_type operator+(ssize_t n, iterator_type a) {
return a + n;
}
friend ssize_t operator-(iterator_type a, iterator_type b) {
return a._i - b._i;
}
bool operator==(iterator_type x) const {
return _i == x._i;
}
bool operator!=(iterator_type x) const {
return _i != x._i;
}
bool operator<(iterator_type x) const {
return _i < x._i;
}
bool operator<=(iterator_type x) const {
return _i <= x._i;
}
bool operator>(iterator_type x) const {
return _i > x._i;
}
bool operator>=(iterator_type x) const {
return _i >= x._i;
}
friend class chunked_vector;
};
using iterator = iterator_type<T>;
using const_iterator = iterator_type<const T>;
public:
iterator begin() const { return iterator(_chunks.data(), 0); }
iterator end() const { return iterator(_chunks.data(), _size); }
const_iterator cbegin() const { return const_iterator(_chunks.data(), 0); }
const_iterator cend() const { return const_iterator(_chunks.data(), _size); }
public:
bool operator==(const chunked_vector& x) const {
return boost::equal(*this, x);
}
bool operator!=(const chunked_vector& x) const {
return !operator==(x);
}
};
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(const chunked_vector& x)
: chunked_vector() {
reserve(x.size());
std::copy(x.begin(), x.end(), std::back_inserter(*this));
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(chunked_vector&& x) noexcept
: _chunks(std::exchange(x._chunks, {}))
, _size(std::exchange(x._size, 0))
, _capacity(std::exchange(x._capacity, 0)) {
}
template <typename T, size_t max_contiguous_allocation>
template <typename Iterator>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(Iterator begin, Iterator end)
: chunked_vector() {
auto is_random_access = std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category>::value;
if (is_random_access) {
reserve(std::distance(begin, end));
}
std::copy(begin, end, std::back_inserter(*this));
if (!is_random_access) {
shrink_to_fit();
}
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(size_t n, const T& value) {
reserve(n);
std::fill_n(std::back_inserter(*this), n, value);
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>&
chunked_vector<T, max_contiguous_allocation>::operator=(const chunked_vector& x) {
auto tmp = chunked_vector(x);
return *this = std::move(tmp);
}
template <typename T, size_t max_contiguous_allocation>
inline
chunked_vector<T, max_contiguous_allocation>&
chunked_vector<T, max_contiguous_allocation>::operator=(chunked_vector&& x) noexcept {
if (this != &x) {
this->~chunked_vector();
new (this) chunked_vector(std::move(x));
}
return *this;
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::~chunked_vector() {
if constexpr (!std::is_trivially_destructible_v<T>) {
for (auto i = size_t(0); i != _size; ++i) {
addr(i)->~T();
}
}
}
template <typename T, size_t max_contiguous_allocation>
typename chunked_vector<T, max_contiguous_allocation>::chunk_ptr
chunked_vector<T, max_contiguous_allocation>::new_chunk(size_t n) {
auto p = malloc(n * sizeof(T));
if (!p) {
throw std::bad_alloc();
}
return chunk_ptr(reinterpret_cast<T*>(p));
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::migrate(T* begin, T* end, T* result) {
while (begin != end) {
new (result) T(std::move(*begin));
begin->~T();
++begin;
++result;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::make_room(size_t n) {
// First, if the last chunk is below max_chunk_capacity(), enlarge it
auto last_chunk_capacity_deficit = _chunks.size() * max_chunk_capacity() - _capacity;
if (last_chunk_capacity_deficit) {
auto last_chunk_capacity = max_chunk_capacity() - last_chunk_capacity_deficit;
auto capacity_increase = std::min(last_chunk_capacity_deficit, n - _capacity);
auto new_last_chunk_capacity = last_chunk_capacity + capacity_increase;
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr(_capacity - last_chunk_capacity), addr(_size), new_last_chunk.get());
_chunks.back() = std::move(new_last_chunk);
_capacity += capacity_increase;
}
// Reduce reallocations in the _chunks vector
auto nr_chunks = (n + max_chunk_capacity() - 1) / max_chunk_capacity();
_chunks.reserve(nr_chunks);
// Add more chunks as needed
while (_capacity < n) {
auto now = std::min(n - _capacity, max_chunk_capacity());
_chunks.push_back(new_chunk(now));
_capacity += now;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::do_reserve_for_push_back() {
if (_capacity == 0) {
// allocate a bit of room in case utilization will be low
reserve(boost::algorithm::clamp(512 / sizeof(T), 1, max_chunk_capacity()));
} else if (_capacity < max_chunk_capacity() / 2) {
// exponential increase when only one chunk to reduce copying
reserve(_capacity * 2);
} else {
// add a chunk at a time later, since no copying will take place
reserve((_capacity / max_chunk_capacity() + 1) * max_chunk_capacity());
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::resize(size_t n) {
reserve(n);
// FIXME: construct whole chunks at once
while (_size > n) {
pop_back();
}
while (_size < n) {
push_back(T{});
}
shrink_to_fit();
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::shrink_to_fit() {
if (_chunks.empty()) {
return;
}
while (!_chunks.empty() && _size <= (_chunks.size() - 1) * max_chunk_capacity()) {
_chunks.pop_back();
_capacity = _chunks.size() * max_chunk_capacity();
}
auto overcapacity = _size - _capacity;
if (overcapacity) {
auto new_last_chunk_capacity = _size - (_chunks.size() - 1) * max_chunk_capacity();
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr((_chunks.size() - 1) * max_chunk_capacity()), addr(_size), new_last_chunk.get());
_chunks.back() = std::move(new_last_chunk);
_capacity = _size;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::clear() {
resize(0);
}
}
<commit_msg>utils: chunked_vector: Implement front()<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// A vector-like container that uses discontiguous storage. Provides fast random access,
// the ability to append at the end, and limited contiguous allocations.
//
// std::deque would be a good fit, except the backing array can grow quite large.
#include "utils/small_vector.hh"
#include <boost/range/algorithm/equal.hpp>
#include <boost/algorithm/clamp.hpp>
#include <boost/version.hpp>
#include <memory>
#include <type_traits>
#include <iterator>
#include <utility>
#include <algorithm>
#include <stdexcept>
namespace utils {
struct chunked_vector_free_deleter {
void operator()(void* x) const { ::free(x); }
};
template <typename T, size_t max_contiguous_allocation = 128*1024>
class chunked_vector {
static_assert(std::is_nothrow_move_constructible<T>::value, "T must be nothrow move constructible");
using chunk_ptr = std::unique_ptr<T[], chunked_vector_free_deleter>;
// Each chunk holds max_chunk_capacity() items, except possibly the last
utils::small_vector<chunk_ptr, 1> _chunks;
size_t _size = 0;
size_t _capacity = 0;
private:
static size_t max_chunk_capacity() {
return std::max(max_contiguous_allocation / sizeof(T), size_t(1));
}
void reserve_for_push_back() {
if (_size == _capacity) {
do_reserve_for_push_back();
}
}
void do_reserve_for_push_back();
void make_room(size_t n);
chunk_ptr new_chunk(size_t n);
T* addr(size_t i) const {
return &_chunks[i / max_chunk_capacity()][i % max_chunk_capacity()];
}
void check_bounds(size_t i) const {
if (i >= _size) {
throw std::out_of_range("chunked_vector out of range access");
}
}
static void migrate(T* begin, T* end, T* result);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ssize_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
public:
chunked_vector() = default;
chunked_vector(const chunked_vector& x);
chunked_vector(chunked_vector&& x) noexcept;
template <typename Iterator>
chunked_vector(Iterator begin, Iterator end);
explicit chunked_vector(size_t n, const T& value = T());
~chunked_vector();
chunked_vector& operator=(const chunked_vector& x);
chunked_vector& operator=(chunked_vector&& x) noexcept;
bool empty() const {
return !_size;
}
size_t size() const {
return _size;
}
T& operator[](size_t i) {
return *addr(i);
}
const T& operator[](size_t i) const {
return *addr(i);
}
T& at(size_t i) {
check_bounds(i);
return *addr(i);
}
const T& at(size_t i) const {
check_bounds(i);
return *addr(i);
}
void push_back(const T& x) {
reserve_for_push_back();
new (addr(_size)) T(x);
++_size;
}
void push_back(T&& x) {
reserve_for_push_back();
new (addr(_size)) T(std::move(x));
++_size;
}
template <typename... Args>
T& emplace_back(Args&&... args) {
reserve_for_push_back();
auto& ret = *new (addr(_size)) T(std::forward<Args>(args)...);
++_size;
return ret;
}
void pop_back() {
--_size;
addr(_size)->~T();
}
const T& back() const {
return *addr(_size - 1);
}
T& back() {
return *addr(_size - 1);
}
void clear();
void shrink_to_fit();
void resize(size_t n);
void reserve(size_t n) {
if (n > _capacity) {
make_room(n);
}
}
size_t memory_size() const {
return _capacity * sizeof(T);
}
public:
template <class ValueType>
class iterator_type {
const chunk_ptr* _chunks;
size_t _i;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = ValueType;
using difference_type = ssize_t;
using pointer = ValueType*;
using reference = ValueType&;
private:
pointer addr() const {
return &_chunks[_i / max_chunk_capacity()][_i % max_chunk_capacity()];
}
iterator_type(const chunk_ptr* chunks, size_t i) : _chunks(chunks), _i(i) {}
public:
iterator_type() = default;
iterator_type(const iterator_type<std::remove_const_t<ValueType>>& x) : _chunks(x._chunks), _i(x._i) {} // needed for iterator->const_iterator conversion
reference operator*() const {
return *addr();
}
pointer operator->() const {
return addr();
}
reference operator[](ssize_t n) const {
return *(*this + n);
}
iterator_type& operator++() {
++_i;
return *this;
}
iterator_type operator++(int) {
auto x = *this;
++_i;
return x;
}
iterator_type& operator--() {
--_i;
return *this;
}
iterator_type operator--(int) {
auto x = *this;
--_i;
return x;
}
iterator_type& operator+=(ssize_t n) {
_i += n;
return *this;
}
iterator_type& operator-=(ssize_t n) {
_i -= n;
return *this;
}
iterator_type operator+(ssize_t n) const {
auto x = *this;
return x += n;
}
iterator_type operator-(ssize_t n) const {
auto x = *this;
return x -= n;
}
friend iterator_type operator+(ssize_t n, iterator_type a) {
return a + n;
}
friend ssize_t operator-(iterator_type a, iterator_type b) {
return a._i - b._i;
}
bool operator==(iterator_type x) const {
return _i == x._i;
}
bool operator!=(iterator_type x) const {
return _i != x._i;
}
bool operator<(iterator_type x) const {
return _i < x._i;
}
bool operator<=(iterator_type x) const {
return _i <= x._i;
}
bool operator>(iterator_type x) const {
return _i > x._i;
}
bool operator>=(iterator_type x) const {
return _i >= x._i;
}
friend class chunked_vector;
};
using iterator = iterator_type<T>;
using const_iterator = iterator_type<const T>;
public:
const T& front() const { return *cbegin(); }
T& front() { return *begin(); }
iterator begin() const { return iterator(_chunks.data(), 0); }
iterator end() const { return iterator(_chunks.data(), _size); }
const_iterator cbegin() const { return const_iterator(_chunks.data(), 0); }
const_iterator cend() const { return const_iterator(_chunks.data(), _size); }
public:
bool operator==(const chunked_vector& x) const {
return boost::equal(*this, x);
}
bool operator!=(const chunked_vector& x) const {
return !operator==(x);
}
};
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(const chunked_vector& x)
: chunked_vector() {
reserve(x.size());
std::copy(x.begin(), x.end(), std::back_inserter(*this));
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(chunked_vector&& x) noexcept
: _chunks(std::exchange(x._chunks, {}))
, _size(std::exchange(x._size, 0))
, _capacity(std::exchange(x._capacity, 0)) {
}
template <typename T, size_t max_contiguous_allocation>
template <typename Iterator>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(Iterator begin, Iterator end)
: chunked_vector() {
auto is_random_access = std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category>::value;
if (is_random_access) {
reserve(std::distance(begin, end));
}
std::copy(begin, end, std::back_inserter(*this));
if (!is_random_access) {
shrink_to_fit();
}
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::chunked_vector(size_t n, const T& value) {
reserve(n);
std::fill_n(std::back_inserter(*this), n, value);
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>&
chunked_vector<T, max_contiguous_allocation>::operator=(const chunked_vector& x) {
auto tmp = chunked_vector(x);
return *this = std::move(tmp);
}
template <typename T, size_t max_contiguous_allocation>
inline
chunked_vector<T, max_contiguous_allocation>&
chunked_vector<T, max_contiguous_allocation>::operator=(chunked_vector&& x) noexcept {
if (this != &x) {
this->~chunked_vector();
new (this) chunked_vector(std::move(x));
}
return *this;
}
template <typename T, size_t max_contiguous_allocation>
chunked_vector<T, max_contiguous_allocation>::~chunked_vector() {
if constexpr (!std::is_trivially_destructible_v<T>) {
for (auto i = size_t(0); i != _size; ++i) {
addr(i)->~T();
}
}
}
template <typename T, size_t max_contiguous_allocation>
typename chunked_vector<T, max_contiguous_allocation>::chunk_ptr
chunked_vector<T, max_contiguous_allocation>::new_chunk(size_t n) {
auto p = malloc(n * sizeof(T));
if (!p) {
throw std::bad_alloc();
}
return chunk_ptr(reinterpret_cast<T*>(p));
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::migrate(T* begin, T* end, T* result) {
while (begin != end) {
new (result) T(std::move(*begin));
begin->~T();
++begin;
++result;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::make_room(size_t n) {
// First, if the last chunk is below max_chunk_capacity(), enlarge it
auto last_chunk_capacity_deficit = _chunks.size() * max_chunk_capacity() - _capacity;
if (last_chunk_capacity_deficit) {
auto last_chunk_capacity = max_chunk_capacity() - last_chunk_capacity_deficit;
auto capacity_increase = std::min(last_chunk_capacity_deficit, n - _capacity);
auto new_last_chunk_capacity = last_chunk_capacity + capacity_increase;
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr(_capacity - last_chunk_capacity), addr(_size), new_last_chunk.get());
_chunks.back() = std::move(new_last_chunk);
_capacity += capacity_increase;
}
// Reduce reallocations in the _chunks vector
auto nr_chunks = (n + max_chunk_capacity() - 1) / max_chunk_capacity();
_chunks.reserve(nr_chunks);
// Add more chunks as needed
while (_capacity < n) {
auto now = std::min(n - _capacity, max_chunk_capacity());
_chunks.push_back(new_chunk(now));
_capacity += now;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::do_reserve_for_push_back() {
if (_capacity == 0) {
// allocate a bit of room in case utilization will be low
reserve(boost::algorithm::clamp(512 / sizeof(T), 1, max_chunk_capacity()));
} else if (_capacity < max_chunk_capacity() / 2) {
// exponential increase when only one chunk to reduce copying
reserve(_capacity * 2);
} else {
// add a chunk at a time later, since no copying will take place
reserve((_capacity / max_chunk_capacity() + 1) * max_chunk_capacity());
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::resize(size_t n) {
reserve(n);
// FIXME: construct whole chunks at once
while (_size > n) {
pop_back();
}
while (_size < n) {
push_back(T{});
}
shrink_to_fit();
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::shrink_to_fit() {
if (_chunks.empty()) {
return;
}
while (!_chunks.empty() && _size <= (_chunks.size() - 1) * max_chunk_capacity()) {
_chunks.pop_back();
_capacity = _chunks.size() * max_chunk_capacity();
}
auto overcapacity = _size - _capacity;
if (overcapacity) {
auto new_last_chunk_capacity = _size - (_chunks.size() - 1) * max_chunk_capacity();
// FIXME: realloc? maybe not worth the complication; only works for PODs
auto new_last_chunk = new_chunk(new_last_chunk_capacity);
migrate(addr((_chunks.size() - 1) * max_chunk_capacity()), addr(_size), new_last_chunk.get());
_chunks.back() = std::move(new_last_chunk);
_capacity = _size;
}
}
template <typename T, size_t max_contiguous_allocation>
void
chunked_vector<T, max_contiguous_allocation>::clear() {
resize(0);
}
}
<|endoftext|> |
<commit_before>#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include <assert.h>
#if defined(TEST_OPENCL)
#include "HalideRuntimeOpenCL.h"
#elif defined(TEST_CUDA)
#include "HalideRuntimeCuda.h"
#endif
#include "gpu_only.h"
#include "halide_image.h"
int main(int argc, char **argv) {
#if defined(TEST_OPENCL) || defined(TEST_CUDA)
const int W = 32, H = 32;
Image<int> input(W, H);
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
input(x, y) = x + y;
}
}
// Explicitly copy data to the GPU.
input.set_host_dirty();
#if defined(TEST_OPENCL)
input.copy_to_device(halide_opencl_device_interface());
#elif defined(TEST_CUDA)
input.copy_to_device(halide_cuda_device_interface());
#endif
Image<int> output(W, H);
// Create buffer_ts without host pointers.
buffer_t input_no_host = *((buffer_t *)input);
input_no_host.host = NULL;
buffer_t output_no_host = *((buffer_t *)output);
// We need a fake pointer here to trick Halide into creating the
// device buffer (and not do bounds inference instead of running
// the pipeline). Halide will not dereference this pointer.
output_no_host.host = (uint8_t *)1;
gpu_only(&input_no_host, &output_no_host);
// Restore the host pointer and copy to host.
output_no_host.host = (uint8_t *)output.data();
halide_copy_to_host(NULL, &output_no_host);
// Verify output.
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (input(x, y) * 2 != output(x, y)) {
printf("Error at %d, %d: %d != %d\n", x, y, input(x, y), output(x, y));
return -1;
}
}
}
printf("Success!\n");
#else
printf("No GPU target enabled, skipping...\n");
#endif
return 0;
}
<commit_msg>Add missing using namespace to gpu test<commit_after>#include <math.h>
#include <stdio.h>
#include "HalideRuntime.h"
#include <assert.h>
#if defined(TEST_OPENCL)
#include "HalideRuntimeOpenCL.h"
#elif defined(TEST_CUDA)
#include "HalideRuntimeCuda.h"
#endif
#include "gpu_only.h"
#include "halide_image.h"
using namespace Halide::Tools;
int main(int argc, char **argv) {
#if defined(TEST_OPENCL) || defined(TEST_CUDA)
const int W = 32, H = 32;
Image<int> input(W, H);
for (int y = 0; y < input.height(); y++) {
for (int x = 0; x < input.width(); x++) {
input(x, y) = x + y;
}
}
// Explicitly copy data to the GPU.
input.set_host_dirty();
#if defined(TEST_OPENCL)
input.copy_to_device(halide_opencl_device_interface());
#elif defined(TEST_CUDA)
input.copy_to_device(halide_cuda_device_interface());
#endif
Image<int> output(W, H);
// Create buffer_ts without host pointers.
buffer_t input_no_host = *((buffer_t *)input);
input_no_host.host = NULL;
buffer_t output_no_host = *((buffer_t *)output);
// We need a fake pointer here to trick Halide into creating the
// device buffer (and not do bounds inference instead of running
// the pipeline). Halide will not dereference this pointer.
output_no_host.host = (uint8_t *)1;
gpu_only(&input_no_host, &output_no_host);
// Restore the host pointer and copy to host.
output_no_host.host = (uint8_t *)output.data();
halide_copy_to_host(NULL, &output_no_host);
// Verify output.
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (input(x, y) * 2 != output(x, y)) {
printf("Error at %d, %d: %d != %d\n", x, y, input(x, y), output(x, y));
return -1;
}
}
}
printf("Success!\n");
#else
printf("No GPU target enabled, skipping...\n");
#endif
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix painting issue in Reader 9.2.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 ARM. All rights reserved.
*/
#include "mbed-net-sockets/UDPSocket.h"
#include "EthernetInterface.h"
#include "test_env.h"
#include "lwm2m-client/m2minterfacefactory.h"
#include "lwm2m-client/m2minterfaceobserver.h"
#include "lwm2m-client/m2mdevice.h"
#include "lwm2m-client/m2mobjectinstance.h"
#include "lwm2m-client/m2minterface.h"
#include "testconfig.h"
// TODO: Remove when yotta supports init.
#include "lwipv4_init.h"
const String &MANUFACTURER = "ARM";
const String &TYPE = "type";
// Dynamic resource variables
const String &DYNAMIC_RESOURCE_NAME = "Dynamic";
const String &DYNAMIC_RESOURCE_TYPE = "DynamicType";
const String &STATIC_RESOURCE_NAME = "Static";
const String &STATIC_RESOURCE_TYPE = "StaticType";
const uint8_t STATIC_VALUE[] = "Static value";
class M2MLWClient: public M2MInterfaceObserver {
public:
M2MLWClient(TestConfig *test_config){
_interface = NULL;
_register_security = NULL;
_resource_object = NULL;
_bootstrapped = false;
_error = false;
_registered = false;
_unregistered = false;
_registration_updated = false;
_resource_value = 0;
_object = NULL;
_test_config = test_config;
}
virtual ~M2MLWClient() {
if(_interface) {
delete _interface;
}
if( _register_security){
delete _register_security;
}
}
bool create_interface() {
bool success = false;
// Creates M2MInterface using which endpoint can
// setup its name, resource type, life time, connection mode,
// Currently only LwIPv4 is supported.
_interface = M2MInterfaceFactory::create_interface( *this,
_test_config->get_endpoint_name(),
_test_config->get_endpoint_type(),
_test_config->get_lifetime(),
_test_config->get_port(),
"",
M2MInterface::UDP,
M2MInterface::LwIP_IPv4,
"");
if (_interface) {
success = true;
}
return success;
}
bool bootstrap_successful() {
return _bootstrapped;
}
M2MSecurity* create_bootstrap_object() {
// Creates bootstrap server object with Bootstrap server address and other parameters
// required for client to connect to bootstrap server.
M2MSecurity *security = M2MInterfaceFactory::create_security(M2MSecurity::Bootstrap);
if(security) {
security->set_resource_value(M2MSecurity::M2MServerUri, _test_config->get_bootstrap_server());
security->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::NoSecurity);
}
return security;
}
void test_bootstrap(M2MSecurity *security) {
if(_interface) {
// Bootstrap function.
_interface->bootstrap(security);
}
}
bool register_successful() {
return _registered;
}
bool unregister_successful() {
return _unregistered;
}
bool update_register_successful() {
return _registration_updated;
}
M2MSecurity* create_register_object() {
// Creates server object with LWM2M server address and other parameters
// required for client to connect to LWM2M server.
M2MSecurity *security = M2MInterfaceFactory::create_security(M2MSecurity::M2MServer);
if(security) {
security->set_resource_value(M2MSecurity::M2MServerUri, _test_config->get_mds_server());
security->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::NoSecurity);
}
return security;
}
void test_register(M2MObjectList object_list){
if(_interface) {
// Register function
_interface->register_object(_register_security, object_list);
}
}
bool test_update_register(const uint32_t lifetime)
{
bool success = false;
if(_interface && _register_security) {
success = true;
_interface->update_registration(_register_security,lifetime);
}
return success;
}
void test_unregister(){
if(_interface) {
// Unregister function
_interface->unregister_object(NULL);
}
}
void set_register_object(M2MSecurity *®ister_object){
if(_register_security) {
delete _register_security;
_register_security = NULL;
}
_register_security = register_object;
}
M2MDevice* create_device_object() {
M2MDevice *device = M2MInterfaceFactory::create_device();
if (device) {
device->create_resource(M2MDevice::Manufacturer, MANUFACTURER);
device->create_resource(M2MDevice::DeviceType, TYPE);
}
return device;
}
M2MObject* create_generic_object() {
_object = M2MInterfaceFactory::create_object("Test");
if(_object) {
M2MObjectInstance* inst = _object->create_object_instance();
if(inst) {
M2MResource* res = inst->create_dynamic_resource("D","ResourceTest",true);
char buffer[20];
int size = sprintf(buffer,"%d",_resource_value);
res->set_operation(M2MBase::GET_PUT_POST_ALLOWED);
res->set_value((const uint8_t*)buffer,
(const uint32_t)size,
true);
_resource_value++;
inst->create_static_resource("S",
"ResourceTest",
STATIC_VALUE,
sizeof(STATIC_VALUE)-1);
}
}
return _object;
}
//Callback from mbed client stack when the bootstrap
// is successful, it returns the mbed Device Server object
// which will be used for registering the resources to
// mbed Device server.
void bootstrap_done(M2MSecurity *server_object){
if(server_object) {
_bootstrapped = true;
_error = false;
}
}
//Callback from mbed client stack when the registration
// is successful, it returns the mbed Device Server object
// to which the resources are registered and registered objects.
void object_registered(M2MSecurity */*security_object*/, const M2MServer &/*server_object*/){
_registered = true;
_unregistered = false;
}
//Callback from mbed client stack when the registration update
// is successful, it returns the mbed Device Server object
// to which the resources are registered and registered objects.
void registration_updated(M2MSecurity */*security_object*/, const M2MServer &/*server_object*/){
_registration_updated = true;
}
//Callback from mbed client stack when the unregistration
// is successful, it returns the mbed Device Server object
// to which the resources were unregistered.
void object_unregistered(M2MSecurity */*server_object*/){
_unregistered = true;
_registered = false;
}
//Callback from mbed client stack if any value has changed
// during PUT operation. Object and its type is passed in
// the callback.
void value_updated(M2MBase *base, M2MBase::BaseType type) {
printf("\nValue updated of Object name %s and Type %d\n",
base->name().c_str(), type);
}
//Callback from mbed client stack if any error is encountered
// during any of the LWM2M operations. Error type is passed in
// the callback.
void error(M2MInterface::Error error){
_error = true;
printf("\nError occured %d\n", error);
}
private:
M2MInterface *_interface;
M2MSecurity *_register_security;
M2MObject *_resource_object;
M2MObject *_object;
volatile bool _bootstrapped;
volatile bool _error;
volatile bool _registered;
volatile bool _unregistered;
volatile bool _registration_updated;
int _resource_value;
TestConfig *_test_config;
};
#define SUITE_TEST_INFO(test_name, info) printf("Suite-%s: %s\n", test_name, info)
#define SUITE_TEST_RESULT(test_name, result) printf("Suite-%s: result %s\n", test_name, result ? "PASSED" : "FAILED")
#define SUITE_RESULT(result) printf("Suite: result %s\n", result ? "success" : "failure")
bool test_bootStrap(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_bootStrap";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface to manage bootstrap,
// register and unregister
_result &= lwm2mclient->create_interface();
// Create LWM2M bootstrap object specifying bootstrap server
// information.
M2MSecurity* security_object = lwm2mclient->create_bootstrap_object();
// Issue bootstrap command.
lwm2mclient->test_bootstrap(security_object);
SUITE_TEST_INFO(_tn, "bootstrap done");
// Wait till the bootstrap callback is called successfully.
// Callback comes in bootstrap_done()
while (!(_result &= lwm2mclient->bootstrap_successful())) { __WFI(); }
// Delete security object created for bootstrapping
if(security_object) {
delete security_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
bool test_deviceObject(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_deviceObject";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface for M2M server
_result &= lwm2mclient->create_interface();
M2MSecurity *register_object = lwm2mclient->create_register_object();
lwm2mclient->set_register_object(register_object);
// Create LWM2M device object specifying device resources
// as per OMA LWM2M specification.
M2MDevice* device_object = lwm2mclient->create_device_object();
// Add the device object that we want to register
// into the list and pass the list for register API.
M2MObjectList object_list;
object_list.push_back(device_object);
// Issue register command.
lwm2mclient->test_register(object_list);
SUITE_TEST_INFO(_tn, "register done");
wait_ms(1000);
// Wait till the register callback is called successfully.
// Callback comes in object_registered()
while (!(_result &= lwm2mclient->register_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "register callback done");
// Wait 5 seconds
wait_ms(1000);
//TODO move this to callback when that can be taken in use
_result &= lwm2mclient->test_update_register(2222);
SUITE_TEST_INFO(_tn, "update register done");
// Wait till the register callback is called successfully.
// Callback comes in object_updated()
//while (!lwm2mclient.update_register_successful()) { __WFI(); }
// Issue unregister command.
lwm2mclient->test_unregister();
SUITE_TEST_INFO(_tn, "unregister done");
// Wait for the unregister successful callback,
// Callback comes in object_unregistered().
while (!(_result &= lwm2mclient->unregister_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "unregister callback done");
// Delete device object created for registering device
// resources.
if(device_object) {
delete device_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
bool test_resource(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_resource";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
//M2MLWClient *lwm2mclient;
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface for M2M server
_result &= lwm2mclient->create_interface();
M2MSecurity *register_object = lwm2mclient->create_register_object();
lwm2mclient->set_register_object(register_object);
// Create LWM2M device object specifying device resources
// as per OMA LWM2M specification.
M2MDevice* device_object = lwm2mclient->create_device_object();
// Create LWM2M generic object for resource
M2MObject* resource_object = lwm2mclient->create_generic_object();
// Add the device object that we want to register
// into the list and pass the list for register API.
M2MObjectList object_list;
object_list.push_back(device_object);
object_list.push_back(resource_object);
// Issue register command.
lwm2mclient->test_register(object_list);
SUITE_TEST_INFO(_tn, "register done");
// Wait till the register callback is called successfully.
// Callback comes in object_registered()
//while (! lwm2mclient.register_successful()) { __WFI(); }
while (!( _result &= lwm2mclient->register_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "register callback done");
// Wait 5 seconds
wait_ms(5000);
// Issue unregister command.
lwm2mclient->test_unregister();
SUITE_TEST_INFO(_tn, "unregister done");
// Wait for the unregister successful callback,
// Callback comes in object_unregistered().
while (!( _result &= lwm2mclient->unregister_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "unregister callback done");
// Delete device object created for registering device
// resources.
if(device_object) {
delete device_object;
}
// Delete resource object for registering resources.
if(resource_object) {
delete resource_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
int main() {
bool result = true;
MBED_HOSTTEST_TIMEOUT(40);
MBED_HOSTTEST_SELECT(lwm2mclient_auto);
MBED_HOSTTEST_DESCRIPTION(LWM2MClient Smoke Test);
MBED_HOSTTEST_START("LWM2MClientSmokeTest");
// This sets up the network interface configuration which will be used
// by LWM2M Client API to communicate with mbed Device server.
EthernetInterface eth;
eth.init(); //Use DHCP
eth.connect();
lwipv4_socket_init();
// Create test config object, and setup with unique MAC address
TestConfig test_config;
test_config.setup();
result &= test_bootStrap(&test_config);
result &= test_deviceObject(&test_config);
result &= test_resource(&test_config);
// Disconnect and teardown the network interface
eth.disconnect();
// Communicate test result
SUITE_RESULT(result);
}
<commit_msg>Added led to signify when test is executing<commit_after>/*
* Copyright (c) 2015 ARM. All rights reserved.
*/
#include "mbed-net-sockets/UDPSocket.h"
#include "EthernetInterface.h"
#include "test_env.h"
#include "lwm2m-client/m2minterfacefactory.h"
#include "lwm2m-client/m2minterfaceobserver.h"
#include "lwm2m-client/m2mdevice.h"
#include "lwm2m-client/m2mobjectinstance.h"
#include "lwm2m-client/m2minterface.h"
#include "testconfig.h"
// TODO: Remove when yotta supports init.
#include "lwipv4_init.h"
const String &MANUFACTURER = "ARM";
const String &TYPE = "type";
// Dynamic resource variables
const String &DYNAMIC_RESOURCE_NAME = "Dynamic";
const String &DYNAMIC_RESOURCE_TYPE = "DynamicType";
const String &STATIC_RESOURCE_NAME = "Static";
const String &STATIC_RESOURCE_TYPE = "StaticType";
const uint8_t STATIC_VALUE[] = "Static value";
class M2MLWClient: public M2MInterfaceObserver {
public:
M2MLWClient(TestConfig *test_config){
_interface = NULL;
_register_security = NULL;
_resource_object = NULL;
_bootstrapped = false;
_error = false;
_registered = false;
_unregistered = false;
_registration_updated = false;
_resource_value = 0;
_object = NULL;
_test_config = test_config;
}
virtual ~M2MLWClient() {
if(_interface) {
delete _interface;
}
if( _register_security){
delete _register_security;
}
}
bool create_interface() {
bool success = false;
// Creates M2MInterface using which endpoint can
// setup its name, resource type, life time, connection mode,
// Currently only LwIPv4 is supported.
_interface = M2MInterfaceFactory::create_interface( *this,
_test_config->get_endpoint_name(),
_test_config->get_endpoint_type(),
_test_config->get_lifetime(),
_test_config->get_port(),
"",
M2MInterface::UDP,
M2MInterface::LwIP_IPv4,
"");
if (_interface) {
success = true;
}
return success;
}
bool bootstrap_successful() {
return _bootstrapped;
}
M2MSecurity* create_bootstrap_object() {
// Creates bootstrap server object with Bootstrap server address and other parameters
// required for client to connect to bootstrap server.
M2MSecurity *security = M2MInterfaceFactory::create_security(M2MSecurity::Bootstrap);
if(security) {
security->set_resource_value(M2MSecurity::M2MServerUri, _test_config->get_bootstrap_server());
security->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::NoSecurity);
}
return security;
}
void test_bootstrap(M2MSecurity *security) {
if(_interface) {
// Bootstrap function.
_interface->bootstrap(security);
}
}
bool register_successful() {
return _registered;
}
bool unregister_successful() {
return _unregistered;
}
bool update_register_successful() {
return _registration_updated;
}
M2MSecurity* create_register_object() {
// Creates server object with LWM2M server address and other parameters
// required for client to connect to LWM2M server.
M2MSecurity *security = M2MInterfaceFactory::create_security(M2MSecurity::M2MServer);
if(security) {
security->set_resource_value(M2MSecurity::M2MServerUri, _test_config->get_mds_server());
security->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::NoSecurity);
}
return security;
}
void test_register(M2MObjectList object_list){
if(_interface) {
// Register function
_interface->register_object(_register_security, object_list);
}
}
bool test_update_register(const uint32_t lifetime)
{
bool success = false;
if(_interface && _register_security) {
success = true;
_interface->update_registration(_register_security,lifetime);
}
return success;
}
void test_unregister(){
if(_interface) {
// Unregister function
_interface->unregister_object(NULL);
}
}
void set_register_object(M2MSecurity *®ister_object){
if(_register_security) {
delete _register_security;
_register_security = NULL;
}
_register_security = register_object;
}
M2MDevice* create_device_object() {
M2MDevice *device = M2MInterfaceFactory::create_device();
if (device) {
device->create_resource(M2MDevice::Manufacturer, MANUFACTURER);
device->create_resource(M2MDevice::DeviceType, TYPE);
}
return device;
}
M2MObject* create_generic_object() {
_object = M2MInterfaceFactory::create_object("Test");
if(_object) {
M2MObjectInstance* inst = _object->create_object_instance();
if(inst) {
M2MResource* res = inst->create_dynamic_resource("D","ResourceTest",true);
char buffer[20];
int size = sprintf(buffer,"%d",_resource_value);
res->set_operation(M2MBase::GET_PUT_POST_ALLOWED);
res->set_value((const uint8_t*)buffer,
(const uint32_t)size,
true);
_resource_value++;
inst->create_static_resource("S",
"ResourceTest",
STATIC_VALUE,
sizeof(STATIC_VALUE)-1);
}
}
return _object;
}
//Callback from mbed client stack when the bootstrap
// is successful, it returns the mbed Device Server object
// which will be used for registering the resources to
// mbed Device server.
void bootstrap_done(M2MSecurity *server_object){
if(server_object) {
_bootstrapped = true;
_error = false;
}
}
//Callback from mbed client stack when the registration
// is successful, it returns the mbed Device Server object
// to which the resources are registered and registered objects.
void object_registered(M2MSecurity */*security_object*/, const M2MServer &/*server_object*/){
_registered = true;
_unregistered = false;
}
//Callback from mbed client stack when the registration update
// is successful, it returns the mbed Device Server object
// to which the resources are registered and registered objects.
void registration_updated(M2MSecurity */*security_object*/, const M2MServer &/*server_object*/){
_registration_updated = true;
}
//Callback from mbed client stack when the unregistration
// is successful, it returns the mbed Device Server object
// to which the resources were unregistered.
void object_unregistered(M2MSecurity */*server_object*/){
_unregistered = true;
_registered = false;
}
//Callback from mbed client stack if any value has changed
// during PUT operation. Object and its type is passed in
// the callback.
void value_updated(M2MBase *base, M2MBase::BaseType type) {
printf("\nValue updated of Object name %s and Type %d\n",
base->name().c_str(), type);
}
//Callback from mbed client stack if any error is encountered
// during any of the LWM2M operations. Error type is passed in
// the callback.
void error(M2MInterface::Error error){
_error = true;
printf("\nError occured %d\n", error);
}
private:
M2MInterface *_interface;
M2MSecurity *_register_security;
M2MObject *_resource_object;
M2MObject *_object;
volatile bool _bootstrapped;
volatile bool _error;
volatile bool _registered;
volatile bool _unregistered;
volatile bool _registration_updated;
int _resource_value;
TestConfig *_test_config;
};
#define SUITE_TEST_INFO(test_name, info) printf("Suite-%s: %s\n", test_name, info)
#define SUITE_TEST_RESULT(test_name, result) printf("Suite-%s: result %s\n", test_name, result ? "PASSED" : "FAILED")
#define SUITE_RESULT(result) printf("Suite: result %s\n", result ? "success" : "failure")
bool test_bootStrap(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_bootStrap";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface to manage bootstrap,
// register and unregister
_result &= lwm2mclient->create_interface();
// Create LWM2M bootstrap object specifying bootstrap server
// information.
M2MSecurity* security_object = lwm2mclient->create_bootstrap_object();
// Issue bootstrap command.
lwm2mclient->test_bootstrap(security_object);
SUITE_TEST_INFO(_tn, "bootstrap done");
// Wait till the bootstrap callback is called successfully.
// Callback comes in bootstrap_done()
while (!(_result &= lwm2mclient->bootstrap_successful())) { __WFI(); }
// Delete security object created for bootstrapping
if(security_object) {
delete security_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
bool test_deviceObject(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_deviceObject";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface for M2M server
_result &= lwm2mclient->create_interface();
M2MSecurity *register_object = lwm2mclient->create_register_object();
lwm2mclient->set_register_object(register_object);
// Create LWM2M device object specifying device resources
// as per OMA LWM2M specification.
M2MDevice* device_object = lwm2mclient->create_device_object();
// Add the device object that we want to register
// into the list and pass the list for register API.
M2MObjectList object_list;
object_list.push_back(device_object);
// Issue register command.
lwm2mclient->test_register(object_list);
SUITE_TEST_INFO(_tn, "register done");
wait_ms(1000);
// Wait till the register callback is called successfully.
// Callback comes in object_registered()
while (!(_result &= lwm2mclient->register_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "register callback done");
// Wait 5 seconds
wait_ms(1000);
//TODO move this to callback when that can be taken in use
_result &= lwm2mclient->test_update_register(2222);
SUITE_TEST_INFO(_tn, "update register done");
// Wait till the register callback is called successfully.
// Callback comes in object_updated()
//while (!lwm2mclient.update_register_successful()) { __WFI(); }
// Issue unregister command.
lwm2mclient->test_unregister();
SUITE_TEST_INFO(_tn, "unregister done");
// Wait for the unregister successful callback,
// Callback comes in object_unregistered().
while (!(_result &= lwm2mclient->unregister_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "unregister callback done");
// Delete device object created for registering device
// resources.
if(device_object) {
delete device_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
bool test_resource(TestConfig *test_config) {
bool _result = true;
const char* _tn = "test_resource";
SUITE_TEST_INFO(_tn, "STARTED");
// Instantiate the class which implements
// LWM2M Client API
//M2MLWClient *lwm2mclient;
M2MLWClient *lwm2mclient = new M2MLWClient(test_config);
SUITE_TEST_INFO(_tn, "client done");
// Create LWM2M Client API interface for M2M server
_result &= lwm2mclient->create_interface();
M2MSecurity *register_object = lwm2mclient->create_register_object();
lwm2mclient->set_register_object(register_object);
// Create LWM2M device object specifying device resources
// as per OMA LWM2M specification.
M2MDevice* device_object = lwm2mclient->create_device_object();
// Create LWM2M generic object for resource
M2MObject* resource_object = lwm2mclient->create_generic_object();
// Add the device object that we want to register
// into the list and pass the list for register API.
M2MObjectList object_list;
object_list.push_back(device_object);
object_list.push_back(resource_object);
// Issue register command.
lwm2mclient->test_register(object_list);
SUITE_TEST_INFO(_tn, "register done");
// Wait till the register callback is called successfully.
// Callback comes in object_registered()
//while (! lwm2mclient.register_successful()) { __WFI(); }
while (!( _result &= lwm2mclient->register_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "register callback done");
// Wait 5 seconds
wait_ms(5000);
// Issue unregister command.
lwm2mclient->test_unregister();
SUITE_TEST_INFO(_tn, "unregister done");
// Wait for the unregister successful callback,
// Callback comes in object_unregistered().
while (!( _result &= lwm2mclient->unregister_successful() ))
{ __WFI(); }
SUITE_TEST_INFO(_tn, "unregister callback done");
// Delete device object created for registering device
// resources.
if(device_object) {
delete device_object;
}
// Delete resource object for registering resources.
if(resource_object) {
delete resource_object;
}
if (lwm2mclient) {
delete lwm2mclient;
}
SUITE_TEST_RESULT(_tn, _result);
return _result;
}
int main() {
bool result = true;
DigitalOut _led = DigitalOut(LED3);
_led = 1;
MBED_HOSTTEST_TIMEOUT(40);
MBED_HOSTTEST_SELECT(lwm2mclient_auto);
MBED_HOSTTEST_DESCRIPTION(LWM2MClient Smoke Test);
MBED_HOSTTEST_START("LWM2MClientSmokeTest");
// This sets up the network interface configuration which will be used
// by LWM2M Client API to communicate with mbed Device server.
EthernetInterface eth;
eth.init(); //Use DHCP
eth.connect();
lwipv4_socket_init();
// Create test config object, and setup with unique MAC address
TestConfig test_config;
test_config.setup();
_led = 0;
result &= test_bootStrap(&test_config);
result &= test_deviceObject(&test_config);
result &= test_resource(&test_config);
_led = 1;
// Disconnect and teardown the network interface
eth.disconnect();
// Communicate test result
SUITE_RESULT(result);
}
<|endoftext|> |
<commit_before>// RUN: %srcroot/test/runtime/run-scheduler-test.py %s -gxx "%gxx" -llvmgcc "%llvmgcc" -projbindir "%projbindir" -ternruntime "%ternruntime" -ternbcruntime "%ternbcruntime"
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define N 100
pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
struct timespec oldts;
struct timeval oldtv;
time_t oldtt;
// require mu hold before calling this function
void check_time(bool init = false)
{
struct timespec ts;
struct timeval tv;
time_t tt;
gettimeofday(&tv, NULL);
clock_gettime(CLOCK_REALTIME, &ts);
time(&tt);
if (!init)
{
if (tv.tv_sec < oldtv.tv_sec ||
tv.tv_sec == oldtv.tv_sec && tv.tv_usec < oldtv.tv_usec)
assert(0 && "gettimeofday is not monotonic");
if (ts.tv_sec < oldts.tv_sec ||
ts.tv_sec == oldts.tv_sec && ts.tv_nsec < oldts.tv_nsec)
assert(0 && "clock_gettime is not monotonic");
if (tt < oldtt)
assert(0 && "time is not monotonic");
}
oldts = ts;
oldtv = tv;
oldtt = tt;
}
void* thread_func(void*) {
for(unsigned i=0;i<100;++i)
sched_yield();
pthread_mutex_lock(&mu);
check_time();
usleep(10);
pthread_mutex_unlock(&mu);
}
int main(int argc, char *argv[], char *env[]) {
int ret;
pthread_t th[N];
check_time(true);
for (int i = 0; i < N; ++i)
pthread_create(&th[i], NULL, thread_func, NULL);
for (int i = 0; i < N; ++i)
pthread_join(th[i], NULL);
printf("test done\n");
return 0;
}
// CHECK indicates expected output checked by FileCheck; auto-generated by appending -gen to the RUN command above.
// CHECK: test done
<commit_msg>add compatibility check between different gettime functions<commit_after>// RUN: %srcroot/test/runtime/run-scheduler-test.py %s -gxx "%gxx" -llvmgcc "%llvmgcc" -projbindir "%projbindir" -ternruntime "%ternruntime" -ternbcruntime "%ternbcruntime"
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define N 100
pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
struct timespec oldts;
struct timeval oldtv;
time_t oldtt;
// require mu hold before calling this function
void check_time(bool init = false)
{
struct timespec ts;
struct timeval tv;
time_t tt;
gettimeofday(&tv, NULL);
clock_gettime(CLOCK_REALTIME, &ts);
time(&tt);
if (!init)
{
if (tv.tv_sec < oldtv.tv_sec ||
tv.tv_sec == oldtv.tv_sec && tv.tv_usec < oldtv.tv_usec)
assert(0 && "gettimeofday is not monotonic");
if (tv.tv_sec < oldts.tv_sec ||
tv.tv_sec == oldts.tv_sec && tv.tv_usec * 1000 < oldts.tv_nsec)
assert(0 && "gettimeofday is not monotonic");
if (tv.tv_sec < oldtt)
assert(0 && "gettimeofday is not monotonic");
if (ts.tv_sec < oldts.tv_sec ||
ts.tv_sec == oldts.tv_sec && ts.tv_nsec < oldts.tv_nsec)
assert(0 && "clock_gettime is not monotonic");
if (ts.tv_sec < oldtv.tv_sec ||
ts.tv_sec == oldtv.tv_sec && ts.tv_nsec < oldtv.tv_usec * 1000)
assert(0 && "clock_gettime is not monotonic");
if (ts.tv_sec < oldtt)
assert(0 && "clock_gettime is not monotonic");
if (tt < oldtt || tt < oldtv.tv_sec || tt < oldts.tv_sec)
assert(0 && "time is not monotonic");
}
oldts = ts;
oldtv = tv;
oldtt = tt;
}
void* thread_func(void*) {
for(unsigned i=0;i<100;++i)
sched_yield();
pthread_mutex_lock(&mu);
check_time();
usleep(10);
pthread_mutex_unlock(&mu);
}
int main(int argc, char *argv[], char *env[]) {
int ret;
pthread_t th[N];
check_time(true);
for (int i = 0; i < N; ++i)
pthread_create(&th[i], NULL, thread_func, NULL);
for (int i = 0; i < N; ++i)
pthread_join(th[i], NULL);
printf("test done\n");
return 0;
}
// CHECK indicates expected output checked by FileCheck; auto-generated by appending -gen to the RUN command above.
// CHECK: test done
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2014, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <strings.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <assert.h>
#include <errno.h>
#include <convert.hpp>
#include <sstream>
#include "TestPlatform.h"
#include "ParameterMgrPlatformConnector.h"
#include "RemoteProcessorServer.h"
using std::string;
class CParameterMgrPlatformConnectorLogger : public CParameterMgrPlatformConnector::ILogger
{
public:
CParameterMgrPlatformConnectorLogger() {}
virtual void log(bool bIsWarning, const string& strLog) {
if (bIsWarning) {
std::cerr << strLog << std::endl;
} else {
std::cout << strLog << std::endl;
}
}
};
CTestPlatform::CTestPlatform(const string& strClass, int iPortNumber, sem_t& exitSemaphore) :
_pParameterMgrPlatformConnector(new CParameterMgrPlatformConnector(strClass)),
_pParameterMgrPlatformConnectorLogger(new CParameterMgrPlatformConnectorLogger),
_portNumber(iPortNumber),
_exitSemaphore(exitSemaphore)
{
_pCommandHandler = new CCommandHandler(this);
// Add command parsers
_pCommandHandler->addCommandParser("exit", &CTestPlatform::exit,
0, "", "Exit TestPlatform");
_pCommandHandler->addCommandParser(
"createExclusiveSelectionCriterionFromStateList",
&CTestPlatform::createExclusiveSelectionCriterionFromStateList,
2, "<name> <stateList>",
"Create inclusive selection criterion from state name list");
_pCommandHandler->addCommandParser(
"createInclusiveSelectionCriterionFromStateList",
&CTestPlatform::createInclusiveSelectionCriterionFromStateList,
2, "<name> <stateList>",
"Create exclusive selection criterion from state name list");
_pCommandHandler->addCommandParser(
"createExclusiveSelectionCriterion",
&CTestPlatform::createExclusiveSelectionCriterion,
2, "<name> <nbStates>", "Create inclusive selection criterion");
_pCommandHandler->addCommandParser(
"createInclusiveSelectionCriterion",
&CTestPlatform::createInclusiveSelectionCriterion,
2, "<name> <nbStates>", "Create exclusive selection criterion");
_pCommandHandler->addCommandParser("start", &CTestPlatform::startParameterMgr,
0, "", "Start ParameterMgr");
_pCommandHandler->addCommandParser("setCriterionState", &CTestPlatform::setCriterionState,
2, "<name> <state>",
"Set the current state of a selection criterion");
_pCommandHandler->addCommandParser(
"applyConfigurations",
&CTestPlatform::applyConfigurations,
0, "", "Apply configurations selected by current selection criteria states");
_pCommandHandler->addCommandParser(
"setFailureOnMissingSubsystem",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setFailureOnMissingSubsystem>,
1, "true|false", "Set policy for missing subsystems, "
"either abort start or fallback on virtual subsystem.");
_pCommandHandler->addCommandParser(
"getMissingSubsystemPolicy",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getFailureOnMissingSubsystem>,
0, "", "Get policy for missing subsystems, "
"either abort start or fallback on virtual subsystem.");
_pCommandHandler->addCommandParser(
"setFailureOnFailedSettingsLoad",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad>,
1, "true|false",
"Set policy for failed settings load, either abort start or continue without domains.");
_pCommandHandler->addCommandParser(
"getFailedSettingsLoadPolicy",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getFailureOnFailedSettingsLoad>,
0, "",
"Get policy for failed settings load, either abort start or continue without domains.");
_pCommandHandler->addCommandParser(
"setValidateSchemasOnStart",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setValidateSchemasOnStart>,
1, "true|false",
"Set policy for schema validation based on .xsd files (false by default).");
_pCommandHandler->addCommandParser(
"getValidateSchemasOnStart",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getValidateSchemasOnStart>,
0, "",
"Get policy for schema validation based on .xsd files.");
// Create server
_pRemoteProcessorServer = new CRemoteProcessorServer(iPortNumber, _pCommandHandler);
_pParameterMgrPlatformConnector->setLogger(_pParameterMgrPlatformConnectorLogger);
}
CTestPlatform::~CTestPlatform()
{
delete _pRemoteProcessorServer;
delete _pCommandHandler;
delete _pParameterMgrPlatformConnectorLogger;
delete _pParameterMgrPlatformConnector;
}
CTestPlatform::CommandReturn CTestPlatform::exit(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
// Stop local server
_pRemoteProcessorServer->stop();
// Release the main blocking semaphore to quit application
sem_post(&_exitSemaphore);
return CTestPlatform::CCommandHandler::EDone;
}
bool CTestPlatform::load(std::string& strError)
{
// Start remote processor server
if (!_pRemoteProcessorServer->start()) {
std::ostringstream oss;
oss << "TestPlatform: Unable to start remote processor server on port " << _portNumber;
strError = oss.str();
return false;
}
return true;
}
//////////////// Remote command parsers
/// Selection Criterion
CTestPlatform::CommandReturn CTestPlatform::createExclusiveSelectionCriterionFromStateList(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createExclusiveSelectionCriterionFromStateList(
remoteCommand.getArgument(0), remoteCommand, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createInclusiveSelectionCriterionFromStateList(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createInclusiveSelectionCriterionFromStateList(
remoteCommand.getArgument(0), remoteCommand, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createExclusiveSelectionCriterion(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createExclusiveSelectionCriterion(
remoteCommand.getArgument(0),
strtoul(remoteCommand.getArgument(1).c_str(), NULL, 0),
strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createInclusiveSelectionCriterion(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createInclusiveSelectionCriterion(
remoteCommand.getArgument(0),
strtoul(remoteCommand.getArgument(1).c_str(), NULL, 0),
strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::startParameterMgr(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
return _pParameterMgrPlatformConnector->start(strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
template<CTestPlatform::setter_t setFunction>
CTestPlatform::CommandReturn CTestPlatform::setter(
const IRemoteCommand& remoteCommand, string& strResult)
{
const string& strAbort = remoteCommand.getArgument(0);
bool bFail;
if(!convertTo(strAbort, bFail)) {
return CTestPlatform::CCommandHandler::EShowUsage;
}
return (_pParameterMgrPlatformConnector->*setFunction)(bFail, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
template<CTestPlatform::getter_t getFunction>
CTestPlatform::CommandReturn CTestPlatform::getter(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
(void)strResult;
strResult = (_pParameterMgrPlatformConnector->*getFunction)() ? "true" : "false";
return CTestPlatform::CCommandHandler::EDone;
}
CTestPlatform::CommandReturn CTestPlatform::setCriterionState(
const IRemoteCommand& remoteCommand, string& strResult)
{
bool bSuccess;
const char * pcState = remoteCommand.getArgument(1).c_str();
char *pcStrEnd;
// Reset errno to check if it is updated during the conversion (strtol/strtoul)
errno = 0;
uint32_t state = strtoul(pcState , &pcStrEnd, 0);
if (!errno && (*pcStrEnd == '\0')) {
// Sucessfull conversion, set criterion state by numerical state
bSuccess = setCriterionState(remoteCommand.getArgument(0), state , strResult ) ;
} else {
// Conversion failed, set criterion state by lexical state
bSuccess = setCriterionStateByLexicalSpace(remoteCommand , strResult );
}
return bSuccess ? CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::applyConfigurations(const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
(void)strResult;
_pParameterMgrPlatformConnector->applyConfigurations();
return CTestPlatform::CCommandHandler::EDone;
}
//////////////// Remote command handlers
bool CTestPlatform::createExclusiveSelectionCriterionFromStateList(const string& strName, const IRemoteCommand& remoteCommand, string& strResult)
{
assert (_pParameterMgrPlatformConnector != NULL);
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(false);
assert(pCriterionType != NULL);
uint32_t uiNbStates = remoteCommand.getArgumentCount() - 1 ;
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
const std::string& strValue = remoteCommand.getArgument(uiState + 1);
if (!pCriterionType->addValuePair(uiState, strValue)) {
strResult = "Unable to add value: " + strValue;
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createInclusiveSelectionCriterionFromStateList(const string& strName, const IRemoteCommand& remoteCommand, string& strResult)
{
assert (_pParameterMgrPlatformConnector != NULL);
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(true);
assert(pCriterionType != NULL);
uint32_t uiNbStates = remoteCommand.getArgumentCount() - 1 ;
if (uiNbStates > 32) {
strResult = "Maximum number of states for inclusive criterion is 32";
return false;
}
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
const std::string& strValue = remoteCommand.getArgument(uiState + 1);
if (!pCriterionType->addValuePair(0x1 << uiState, strValue)) {
strResult = "Unable to add value: " + strValue;
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createExclusiveSelectionCriterion(const string& strName, uint32_t uiNbStates, string& strResult)
{
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(false);
uint32_t uistate;
for (uistate = 0; uistate < uiNbStates; uistate++) {
std::ostringstream ostrValue;
ostrValue << "State_";
ostrValue << uistate;
if (!pCriterionType->addValuePair(uistate, ostrValue.str())) {
strResult = "Unable to add value: " + ostrValue.str();
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createInclusiveSelectionCriterion(const string& strName, uint32_t uiNbStates, string& strResult)
{
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(true);
if (uiNbStates > 32) {
strResult = "Maximum number of states for inclusive criterion is 32";
return false;
}
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
std::ostringstream ostrValue;
ostrValue << "State_0x";
ostrValue << (0x1 << uiState);
if (!pCriterionType->addValuePair(0x1 << uiState, ostrValue.str())) {
strResult = "Unable to add value: " + ostrValue.str();
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::setCriterionState(const string& strName, uint32_t uiState, string& strResult)
{
ISelectionCriterionInterface* pCriterion = _pParameterMgrPlatformConnector->getSelectionCriterion(strName);
if (!pCriterion) {
strResult = "Unable to retrieve selection criterion: " + strName;
return false;
}
pCriterion->setCriterionState(uiState);
return true;
}
bool CTestPlatform::setCriterionStateByLexicalSpace(const IRemoteCommand& remoteCommand, string& strResult)
{
// Get criterion name
std::string strCriterionName = remoteCommand.getArgument(0);
ISelectionCriterionInterface* pCriterion = _pParameterMgrPlatformConnector->getSelectionCriterion(strCriterionName);
if (!pCriterion) {
strResult = "Unable to retrieve selection criterion: " + strCriterionName;
return false;
}
// Get criterion type
const ISelectionCriterionTypeInterface* pCriterionType = pCriterion->getCriterionType();
// Get substate number, the first argument (index 0) is the criterion name
uint32_t uiNbSubStates = remoteCommand.getArgumentCount() - 1;
// Check that exclusive criterion has only one substate
if (!pCriterionType->isTypeInclusive() && uiNbSubStates != 1) {
strResult = "Exclusive criterion " + strCriterionName + " can only have one state";
return false;
}
/// Translate lexical state to numerical state
uint32_t uiNumericalState = 0;
uint32_t uiLexicalSubStateIndex;
// Parse lexical substates
for (uiLexicalSubStateIndex = 1; uiLexicalSubStateIndex <= uiNbSubStates; uiLexicalSubStateIndex++) {
int iNumericalSubState;
const std::string& strLexicalSubState = remoteCommand.getArgument(uiLexicalSubStateIndex);
// Translate lexical to numerical substate
if (!pCriterionType->getNumericalValue(strLexicalSubState, iNumericalSubState)) {
strResult = "Unable to find lexical state \"" + strLexicalSubState + "\" in criteria " + strCriterionName;
return false;
}
// Aggregate numerical substates
uiNumericalState |= iNumericalSubState;
}
// Set criterion new state
pCriterion->setCriterionState(uiNumericalState);
return true;
}
<commit_msg>test-platform: fix boolean remote getter commands output<commit_after>/*
* Copyright (c) 2011-2014, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <strings.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <assert.h>
#include <errno.h>
#include <convert.hpp>
#include <sstream>
#include "TestPlatform.h"
#include "ParameterMgrPlatformConnector.h"
#include "RemoteProcessorServer.h"
using std::string;
class CParameterMgrPlatformConnectorLogger : public CParameterMgrPlatformConnector::ILogger
{
public:
CParameterMgrPlatformConnectorLogger() {}
virtual void log(bool bIsWarning, const string& strLog) {
if (bIsWarning) {
std::cerr << strLog << std::endl;
} else {
std::cout << strLog << std::endl;
}
}
};
CTestPlatform::CTestPlatform(const string& strClass, int iPortNumber, sem_t& exitSemaphore) :
_pParameterMgrPlatformConnector(new CParameterMgrPlatformConnector(strClass)),
_pParameterMgrPlatformConnectorLogger(new CParameterMgrPlatformConnectorLogger),
_portNumber(iPortNumber),
_exitSemaphore(exitSemaphore)
{
_pCommandHandler = new CCommandHandler(this);
// Add command parsers
_pCommandHandler->addCommandParser("exit", &CTestPlatform::exit,
0, "", "Exit TestPlatform");
_pCommandHandler->addCommandParser(
"createExclusiveSelectionCriterionFromStateList",
&CTestPlatform::createExclusiveSelectionCriterionFromStateList,
2, "<name> <stateList>",
"Create inclusive selection criterion from state name list");
_pCommandHandler->addCommandParser(
"createInclusiveSelectionCriterionFromStateList",
&CTestPlatform::createInclusiveSelectionCriterionFromStateList,
2, "<name> <stateList>",
"Create exclusive selection criterion from state name list");
_pCommandHandler->addCommandParser(
"createExclusiveSelectionCriterion",
&CTestPlatform::createExclusiveSelectionCriterion,
2, "<name> <nbStates>", "Create inclusive selection criterion");
_pCommandHandler->addCommandParser(
"createInclusiveSelectionCriterion",
&CTestPlatform::createInclusiveSelectionCriterion,
2, "<name> <nbStates>", "Create exclusive selection criterion");
_pCommandHandler->addCommandParser("start", &CTestPlatform::startParameterMgr,
0, "", "Start ParameterMgr");
_pCommandHandler->addCommandParser("setCriterionState", &CTestPlatform::setCriterionState,
2, "<name> <state>",
"Set the current state of a selection criterion");
_pCommandHandler->addCommandParser(
"applyConfigurations",
&CTestPlatform::applyConfigurations,
0, "", "Apply configurations selected by current selection criteria states");
_pCommandHandler->addCommandParser(
"setFailureOnMissingSubsystem",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setFailureOnMissingSubsystem>,
1, "true|false", "Set policy for missing subsystems, "
"either abort start or fallback on virtual subsystem.");
_pCommandHandler->addCommandParser(
"getMissingSubsystemPolicy",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getFailureOnMissingSubsystem>,
0, "", "Get policy for missing subsystems, "
"either abort start or fallback on virtual subsystem.");
_pCommandHandler->addCommandParser(
"setFailureOnFailedSettingsLoad",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setFailureOnFailedSettingsLoad>,
1, "true|false",
"Set policy for failed settings load, either abort start or continue without domains.");
_pCommandHandler->addCommandParser(
"getFailedSettingsLoadPolicy",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getFailureOnFailedSettingsLoad>,
0, "",
"Get policy for failed settings load, either abort start or continue without domains.");
_pCommandHandler->addCommandParser(
"setValidateSchemasOnStart",
&CTestPlatform::setter<&CParameterMgrPlatformConnector::setValidateSchemasOnStart>,
1, "true|false",
"Set policy for schema validation based on .xsd files (false by default).");
_pCommandHandler->addCommandParser(
"getValidateSchemasOnStart",
&CTestPlatform::getter<&CParameterMgrPlatformConnector::getValidateSchemasOnStart>,
0, "",
"Get policy for schema validation based on .xsd files.");
// Create server
_pRemoteProcessorServer = new CRemoteProcessorServer(iPortNumber, _pCommandHandler);
_pParameterMgrPlatformConnector->setLogger(_pParameterMgrPlatformConnectorLogger);
}
CTestPlatform::~CTestPlatform()
{
delete _pRemoteProcessorServer;
delete _pCommandHandler;
delete _pParameterMgrPlatformConnectorLogger;
delete _pParameterMgrPlatformConnector;
}
CTestPlatform::CommandReturn CTestPlatform::exit(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
// Stop local server
_pRemoteProcessorServer->stop();
// Release the main blocking semaphore to quit application
sem_post(&_exitSemaphore);
return CTestPlatform::CCommandHandler::EDone;
}
bool CTestPlatform::load(std::string& strError)
{
// Start remote processor server
if (!_pRemoteProcessorServer->start()) {
std::ostringstream oss;
oss << "TestPlatform: Unable to start remote processor server on port " << _portNumber;
strError = oss.str();
return false;
}
return true;
}
//////////////// Remote command parsers
/// Selection Criterion
CTestPlatform::CommandReturn CTestPlatform::createExclusiveSelectionCriterionFromStateList(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createExclusiveSelectionCriterionFromStateList(
remoteCommand.getArgument(0), remoteCommand, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createInclusiveSelectionCriterionFromStateList(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createInclusiveSelectionCriterionFromStateList(
remoteCommand.getArgument(0), remoteCommand, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createExclusiveSelectionCriterion(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createExclusiveSelectionCriterion(
remoteCommand.getArgument(0),
strtoul(remoteCommand.getArgument(1).c_str(), NULL, 0),
strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::createInclusiveSelectionCriterion(
const IRemoteCommand& remoteCommand, string& strResult)
{
return createInclusiveSelectionCriterion(
remoteCommand.getArgument(0),
strtoul(remoteCommand.getArgument(1).c_str(), NULL, 0),
strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::startParameterMgr(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
return _pParameterMgrPlatformConnector->start(strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
template<CTestPlatform::setter_t setFunction>
CTestPlatform::CommandReturn CTestPlatform::setter(
const IRemoteCommand& remoteCommand, string& strResult)
{
const string& strAbort = remoteCommand.getArgument(0);
bool bFail;
if(!convertTo(strAbort, bFail)) {
return CTestPlatform::CCommandHandler::EShowUsage;
}
return (_pParameterMgrPlatformConnector->*setFunction)(bFail, strResult) ?
CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
template<CTestPlatform::getter_t getFunction>
CTestPlatform::CommandReturn CTestPlatform::getter(
const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
strResult = (_pParameterMgrPlatformConnector->*getFunction)() ? "true" : "false";
return CTestPlatform::CCommandHandler::ESucceeded;
}
CTestPlatform::CommandReturn CTestPlatform::setCriterionState(
const IRemoteCommand& remoteCommand, string& strResult)
{
bool bSuccess;
const char * pcState = remoteCommand.getArgument(1).c_str();
char *pcStrEnd;
// Reset errno to check if it is updated during the conversion (strtol/strtoul)
errno = 0;
uint32_t state = strtoul(pcState , &pcStrEnd, 0);
if (!errno && (*pcStrEnd == '\0')) {
// Sucessfull conversion, set criterion state by numerical state
bSuccess = setCriterionState(remoteCommand.getArgument(0), state , strResult ) ;
} else {
// Conversion failed, set criterion state by lexical state
bSuccess = setCriterionStateByLexicalSpace(remoteCommand , strResult );
}
return bSuccess ? CTestPlatform::CCommandHandler::EDone : CTestPlatform::CCommandHandler::EFailed;
}
CTestPlatform::CommandReturn CTestPlatform::applyConfigurations(const IRemoteCommand& remoteCommand, string& strResult)
{
(void)remoteCommand;
(void)strResult;
_pParameterMgrPlatformConnector->applyConfigurations();
return CTestPlatform::CCommandHandler::EDone;
}
//////////////// Remote command handlers
bool CTestPlatform::createExclusiveSelectionCriterionFromStateList(const string& strName, const IRemoteCommand& remoteCommand, string& strResult)
{
assert (_pParameterMgrPlatformConnector != NULL);
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(false);
assert(pCriterionType != NULL);
uint32_t uiNbStates = remoteCommand.getArgumentCount() - 1 ;
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
const std::string& strValue = remoteCommand.getArgument(uiState + 1);
if (!pCriterionType->addValuePair(uiState, strValue)) {
strResult = "Unable to add value: " + strValue;
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createInclusiveSelectionCriterionFromStateList(const string& strName, const IRemoteCommand& remoteCommand, string& strResult)
{
assert (_pParameterMgrPlatformConnector != NULL);
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(true);
assert(pCriterionType != NULL);
uint32_t uiNbStates = remoteCommand.getArgumentCount() - 1 ;
if (uiNbStates > 32) {
strResult = "Maximum number of states for inclusive criterion is 32";
return false;
}
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
const std::string& strValue = remoteCommand.getArgument(uiState + 1);
if (!pCriterionType->addValuePair(0x1 << uiState, strValue)) {
strResult = "Unable to add value: " + strValue;
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createExclusiveSelectionCriterion(const string& strName, uint32_t uiNbStates, string& strResult)
{
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(false);
uint32_t uistate;
for (uistate = 0; uistate < uiNbStates; uistate++) {
std::ostringstream ostrValue;
ostrValue << "State_";
ostrValue << uistate;
if (!pCriterionType->addValuePair(uistate, ostrValue.str())) {
strResult = "Unable to add value: " + ostrValue.str();
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::createInclusiveSelectionCriterion(const string& strName, uint32_t uiNbStates, string& strResult)
{
ISelectionCriterionTypeInterface* pCriterionType = _pParameterMgrPlatformConnector->createSelectionCriterionType(true);
if (uiNbStates > 32) {
strResult = "Maximum number of states for inclusive criterion is 32";
return false;
}
uint32_t uiState;
for (uiState = 0; uiState < uiNbStates; uiState++) {
std::ostringstream ostrValue;
ostrValue << "State_0x";
ostrValue << (0x1 << uiState);
if (!pCriterionType->addValuePair(0x1 << uiState, ostrValue.str())) {
strResult = "Unable to add value: " + ostrValue.str();
return false;
}
}
_pParameterMgrPlatformConnector->createSelectionCriterion(strName, pCriterionType);
return true;
}
bool CTestPlatform::setCriterionState(const string& strName, uint32_t uiState, string& strResult)
{
ISelectionCriterionInterface* pCriterion = _pParameterMgrPlatformConnector->getSelectionCriterion(strName);
if (!pCriterion) {
strResult = "Unable to retrieve selection criterion: " + strName;
return false;
}
pCriterion->setCriterionState(uiState);
return true;
}
bool CTestPlatform::setCriterionStateByLexicalSpace(const IRemoteCommand& remoteCommand, string& strResult)
{
// Get criterion name
std::string strCriterionName = remoteCommand.getArgument(0);
ISelectionCriterionInterface* pCriterion = _pParameterMgrPlatformConnector->getSelectionCriterion(strCriterionName);
if (!pCriterion) {
strResult = "Unable to retrieve selection criterion: " + strCriterionName;
return false;
}
// Get criterion type
const ISelectionCriterionTypeInterface* pCriterionType = pCriterion->getCriterionType();
// Get substate number, the first argument (index 0) is the criterion name
uint32_t uiNbSubStates = remoteCommand.getArgumentCount() - 1;
// Check that exclusive criterion has only one substate
if (!pCriterionType->isTypeInclusive() && uiNbSubStates != 1) {
strResult = "Exclusive criterion " + strCriterionName + " can only have one state";
return false;
}
/// Translate lexical state to numerical state
uint32_t uiNumericalState = 0;
uint32_t uiLexicalSubStateIndex;
// Parse lexical substates
for (uiLexicalSubStateIndex = 1; uiLexicalSubStateIndex <= uiNbSubStates; uiLexicalSubStateIndex++) {
int iNumericalSubState;
const std::string& strLexicalSubState = remoteCommand.getArgument(uiLexicalSubStateIndex);
// Translate lexical to numerical substate
if (!pCriterionType->getNumericalValue(strLexicalSubState, iNumericalSubState)) {
strResult = "Unable to find lexical state \"" + strLexicalSubState + "\" in criteria " + strCriterionName;
return false;
}
// Aggregate numerical substates
uiNumericalState |= iNumericalSubState;
}
// Set criterion new state
pCriterion->setCriterionState(uiNumericalState);
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "../src/exception.h"
#include "../src/index.h"
void misc_test() {
{ // empty node checksum
const std::string fname = "/tmp/misc_bdt";
if (LeviDB::IOEnv::fileExists(fname)) {
LeviDB::IOEnv::deleteFile(fname);
}
{
LeviDB::BitDegradeTree bdt(fname);
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.insert({reinterpret_cast<char *>(&val), sizeof(val)}, {val});
}
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.remove({reinterpret_cast<char *>(&val), sizeof(val)});
}
}
{
LeviDB::RandomWriteFile rwf(fname);
rwf.write(4097, "6");
}
LeviDB::BitDegradeTree bdt(fname, LeviDB::OffsetToEmpty{4096});
try {
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.insert({reinterpret_cast<char *>(&val), sizeof(val)}, {val});
}
assert(false);
} catch (const LeviDB::Exception & e) {
}
}
std::cout << __FUNCTION__ << std::endl;
}<commit_msg>ob mode usr<commit_after>#include <iostream>
#include "../src/exception.h"
#include "../src/index.h"
void misc_test() {
{ // empty node checksum
const std::string fname = "/tmp/misc_bdt";
if (LeviDB::IOEnv::fileExists(fname)) {
LeviDB::IOEnv::deleteFile(fname);
}
{
LeviDB::BitDegradeTree bdt(fname);
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.insert({reinterpret_cast<char *>(&val), sizeof(val)}, {val});
}
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.remove({reinterpret_cast<char *>(&val), sizeof(val)});
}
}
{
LeviDB::RandomWriteFile rwf(fname);
rwf.write(4097, "6");
}
LeviDB::BitDegradeTree bdt(fname, LeviDB::OffsetToEmpty{4096});
try {
for (int i = 0; i < LeviDB::IndexConst::rank_ * 2 + 3; i += 2) {
auto val = static_cast<uint32_t>(i);
bdt.insert({reinterpret_cast<char *>(&val), sizeof(val)}, {val});
}
assert(false);
} catch (const LeviDB::Exception & e) {
}
}
{ // ob mode usr
std::string model = "ABC";
LeviDB::USR u(&model);
LeviDB::USR u2(model);
assert(u.toSlice() == u2.toSlice());
}
std::cout << __FUNCTION__ << std::endl;
}<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <iostream>
#include <boost/algorithm/string/replace.hpp>
#include <iomanip>
#include <bh_instruction.hpp>
#include <bh_component.hpp>
#include <jitk/symbol_table.hpp>
#include "engine_cuda.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace bohrium {
EngineCUDA::EngineCUDA(const ConfigParser &config, jitk::Statistics &stat) :
EngineGPU(config, stat),
work_group_size_1dx(config.defaultGet<int>("work_group_size_1dx", 128)),
work_group_size_2dx(config.defaultGet<int>("work_group_size_2dx", 32)),
work_group_size_2dy(config.defaultGet<int>("work_group_size_2dy", 4)),
work_group_size_3dx(config.defaultGet<int>("work_group_size_3dx", 32)),
work_group_size_3dy(config.defaultGet<int>("work_group_size_3dy", 2)),
work_group_size_3dz(config.defaultGet<int>("work_group_size_3dz", 2))
{
int deviceCount = 0;
CUresult err = cuInit(0);
if (err == CUDA_SUCCESS)
check_cuda_errors(cuDeviceGetCount(&deviceCount));
if (deviceCount == 0) {
throw runtime_error("Error: no devices supporting CUDA");
}
// get first CUDA device
check_cuda_errors(cuDeviceGet(&device, 0));
err = cuCtxCreate(&context, 0, device);
if (err != CUDA_SUCCESS) {
cuCtxDetach(context);
throw runtime_error("Error initializing the CUDA context.");
}
// Let's make sure that the directories exist
jitk::create_directories(tmp_src_dir);
jitk::create_directories(tmp_bin_dir);
if (not cache_bin_dir.empty()) {
jitk::create_directories(cache_bin_dir);
}
// Write the compilation hash
compilation_hash = util::hash(info());
// Get the compiler command and replace {MAJOR} and {MINOR} with the SM versions
string compiler_cmd = config.get<string>("compiler_cmd");
int major = 0, minor = 0;
check_cuda_errors(cuDeviceComputeCapability(&major, &minor, device));
boost::replace_all(compiler_cmd, "{MAJOR}", std::to_string(major));
boost::replace_all(compiler_cmd, "{MINOR}", std::to_string(minor));
// Init the compiler
compiler = jitk::Compiler(compiler_cmd, verbose, config.file_dir.string());
}
EngineCUDA::~EngineCUDA() {
cuCtxDetach(context);
// Move JIT kernels to the cache dir
if (not cache_bin_dir.empty()) {
try {
for (const auto &kernel: _functions) {
const fs::path src = tmp_bin_dir / jitk::hash_filename(compilation_hash, kernel.first, ".cubin");
if (fs::exists(src)) {
const fs::path dst = cache_bin_dir / jitk::hash_filename(compilation_hash, kernel.first, ".cubin");
if (not fs::exists(dst)) {
fs::copy_file(src, dst);
}
}
}
} catch (const boost::filesystem::filesystem_error &e) {
cout << "Warning: couldn't write CUDA kernels to disk to " << cache_bin_dir
<< ". " << e.what() << endl;
}
}
// File clean up
if (not verbose) {
fs::remove_all(tmp_src_dir);
}
if (cache_file_max != -1 and not cache_bin_dir.empty()) {
util::remove_old_files(cache_bin_dir, cache_file_max);
}
}
pair<tuple<uint32_t, uint32_t, uint32_t>, tuple<uint32_t, uint32_t, uint32_t> >
EngineCUDA::NDRanges(const vector<uint64_t> &thread_stack) const {
const auto &b = thread_stack;
switch (b.size()) {
case 1: {
const auto gsize_and_lsize = jitk::work_ranges(work_group_size_1dx, b[0]);
return make_pair(make_tuple(gsize_and_lsize.first, 1, 1), make_tuple(gsize_and_lsize.second, 1, 1));
}
case 2: {
const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_2dx, b[0]);
const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_2dy, b[1]);
return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, 1),
make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, 1));
}
case 3: {
const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_3dx, b[0]);
const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_3dy, b[1]);
const auto gsize_and_lsize_z = jitk::work_ranges(work_group_size_3dz, b[2]);
return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, gsize_and_lsize_z.first),
make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, gsize_and_lsize_z.second));
}
default:
throw runtime_error("NDRanges: maximum of three dimensions!");
}
}
CUfunction EngineCUDA::getFunction(const string &source, const std::string &func_name) {
uint64_t hash = util::hash(source);
++stat.kernel_cache_lookups;
// Do we have the program already?
if (_functions.find(hash) != _functions.end()) {
return _functions.at(hash);
}
fs::path binfile = cache_bin_dir / jitk::hash_filename(compilation_hash, hash, ".cubin");
// If the binary file of the kernel doesn't exist we create it
if (verbose or cache_bin_dir.empty() or not fs::exists(binfile)) {
++stat.kernel_cache_misses;
// We create the binary file in the tmp dir
binfile = tmp_bin_dir / jitk::hash_filename(compilation_hash, hash, ".cubin");
// Write the source file and compile it (reading from disk)
// TODO: make nvcc read directly from stdin
{
std::string kernel_filename = jitk::hash_filename(compilation_hash, hash, ".cu");
fs::path srcfile = jitk::write_source2file(source, tmp_src_dir,
kernel_filename, verbose);
compiler.compile(binfile.string(), srcfile.string());
}
/* else {
// Pipe the source directly into the compiler thus no source file is written
compiler.compile(binfile.string(), source.c_str(), source.size());
}
*/
}
CUmodule module;
CUresult err = cuModuleLoad(&module, binfile.string().c_str());
if (err != CUDA_SUCCESS) {
const char *err_name, *err_desc;
cuGetErrorName(err, &err_name);
cuGetErrorString(err, &err_desc);
cout << "Error loading the module \"" << binfile.string()
<< "\", " << err_name << ": \"" << err_desc << "\"." << endl;
cuCtxDetach(context);
throw runtime_error("cuModuleLoad() failed");
}
CUfunction program;
err = cuModuleGetFunction(&program, module, func_name.c_str());
if (err != CUDA_SUCCESS) {
const char *err_name, *err_desc;
cuGetErrorName(err, &err_name);
cuGetErrorString(err, &err_desc);
cout << "Error getting kernel function 'execute' \"" << binfile.string()
<< "\", " << err_name << ": \"" << err_desc << "\"." << endl;
throw runtime_error("cuModuleGetFunction() failed");
}
_functions[hash] = program;
return program;
}
void EngineCUDA::writeKernel(const jitk::Block &block,
const jitk::SymbolTable &symbols,
const std::vector<uint64_t> &thread_stack,
uint64_t codegen_hash,
std::stringstream &ss) {
// Write the need includes
ss << "#include <kernel_dependencies/complex_cuda.h>\n";
ss << "#include <kernel_dependencies/integer_operations.h>\n";
if (symbols.useRandom()) { // Write the random function
ss << "#include <kernel_dependencies/random123_cuda.h>\n";
}
ss << "\n";
// Write the header of the execute function
ss << "extern \"C\" __global__ void execute_" << codegen_hash;
writeKernelFunctionArguments(symbols, ss, nullptr);
ss << " {\n";
// Write the IDs of the threaded blocks
if (not thread_stack.empty()) {
util::spaces(ss, 4);
ss << "// The IDs of the threaded blocks: \n";
for (unsigned int i=0; i < thread_stack.size(); ++i) {
util::spaces(ss, 4);
ss << "const " << writeType(bh_type::INT64) << " i" << i << " = " << writeThreadId(i) << "; "
<< "if (i" << i << " >= " << thread_stack[i] << ") { return; } // Prevent overflow\n";
}
ss << "\n";
}
writeLoopBlock(symbols, nullptr, block.getLoop(), thread_stack, true, ss);
ss << "}\n\n";
}
void EngineCUDA::execute(const jitk::SymbolTable &symbols,
const std::string &source,
uint64_t codegen_hash,
const vector<uint64_t> &thread_stack,
const vector<const bh_instruction*> &constants) {
uint64_t hash = util::hash(source);
std::string source_filename = jitk::hash_filename(compilation_hash, hash, ".cu");
auto tcompile = chrono::steady_clock::now();
string func_name; { stringstream t; t << "execute_" << codegen_hash; func_name = t.str(); }
CUfunction program = getFunction(source, func_name);
stat.time_compile += chrono::steady_clock::now() - tcompile;
// Let's execute the CUDA kernel
vector<void *> args;
for (bh_base *base: symbols.getParams()) { // NB: the iteration order matters!
args.push_back(getBuffer(base));
}
for (const bh_view *view: symbols.offsetStrideViews()) {
args.push_back((void*)&view->start);
for (int j=0; j<view->ndim; ++j) {
args.push_back((void*)&view->stride[j]);
}
}
auto exec_start = chrono::steady_clock::now();
tuple<uint32_t, uint32_t, uint32_t> blocks, threads;
tie(blocks, threads) = NDRanges(thread_stack);
check_cuda_errors(cuLaunchKernel(program,
get<0>(blocks), get<1>(blocks), get<2>(blocks), // NxNxN blocks
get<0>(threads), get<1>(threads), get<2>(threads), // NxNxN threads
0, 0, &args[0], 0));
check_cuda_errors(cuCtxSynchronize());
auto texec = chrono::steady_clock::now() - exec_start;
stat.time_exec += texec;
stat.time_per_kernel[source_filename].register_exec_time(texec);
}
void EngineCUDA::setConstructorFlag(std::vector<bh_instruction*> &instr_list) {
jitk::util_set_constructor_flag(instr_list, buffers);
}
std::string EngineCUDA::info() const {
char device_name[1000];
cuDeviceGetName(device_name, 1000, device);
int major = 0, minor = 0;
check_cuda_errors(cuDeviceComputeCapability(&major, &minor, device));
size_t totalGlobalMem;
check_cuda_errors(cuDeviceTotalMem(&totalGlobalMem, device));
stringstream ss;
ss << "----" << "\n";
ss << "CUDA:" << "\n";
ss << " Device: \"" << device_name << " (SM " << major << "." << minor << " compute capability)\"\n";
ss << " Memory: \"" << totalGlobalMem / 1024 / 1024 << " MB\"\n";
ss << " JIT Command: \"" << compiler.cmd_template << "\"\n";
return ss.str();
}
} // bohrium
<commit_msg>clean up: reformat<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include <iostream>
#include <boost/algorithm/string/replace.hpp>
#include <iomanip>
#include <bh_instruction.hpp>
#include <bh_component.hpp>
#include <jitk/symbol_table.hpp>
#include "engine_cuda.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace bohrium {
EngineCUDA::EngineCUDA(const ConfigParser &config, jitk::Statistics &stat) :
EngineGPU(config, stat),
work_group_size_1dx(config.defaultGet<int>("work_group_size_1dx", 128)),
work_group_size_2dx(config.defaultGet<int>("work_group_size_2dx", 32)),
work_group_size_2dy(config.defaultGet<int>("work_group_size_2dy", 4)),
work_group_size_3dx(config.defaultGet<int>("work_group_size_3dx", 32)),
work_group_size_3dy(config.defaultGet<int>("work_group_size_3dy", 2)),
work_group_size_3dz(config.defaultGet<int>("work_group_size_3dz", 2)) {
int deviceCount = 0;
CUresult err = cuInit(0);
if (err == CUDA_SUCCESS)
check_cuda_errors(cuDeviceGetCount(&deviceCount));
if (deviceCount == 0) {
throw runtime_error("Error: no devices supporting CUDA");
}
// get first CUDA device
check_cuda_errors(cuDeviceGet(&device, 0));
err = cuCtxCreate(&context, 0, device);
if (err != CUDA_SUCCESS) {
cuCtxDetach(context);
throw runtime_error("Error initializing the CUDA context.");
}
// Let's make sure that the directories exist
jitk::create_directories(tmp_src_dir);
jitk::create_directories(tmp_bin_dir);
if (not cache_bin_dir.empty()) {
jitk::create_directories(cache_bin_dir);
}
// Write the compilation hash
compilation_hash = util::hash(info());
// Get the compiler command and replace {MAJOR} and {MINOR} with the SM versions
string compiler_cmd = config.get<string>("compiler_cmd");
int major = 0, minor = 0;
check_cuda_errors(cuDeviceComputeCapability(&major, &minor, device));
boost::replace_all(compiler_cmd, "{MAJOR}", std::to_string(major));
boost::replace_all(compiler_cmd, "{MINOR}", std::to_string(minor));
// Init the compiler
compiler = jitk::Compiler(compiler_cmd, verbose, config.file_dir.string());
}
EngineCUDA::~EngineCUDA() {
cuCtxDetach(context);
// Move JIT kernels to the cache dir
if (not cache_bin_dir.empty()) {
try {
for (const auto &kernel: _functions) {
const fs::path src = tmp_bin_dir / jitk::hash_filename(compilation_hash, kernel.first, ".cubin");
if (fs::exists(src)) {
const fs::path dst = cache_bin_dir / jitk::hash_filename(compilation_hash, kernel.first, ".cubin");
if (not fs::exists(dst)) {
fs::copy_file(src, dst);
}
}
}
} catch (const boost::filesystem::filesystem_error &e) {
cout << "Warning: couldn't write CUDA kernels to disk to " << cache_bin_dir
<< ". " << e.what() << endl;
}
}
// File clean up
if (not verbose) {
fs::remove_all(tmp_src_dir);
}
if (cache_file_max != -1 and not cache_bin_dir.empty()) {
util::remove_old_files(cache_bin_dir, cache_file_max);
}
}
pair<tuple<uint32_t, uint32_t, uint32_t>, tuple<uint32_t, uint32_t, uint32_t> >
EngineCUDA::NDRanges(const vector<uint64_t> &thread_stack) const {
const auto &b = thread_stack;
switch (b.size()) {
case 1: {
const auto gsize_and_lsize = jitk::work_ranges(work_group_size_1dx, b[0]);
return make_pair(make_tuple(gsize_and_lsize.first, 1, 1), make_tuple(gsize_and_lsize.second, 1, 1));
}
case 2: {
const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_2dx, b[0]);
const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_2dy, b[1]);
return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, 1),
make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, 1));
}
case 3: {
const auto gsize_and_lsize_x = jitk::work_ranges(work_group_size_3dx, b[0]);
const auto gsize_and_lsize_y = jitk::work_ranges(work_group_size_3dy, b[1]);
const auto gsize_and_lsize_z = jitk::work_ranges(work_group_size_3dz, b[2]);
return make_pair(make_tuple(gsize_and_lsize_x.first, gsize_and_lsize_y.first, gsize_and_lsize_z.first),
make_tuple(gsize_and_lsize_x.second, gsize_and_lsize_y.second, gsize_and_lsize_z.second));
}
default:
throw runtime_error("NDRanges: maximum of three dimensions!");
}
}
CUfunction EngineCUDA::getFunction(const string &source, const std::string &func_name) {
uint64_t hash = util::hash(source);
++stat.kernel_cache_lookups;
// Do we have the program already?
if (_functions.find(hash) != _functions.end()) {
return _functions.at(hash);
}
fs::path binfile = cache_bin_dir / jitk::hash_filename(compilation_hash, hash, ".cubin");
// If the binary file of the kernel doesn't exist we create it
if (verbose or cache_bin_dir.empty() or not fs::exists(binfile)) {
++stat.kernel_cache_misses;
// We create the binary file in the tmp dir
binfile = tmp_bin_dir / jitk::hash_filename(compilation_hash, hash, ".cubin");
// Write the source file and compile it (reading from disk)
// TODO: make nvcc read directly from stdin
{
std::string kernel_filename = jitk::hash_filename(compilation_hash, hash, ".cu");
fs::path srcfile = jitk::write_source2file(source, tmp_src_dir,
kernel_filename, verbose);
compiler.compile(binfile.string(), srcfile.string());
}
/* else {
// Pipe the source directly into the compiler thus no source file is written
compiler.compile(binfile.string(), source.c_str(), source.size());
}
*/
}
CUmodule module;
CUresult err = cuModuleLoad(&module, binfile.string().c_str());
if (err != CUDA_SUCCESS) {
const char *err_name, *err_desc;
cuGetErrorName(err, &err_name);
cuGetErrorString(err, &err_desc);
cout << "Error loading the module \"" << binfile.string()
<< "\", " << err_name << ": \"" << err_desc << "\"." << endl;
cuCtxDetach(context);
throw runtime_error("cuModuleLoad() failed");
}
CUfunction program;
err = cuModuleGetFunction(&program, module, func_name.c_str());
if (err != CUDA_SUCCESS) {
const char *err_name, *err_desc;
cuGetErrorName(err, &err_name);
cuGetErrorString(err, &err_desc);
cout << "Error getting kernel function 'execute' \"" << binfile.string()
<< "\", " << err_name << ": \"" << err_desc << "\"." << endl;
throw runtime_error("cuModuleGetFunction() failed");
}
_functions[hash] = program;
return program;
}
void EngineCUDA::writeKernel(const jitk::Block &block,
const jitk::SymbolTable &symbols,
const std::vector<uint64_t> &thread_stack,
uint64_t codegen_hash,
std::stringstream &ss) {
// Write the need includes
ss << "#include <kernel_dependencies/complex_cuda.h>\n";
ss << "#include <kernel_dependencies/integer_operations.h>\n";
if (symbols.useRandom()) { // Write the random function
ss << "#include <kernel_dependencies/random123_cuda.h>\n";
}
ss << "\n";
// Write the header of the execute function
ss << "extern \"C\" __global__ void execute_" << codegen_hash;
writeKernelFunctionArguments(symbols, ss, nullptr);
ss << " {\n";
// Write the IDs of the threaded blocks
if (not thread_stack.empty()) {
util::spaces(ss, 4);
ss << "// The IDs of the threaded blocks: \n";
for (unsigned int i = 0; i < thread_stack.size(); ++i) {
util::spaces(ss, 4);
ss << "const " << writeType(bh_type::INT64) << " i" << i << " = " << writeThreadId(i) << "; "
<< "if (i" << i << " >= " << thread_stack[i] << ") { return; } // Prevent overflow\n";
}
ss << "\n";
}
writeLoopBlock(symbols, nullptr, block.getLoop(), thread_stack, true, ss);
ss << "}\n\n";
}
void EngineCUDA::execute(const jitk::SymbolTable &symbols,
const std::string &source,
uint64_t codegen_hash,
const vector<uint64_t> &thread_stack,
const vector<const bh_instruction *> &constants) {
uint64_t hash = util::hash(source);
std::string source_filename = jitk::hash_filename(compilation_hash, hash, ".cu");
auto tcompile = chrono::steady_clock::now();
string func_name;
{
stringstream t;
t << "execute_" << codegen_hash;
func_name = t.str();
}
CUfunction program = getFunction(source, func_name);
stat.time_compile += chrono::steady_clock::now() - tcompile;
// Let's execute the CUDA kernel
vector<void *> args;
for (bh_base *base: symbols.getParams()) { // NB: the iteration order matters!
args.push_back(getBuffer(base));
}
for (const bh_view *view: symbols.offsetStrideViews()) {
args.push_back((void *) &view->start);
for (int j = 0; j < view->ndim; ++j) {
args.push_back((void *) &view->stride[j]);
}
}
auto exec_start = chrono::steady_clock::now();
tuple<uint32_t, uint32_t, uint32_t> blocks, threads;
tie(blocks, threads) = NDRanges(thread_stack);
check_cuda_errors(cuLaunchKernel(program,
get<0>(blocks), get<1>(blocks), get<2>(blocks), // NxNxN blocks
get<0>(threads), get<1>(threads), get<2>(threads), // NxNxN threads
0, 0, &args[0], 0));
check_cuda_errors(cuCtxSynchronize());
auto texec = chrono::steady_clock::now() - exec_start;
stat.time_exec += texec;
stat.time_per_kernel[source_filename].register_exec_time(texec);
}
void EngineCUDA::setConstructorFlag(std::vector<bh_instruction *> &instr_list) {
jitk::util_set_constructor_flag(instr_list, buffers);
}
std::string EngineCUDA::info() const {
char device_name[1000];
cuDeviceGetName(device_name, 1000, device);
int major = 0, minor = 0;
check_cuda_errors(cuDeviceComputeCapability(&major, &minor, device));
size_t totalGlobalMem;
check_cuda_errors(cuDeviceTotalMem(&totalGlobalMem, device));
stringstream ss;
ss << "----" << "\n";
ss << "CUDA:" << "\n";
ss << " Device: \"" << device_name << " (SM " << major << "." << minor << " compute capability)\"\n";
ss << " Memory: \"" << totalGlobalMem / 1024 / 1024 << " MB\"\n";
ss << " JIT Command: \"" << compiler.cmd_template << "\"\n";
return ss.str();
}
} // bohrium
<|endoftext|> |
<commit_before>/*
Copyright (C) 2007 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <bmuller@butterfat.net>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
void debug(string s) {
#ifdef DEBUG
print_to_error_log(s);
#endif
};
void print_to_error_log(string s) {
string time_s = "";
time_t rawtime = time(NULL);
tm *tm_t = localtime(&rawtime);
char rv[40];
if(strftime(rv, sizeof(rv)-1, "%a %b %d %H:%M:%S %Y", tm_t))
time_s = "[" + string(rv) + "] ";
s = time_s + "[" + string(PACKAGE_NAME) + "] " + s + "\n";
// escape %'s
string cleaned_s = "";
vector<string> parts = explode(s, "%");
for(unsigned int i=0; i<parts.size()-1; i++)
cleaned_s += parts[i] + "%%";
cleaned_s += parts[parts.size()-1];
// stderr is redirected by apache to apache's error log
fprintf(stderr, cleaned_s.c_str());
fflush(stderr);
};
// get a descriptive string for an error; a short string is used as a GET param
// value in the style of OpenID get params - short, no space, ...
string error_to_string(error_result_t e, bool use_short_string) {
string short_string, long_string;
switch(e) {
case no_idp_found:
short_string = "no_idp_found";
long_string = "There was either no identity provider found at the identity URL given"
" or there was trouble connecting to it.";
break;
case invalid_id_url:
short_string = "invalid_id_url";
long_string = "The identity URL given is not a valid URL.";
break;
case idp_not_trusted:
short_string = "idp_not_trusted";
long_string = "The identity provider for the identity URL given is not trusted.";
break;
case invalid_nonce:
short_string = "invalid_nonce";
long_string = "Invalid nonce; error while authenticating.";
break;
case canceled:
short_string = "canceled";
long_string = "Identification process has been canceled.";
break;
default: // unspecified
short_string = "unspecified";
long_string = "There has been an error while attempting to authenticate.";
break;
}
return (use_short_string) ? short_string : long_string;
}
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_queryless_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('?', 8);
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
}
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_base_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('/', 8);
string::size_type last_q = url.find('?', 8);
if(last==string::npos || (last_q<last && last_q!=string::npos))
last = last_q;
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
}
params_t remove_openid_vars(params_t params) {
map<string,string>::iterator iter;
for(iter = params.begin(); iter != params.end(); iter++) {
string param_key(iter->first);
if(param_key.substr(0, 7) == "openid.") {
params.erase(param_key);
// stupid map iterator screws up if we just continue the iteration...
// so recursion to the rescue - we'll delete them one at a time
return remove_openid_vars(params);
}
}
return params;
}
bool is_valid_url(string url) {
// taken from http://www.osix.net/modules/article/?id=586
string regex = "^(https?://)"
"(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP- 199.194.52.184
"|" // allows either IP or domain or "localhost"
"localhost"
"|"
"([0-9a-z_!~*'()-]+\\.)*" // tertiary domain(s)- www.
"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // second level domain
"[a-z]{2,6})" // first level domain- .com or .museum
"(:[0-9]{1,4})?" // port number- :80
"((/?)|" // a slash isn't required if there is no file name
"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
return regex_match(url, regex);
}
// This isn't a true html_escape function, but rather escapes just enough to get by for
// quoted values - <blah name="stuff to be escaped">
string html_escape(string s) {
s = str_replace("\"", """, s);
s = str_replace("<", "<", s);
s = str_replace(">", ">", s);
return s;
}
string str_replace(string needle, string replacement, string haystack) {
vector<string> v = explode(haystack, needle);
string r = "";
for(vector<string>::size_type i=0; i < v.size()-1; i++)
r += v[i] + replacement;
r += v[v.size()-1];
return r;
}
vector<string> explode(string s, string e) {
vector<string> ret;
int iPos = s.find(e, 0);
int iPit = e.length();
while(iPos>-1) {
if(iPos!=0)
ret.push_back(s.substr(0,iPos));
s.erase(0,iPos+iPit);
iPos = s.find(e, 0);
}
if(s!="")
ret.push_back(s);
return ret;
}
string url_decode(const string& str) {
char * t = curl_unescape(str.c_str(),str.length());
if(!t)
throw failed_conversion(OPKELE_CP_ "failed to curl_unescape()");
string rv(t);
curl_free(t);
return rv;
}
params_t parse_query_string(const string& str) {
params_t p;
if(str.size() == 0) return p;
vector<string> pairs = explode(str, "&");
for(unsigned int i=0; i < pairs.size(); i++) {
string::size_type loc = pairs[i].find( "=", 0 );
// if loc found and loc isn't last char in string
if( loc != string::npos && loc != str.size()-1) {
string key = url_decode(pairs[i].substr(0, loc));
string value = url_decode(pairs[i].substr(loc+1));
p[key] = value;
}
}
return p;
}
void make_cookie_value(string& cookie_value, const string& name, const string& session_id, const string& path, int cookie_lifespan) {
if(cookie_lifespan == 0) {
cookie_value = name + "=" + session_id + "; path=" + path;
} else {
time_t t;
t = time(NULL) + cookie_lifespan;
struct tm *tmp;
tmp = gmtime(&t);
char expires[200];
strftime(expires, sizeof(expires), "%a, %d-%b-%Y %H:%M:%S GMT", tmp);
cookie_value = name + "=" + session_id + "; expires=" + string(expires) + "; path=" + path;
}
}
void int_to_string(int i, string& s) {
char c_int[100];
sprintf(c_int, "%ld", i);
s = string(c_int);
}
bool regex_match(string subject, string pattern) {
const char * error;
int erroffset;
pcre * re = pcre_compile(pattern.c_str(), 0, &error, &erroffset, NULL);
if (re == NULL) {
print_to_error_log("regex compilation failed for regex \"" + pattern + "\": " + error);
return false;
}
return (pcre_exec(re, NULL, subject.c_str(), subject.size(), 0, 0, NULL, 0) >= 0);
};
}
<commit_msg>fixed bug #1<commit_after>/*
Copyright (C) 2007 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <bmuller@butterfat.net>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
void debug(string s) {
#ifdef DEBUG
print_to_error_log(s);
#endif
};
void print_to_error_log(string s) {
string time_s = "";
time_t rawtime = time(NULL);
tm *tm_t = localtime(&rawtime);
char rv[40];
if(strftime(rv, sizeof(rv)-1, "%a %b %d %H:%M:%S %Y", tm_t))
time_s = "[" + string(rv) + "] ";
s = time_s + "[" + string(PACKAGE_NAME) + "] " + s + "\n";
// escape %'s
string cleaned_s = "";
vector<string> parts = explode(s, "%");
for(unsigned int i=0; i<parts.size()-1; i++)
cleaned_s += parts[i] + "%%";
cleaned_s += parts[parts.size()-1];
// stderr is redirected by apache to apache's error log
fprintf(stderr, cleaned_s.c_str());
fflush(stderr);
};
// get a descriptive string for an error; a short string is used as a GET param
// value in the style of OpenID get params - short, no space, ...
string error_to_string(error_result_t e, bool use_short_string) {
string short_string, long_string;
switch(e) {
case no_idp_found:
short_string = "no_idp_found";
long_string = "There was either no identity provider found at the identity URL given"
" or there was trouble connecting to it.";
break;
case invalid_id_url:
short_string = "invalid_id_url";
long_string = "The identity URL given is not a valid URL.";
break;
case idp_not_trusted:
short_string = "idp_not_trusted";
long_string = "The identity provider for the identity URL given is not trusted.";
break;
case invalid_nonce:
short_string = "invalid_nonce";
long_string = "Invalid nonce; error while authenticating.";
break;
case canceled:
short_string = "canceled";
long_string = "Identification process has been canceled.";
break;
default: // unspecified
short_string = "unspecified";
long_string = "There has been an error while attempting to authenticate.";
break;
}
return (use_short_string) ? short_string : long_string;
}
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_queryless_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('?', 8);
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
}
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_base_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('/', 8);
string::size_type last_q = url.find('?', 8);
if(last==string::npos || (last_q<last && last_q!=string::npos))
last = last_q;
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
}
params_t remove_openid_vars(params_t params) {
map<string,string>::iterator iter;
for(iter = params.begin(); iter != params.end(); iter++) {
string param_key(iter->first);
if(param_key.substr(0, 7) == "openid."
&& param_key.substr(0, 10) != "openid.ax."
&& param_key.substr(0, 12) != "openid.sreg.") {
params.erase(param_key);
// stupid map iterator screws up if we just continue the iteration...
// so recursion to the rescue - we'll delete them one at a time
return remove_openid_vars(params);
}
}
return params;
}
bool is_valid_url(string url) {
// taken from http://www.osix.net/modules/article/?id=586
string regex = "^(https?://)"
"(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP- 199.194.52.184
"|" // allows either IP or domain or "localhost"
"localhost"
"|"
"([0-9a-z_!~*'()-]+\\.)*" // tertiary domain(s)- www.
"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // second level domain
"[a-z]{2,6})" // first level domain- .com or .museum
"(:[0-9]{1,4})?" // port number- :80
"((/?)|" // a slash isn't required if there is no file name
"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
return regex_match(url, regex);
}
// This isn't a true html_escape function, but rather escapes just enough to get by for
// quoted values - <blah name="stuff to be escaped">
string html_escape(string s) {
s = str_replace("\"", """, s);
s = str_replace("<", "<", s);
s = str_replace(">", ">", s);
return s;
}
string str_replace(string needle, string replacement, string haystack) {
vector<string> v = explode(haystack, needle);
string r = "";
for(vector<string>::size_type i=0; i < v.size()-1; i++)
r += v[i] + replacement;
r += v[v.size()-1];
return r;
}
vector<string> explode(string s, string e) {
vector<string> ret;
int iPos = s.find(e, 0);
int iPit = e.length();
while(iPos>-1) {
if(iPos!=0)
ret.push_back(s.substr(0,iPos));
s.erase(0,iPos+iPit);
iPos = s.find(e, 0);
}
if(s!="")
ret.push_back(s);
return ret;
}
string url_decode(const string& str) {
char * t = curl_unescape(str.c_str(),str.length());
if(!t)
throw failed_conversion(OPKELE_CP_ "failed to curl_unescape()");
string rv(t);
curl_free(t);
return rv;
}
params_t parse_query_string(const string& str) {
params_t p;
if(str.size() == 0) return p;
vector<string> pairs = explode(str, "&");
for(unsigned int i=0; i < pairs.size(); i++) {
string::size_type loc = pairs[i].find( "=", 0 );
// if loc found and loc isn't last char in string
if( loc != string::npos && loc != str.size()-1) {
string key = url_decode(pairs[i].substr(0, loc));
string value = url_decode(pairs[i].substr(loc+1));
p[key] = value;
}
}
return p;
}
void make_cookie_value(string& cookie_value, const string& name, const string& session_id, const string& path, int cookie_lifespan) {
if(cookie_lifespan == 0) {
cookie_value = name + "=" + session_id + "; path=" + path;
} else {
time_t t;
t = time(NULL) + cookie_lifespan;
struct tm *tmp;
tmp = gmtime(&t);
char expires[200];
strftime(expires, sizeof(expires), "%a, %d-%b-%Y %H:%M:%S GMT", tmp);
cookie_value = name + "=" + session_id + "; expires=" + string(expires) + "; path=" + path;
}
}
void int_to_string(int i, string& s) {
char c_int[100];
sprintf(c_int, "%ld", i);
s = string(c_int);
}
bool regex_match(string subject, string pattern) {
const char * error;
int erroffset;
pcre * re = pcre_compile(pattern.c_str(), 0, &error, &erroffset, NULL);
if (re == NULL) {
print_to_error_log("regex compilation failed for regex \"" + pattern + "\": " + error);
return false;
}
return (pcre_exec(re, NULL, subject.c_str(), subject.size(), 0, 0, NULL, 0) >= 0);
};
}
<|endoftext|> |
<commit_before>#ifndef PYTHONIC_UTILS_NESTED_CONTAINER_HPP
#define PYTHONIC_UTILS_NESTED_CONTAINER_HPP
#include <limits>
#include "pythonic/types/traits.hpp"
namespace pythonic {
namespace types { class str; }
namespace utils {
/* compute nested container depth and memory size*/
template<class T, bool next = types::is_iterable<typename std::remove_reference<T>::type>::value>
struct nested_container_depth {
static const int value = 1 + nested_container_depth<typename std::remove_reference<T>::type::value_type>::value;
};
template<class T>
struct nested_container_depth<T, false> {
static const int value = 0;
};
template<> // need for str, as str iterates over... str
struct nested_container_depth<types::str, true> {
static const int value = 0;
};
/* Get the size of a container, using recursion on inner container if any
* FIXME: should be a constexpr?
* FIXME: why a class and not a function?
*/
template<class T>
struct nested_container_size {
typedef typename std::remove_cv<typename std::remove_reference<T>::type>::type Type;
static size_t flat_size(T const& t) {
return t.size()
*
nested_container_size<
typename std::conditional<
// If we have a scalar of a complex, we want to stop
// recursion, and then dispatch to bool specialization
std::is_scalar<typename Type::value_type>::value
or types::is_complex<typename Type::value_type>::value,
bool,
typename Type::value_type
>::type
>::flat_size(*t.begin());
}
};
/* Recursion stops on bool */
template<>
struct nested_container_size<bool> {
template<class F>
static size_t flat_size(F) { return 1; }
};
/* Statically define (by recursion) the type of element inside nested constainers */
template<class T, size_t end=nested_container_depth<T>::value>
struct nested_container_value_type {
typedef typename nested_container_value_type<typename T::value_type, ((std::is_scalar<typename T::value_type>::value or types::is_complex<typename T::value_type>::value)?0:end-1)>::type type;
};
template<class T>
struct nested_container_value_type<T,0> {
typedef T type;
};
}
}
#endif
<commit_msg>Simplify the nested_container mechanics<commit_after>#ifndef PYTHONIC_UTILS_NESTED_CONTAINER_HPP
#define PYTHONIC_UTILS_NESTED_CONTAINER_HPP
#include <limits>
#include "pythonic/types/traits.hpp"
#include "pythonic/utils/numpy_traits.hpp"
namespace pythonic {
namespace types {
template<class T> class list;
template<class T, size_t N> struct array;
}
namespace utils {
/* compute nested container depth and memory size*/
template<class T, bool IsArray> struct nested_container_depth_helper;
template<class T> struct nested_container_depth_helper<T, false> {
static const int value = 0;
};
template<class T> struct nested_container_depth_helper<T, true> {
static const int value = T::value;
};
template<class T>
struct nested_container_depth {
static const int value = nested_container_depth_helper<T, types::is_array<T>::value>::value;
};
template<class T>
struct nested_container_depth<types::list<T>> {
static const int value = 1 + nested_container_depth<T>::value;
};
template<class T, size_t N>
struct nested_container_depth<types::array<T, N>> {
static const int value = 1 + nested_container_depth<T>::value;
};
template<class T, size_t N>
struct nested_container_depth<types::ndarray<T, N>> {
static const int value = N;
};
/* Get the size of a container, using recursion on inner container if any
* FIXME: should be a constexpr?
* FIXME: why a class and not a function?
*/
template<class T>
struct nested_container_size {
typedef typename std::remove_cv<typename std::remove_reference<T>::type>::type Type;
static size_t flat_size(T const& t) {
return t.size()
*
nested_container_size<
typename std::conditional<
// If we have a scalar of a complex, we want to stop
// recursion, and then dispatch to bool specialization
std::is_scalar<typename Type::value_type>::value
or types::is_complex<typename Type::value_type>::value,
bool,
typename Type::value_type
>::type
>::flat_size(*t.begin());
}
};
/* Recursion stops on bool */
template<>
struct nested_container_size<bool> {
template<class F>
static size_t flat_size(F) { return 1; }
};
/* Statically define (by recursion) the type of element inside nested containers */
template<class T, bool IsArray> struct nested_container_value_type_helper;
template<class T> struct nested_container_value_type_helper<T, false> {
using type = T;
};
template<class T> struct nested_container_value_type_helper<T, true> {
using type = typename T::dtype;
};
template<class T>
struct nested_container_value_type {
using type = typename nested_container_value_type_helper<T, types::is_array<T>::value>::type;
};
template<class T>
struct nested_container_value_type<types::list<T>> {
using type = typename nested_container_value_type<T>::type;
};
template<class T, size_t N>
struct nested_container_value_type<types::array<T, N>> {
using type = typename nested_container_value_type<T>::type;
};
template<class T, size_t N>
struct nested_container_value_type<types::ndarray<T, N>> {
using type = T;
};
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/transport/src/zmq/zmq_poll_client.hpp>
#include <qi/transport/src/zmq/zmq_client_backend.hpp>
#include <qi/exceptions/exceptions.hpp>
#include <iostream>
#include <qi/log.hpp>
#include <qi/perf/sleep.hpp>
namespace qi {
namespace transport {
namespace detail {
/// <summary> Constructor. </summary>
/// <param name="serverAddress"> The server address. </param>
ZMQClientBackend::ZMQClientBackend(const std::string &serverAddress, zmq::context_t &context)
: ClientBackend(serverAddress),
_zcontext(context),
_zsocket(context, ZMQ_REQ),
_poll(_zsocket)
{
int linger = 0;
#ifdef ZMQ_LINGER
_zsocket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
#endif
connect();
}
/// <summary> Connects to the server </summary>
/// this is a little bit tricky, zmq does asynchronous connect/bind. Inproc will fail if
/// bind is not ready
void ZMQClientBackend::connect()
{
int i = 3;
while (i > 0)
{
try {
_zsocket.connect(_serverAddress.c_str());
return;
} catch(const std::exception& e) {
qisDebug << "ZMQClientBackend failed to create client for address \""
<< _serverAddress << "\" Reason: " << e.what() << std::endl;
qisDebug << "retrying.." << std::endl;
}
++i;
msleep(100);
}
throw qi::transport::Exception("ZMQClientBackend cant connect.");
}
/// <summary> Sends. </summary>
/// <param name="tosend"> The data to send. </param>
/// <param name="result"> [in,out] The result. </param>
void ZMQClientBackend::send(const std::string &tosend, std::string &result)
{
// TODO optimise this
// Could we copy from the serialized stream without calling
// stream.str() before sending to this method?
//TODO: could we avoid more copy?
zmq::message_t msg(tosend.size());
memcpy(msg.data(), tosend.data(), tosend.size());
_zsocket.send(msg);
//we leave the possibility to timeout, pollRecv will throw and avoid the call to recv
_poll.recv(&msg, 1000 * 1000 * 1000);
// TODO optimize this
// boost could serialize from msg.data() and size,
// without making a string
result.assign((char *)msg.data(), msg.size());
}
}
}
}
<commit_msg>transport: zmq: client: timeout = 10sec (should be configurable)<commit_after>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/transport/src/zmq/zmq_poll_client.hpp>
#include <qi/transport/src/zmq/zmq_client_backend.hpp>
#include <qi/exceptions/exceptions.hpp>
#include <iostream>
#include <qi/log.hpp>
#include <qi/perf/sleep.hpp>
namespace qi {
namespace transport {
namespace detail {
/// <summary> Constructor. </summary>
/// <param name="serverAddress"> The server address. </param>
ZMQClientBackend::ZMQClientBackend(const std::string &serverAddress, zmq::context_t &context)
: ClientBackend(serverAddress),
_zcontext(context),
_zsocket(context, ZMQ_REQ),
_poll(_zsocket)
{
int linger = 0;
#ifdef ZMQ_LINGER
_zsocket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
#endif
connect();
}
/// <summary> Connects to the server </summary>
/// this is a little bit tricky, zmq does asynchronous connect/bind. Inproc will fail if
/// bind is not ready
void ZMQClientBackend::connect()
{
int i = 3;
while (i > 0)
{
try {
_zsocket.connect(_serverAddress.c_str());
return;
} catch(const std::exception& e) {
qisDebug << "ZMQClientBackend failed to create client for address \""
<< _serverAddress << "\" Reason: " << e.what() << std::endl;
qisDebug << "retrying.." << std::endl;
}
++i;
msleep(100);
}
throw qi::transport::Exception("ZMQClientBackend cant connect.");
}
/// <summary> Sends. </summary>
/// <param name="tosend"> The data to send. </param>
/// <param name="result"> [in,out] The result. </param>
void ZMQClientBackend::send(const std::string &tosend, std::string &result)
{
// TODO optimise this
// Could we copy from the serialized stream without calling
// stream.str() before sending to this method?
//TODO: could we avoid more copy?
zmq::message_t msg(tosend.size());
memcpy(msg.data(), tosend.data(), tosend.size());
_zsocket.send(msg);
//we leave the possibility to timeout, pollRecv will throw and avoid the call to recv
_poll.recv(&msg, 10 * 1000 * 1000);
// TODO optimize this
// boost could serialize from msg.data() and size,
// without making a string
result.assign((char *)msg.data(), msg.size());
}
}
}
}
<|endoftext|> |
<commit_before>#include <test/unit/math/test_ad.hpp>
#include <cmath>
#include <complex>
#include <vector>
#include <type_traits>
TEST(mixFun, absBasics) {
using stan::math::abs;
int a = abs(1);
double b = abs(-2.3);
Eigen::Matrix<double, -1, -1> x(2, 3);
x << 1, 2, 3, 4, 5, 6;
Eigen::Matrix<double, -1, -1> y = abs(x);
std::vector<int> u{1, 2, 3, 4};
std::vector<int> v = abs(u);
}
TEST(mixFun, abs) {
auto f = [](const auto& x) {
return stan::math::abs(x);
};
stan::test::expect_common_nonzero_unary(f);
// 0 (no derivative at 0)
stan::test::expect_value(f, 0);
stan::test::expect_value(f, 0.0);
stan::test::expect_ad(f, -3);
stan::test::expect_ad(f, -2);
stan::test::expect_ad(f, 2);
stan::test::expect_ad(f, -17.3);
stan::test::expect_ad(f, -0.68);
stan::test::expect_ad(f, 0.68);
stan::test::expect_ad(f, 2.0);
stan::test::expect_ad(f, 4.0);
// complex tests
for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
stan::test::expect_ad(f, std::complex<double>(re, im));
}
}
// vector<double>
using svd_t = std::vector<double>;
stan::test::expect_ad(f, svd_t{});
stan::test::expect_ad(f, svd_t{1.0});
stan::test::expect_ad(f, svd_t{1.9, -2.3});
// vector<vector<double>>
using svvd_t = std::vector<svd_t>;
stan::test::expect_ad(f, svvd_t{});
stan::test::expect_ad(f, svvd_t{svd_t{}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});
// vector<complex<double>>
using c_t = std::complex<double>;
using svc_t = std::vector<c_t>;
stan::test::expect_ad(f, svc_t{});
stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});
stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});
// vector<vector<complex<double>>>
using svvc_t = std::vector<svc_t>;
stan::test::expect_ad(f, svvc_t{});
stan::test::expect_ad(f, svvc_t{{}});
stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});
stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},
svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});
// VectorXd
using v_t = Eigen::VectorXd;
v_t a0(0);
stan::test::expect_ad(f, a0);
v_t a1(1);
a1 << 1.9;
stan::test::expect_ad(f, a1);
v_t a2(2);
a2 << 1.9, -2.3;
stan::test::expect_ad(f, a2);
// RowVectorXd
using rv_t = Eigen::RowVectorXd;
rv_t b0(0);
stan::test::expect_ad(f, b0);
rv_t b1(1);
b1 << 1.9;
stan::test::expect_ad(f, b1);
rv_t b2(2);
b2 << 1.9, -2.3;
stan::test::expect_ad(f, b2);
// MatrixXd
using m_t = Eigen::MatrixXd;
m_t c0(0, 0);
stan::test::expect_ad(f, c0);
m_t c0i(0, 2);
stan::test::expect_ad(f, c0i);
m_t c0ii(2, 0);
stan::test::expect_ad(f, c0ii);
m_t c2(2, 1);
c2 << 1.3, -2.9;
stan::test::expect_ad(f, c2);
m_t c6(3, 2);
c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;
stan::test::expect_ad(f, c6);
// vector<VectorXd>
using av_t = std::vector<Eigen::VectorXd>;
av_t d0;
stan::test::expect_ad(f, d0);
av_t d1{a0};
stan::test::expect_ad(f, d1);
av_t d2{a1, a2};
stan::test::expect_ad(f, d2);
// vector<RowVectorXd>
using arv_t = std::vector<Eigen::RowVectorXd>;
arv_t e0;
stan::test::expect_ad(f, e0);
arv_t e1{b0};
stan::test::expect_ad(f, e1);
arv_t e2{b1, b2};
stan::test::expect_ad(f, e2);
// vector<MatrixXd>
using am_t = std::vector<Eigen::MatrixXd>;
am_t g0;
stan::test::expect_ad(f, g0);
am_t g1{c0};
stan::test::expect_ad(f, g1);
am_t g2{c2, c6};
stan::test::expect_ad(f, g2);
// VectorXcd
using vc_t = Eigen::VectorXcd;
vc_t h0(0);
stan::test::expect_ad(f, h0);
vc_t h1(1);
h1 << c_t{1.9, -1.8};
stan::test::expect_ad(f, h1);
vc_t h2(2);
h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
stan::test::expect_ad(f, h2);
// RowVectorXcd
using rvc_t = Eigen::RowVectorXcd;
rvc_t j0(0);
stan::test::expect_ad(f, j0);
rvc_t j1(1);
j1 << c_t{1.9, -1.8};
stan::test::expect_ad(f, j1);
rvc_t j2(2);
j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
stan::test::expect_ad(f, j2);
// MatrixXcd
using mc_t = Eigen::MatrixXcd;
mc_t k0(0, 0);
stan::test::expect_ad(f, k0);
mc_t k2(1, 2);
k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};
stan::test::expect_ad(f, k2);
mc_t k6(3, 2);
k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},
c_t{-13, 125.7}, c_t{-12.5, -10.5};
stan::test::expect_ad(f, k6);
// vector<VectorXcd>
using avc_t = std::vector<vc_t>;
avc_t m0;
stan::test::expect_ad(f, m0);
avc_t m1{h1};
stan::test::expect_ad(f, m1);
avc_t m2{h1, h2};
stan::test::expect_ad(f, m2);
// vector<RowVectorXcd>
using arvc_t = std::vector<rvc_t>;
arvc_t p0(0);
stan::test::expect_ad(f, p0);
arvc_t p1{j1};
stan::test::expect_ad(f, p1);
arvc_t p2{j1, j2};
stan::test::expect_ad(f, p2);
// vector<MatrixXcd>
using amc_t = std::vector<mc_t>;
amc_t q0;
stan::test::expect_ad(f, q0);
amc_t q1{k2};
stan::test::expect_ad(f, q1);
amc_t q2{k2, k6};
stan::test::expect_ad(f, q2);
}
TEST(mixFun, absReturnType) {
// validate return types not overpromoted to complex by assignability
std::complex<stan::math::var> a = 3;
stan::math::var b = abs(a);
std::complex<stan::math::fvar<double>> c = 3;
stan::math::fvar<double> d = abs(c);
SUCCEED();
}
TEST(mathMixMatFun, abs_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_nonzero_args;
auto f = [](const auto& x1) {
using stan::math::abs;
return abs(x1);
};
std::vector<double> com_args = common_nonzero_args();
std::vector<double> args{-3, 2, -0.68, 1};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<commit_msg>add tests for vector<var<Matrix>> types to abs() mix tests<commit_after>#include <test/unit/math/test_ad.hpp>
#include <cmath>
#include <complex>
#include <vector>
#include <type_traits>
TEST(mixFun, absBasics) {
using stan::math::abs;
int a = abs(1);
double b = abs(-2.3);
Eigen::Matrix<double, -1, -1> x(2, 3);
x << 1, 2, 3, 4, 5, 6;
Eigen::Matrix<double, -1, -1> y = abs(x);
std::vector<int> u{1, 2, 3, 4};
std::vector<int> v = abs(u);
}
TEST(mixFun, abs) {
auto f = [](const auto& x) {
return stan::math::abs(x);
};
stan::test::expect_common_nonzero_unary(f);
// 0 (no derivative at 0)
stan::test::expect_value(f, 0);
stan::test::expect_value(f, 0.0);
stan::test::expect_ad(f, -3);
stan::test::expect_ad(f, -2);
stan::test::expect_ad(f, 2);
stan::test::expect_ad(f, -17.3);
stan::test::expect_ad(f, -0.68);
stan::test::expect_ad(f, 0.68);
stan::test::expect_ad(f, 2.0);
stan::test::expect_ad(f, 4.0);
// complex tests
for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
stan::test::expect_ad(f, std::complex<double>(re, im));
}
}
// vector<double>
using svd_t = std::vector<double>;
stan::test::expect_ad(f, svd_t{});
stan::test::expect_ad(f, svd_t{1.0});
stan::test::expect_ad(f, svd_t{1.9, -2.3});
// vector<vector<double>>
using svvd_t = std::vector<svd_t>;
stan::test::expect_ad(f, svvd_t{});
stan::test::expect_ad(f, svvd_t{svd_t{}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});
stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});
// vector<complex<double>>
using c_t = std::complex<double>;
using svc_t = std::vector<c_t>;
stan::test::expect_ad(f, svc_t{});
stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});
stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});
// vector<vector<complex<double>>>
using svvc_t = std::vector<svc_t>;
stan::test::expect_ad(f, svvc_t{});
stan::test::expect_ad(f, svvc_t{{}});
stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});
stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},
svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});
// VectorXd
using v_t = Eigen::VectorXd;
v_t a0(0);
stan::test::expect_ad(f, a0);
stan::test::expect_ad_matvar(f, a0);
v_t a1(1);
a1 << 1.9;
stan::test::expect_ad(f, a1);
stan::test::expect_ad_matvar(f, a1);
v_t a2(2);
a2 << 1.9, -2.3;
stan::test::expect_ad(f, a2);
stan::test::expect_ad_matvar(f, a2);
// RowVectorXd
using rv_t = Eigen::RowVectorXd;
rv_t b0(0);
stan::test::expect_ad(f, b0);
stan::test::expect_ad_matvar(f, b0);
rv_t b1(1);
b1 << 1.9;
stan::test::expect_ad(f, b1);
stan::test::expect_ad_matvar(f, b1);
rv_t b2(2);
b2 << 1.9, -2.3;
stan::test::expect_ad(f, b2);
stan::test::expect_ad_matvar(f, b2);
// MatrixXd
using m_t = Eigen::MatrixXd;
m_t c0(0, 0);
stan::test::expect_ad(f, c0);
stan::test::expect_ad_matvar(f, c0);
m_t c0i(0, 2);
stan::test::expect_ad(f, c0i);
stan::test::expect_ad_matvar(f, c0i);
m_t c0ii(2, 0);
stan::test::expect_ad(f, c0ii);
stan::test::expect_ad_matvar(f, c0ii);
m_t c2(2, 1);
c2 << 1.3, -2.9;
stan::test::expect_ad(f, c2);
stan::test::expect_ad_matvar(f, c2);
m_t c6(3, 2);
c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;
stan::test::expect_ad(f, c6);
stan::test::expect_ad_matvar(f, c6);
// vector<VectorXd>
using av_t = std::vector<Eigen::VectorXd>;
av_t d0;
stan::test::expect_ad(f, d0);
stan::test::expect_ad_matvar(f, d0);
av_t d1{a0};
stan::test::expect_ad(f, d1);
stan::test::expect_ad_matvar(f, d1);
av_t d2{a1, a2};
stan::test::expect_ad(f, d2);
stan::test::expect_ad_matvar(f, d2);
// vector<RowVectorXd>
using arv_t = std::vector<Eigen::RowVectorXd>;
arv_t e0;
stan::test::expect_ad(f, e0);
stan::test::expect_ad_matvar(f, e0);
arv_t e1{b0};
stan::test::expect_ad(f, e1);
stan::test::expect_ad_matvar(f, e1);
arv_t e2{b1, b2};
stan::test::expect_ad(f, e2);
stan::test::expect_ad_matvar(f, e2);
// vector<MatrixXd>
using am_t = std::vector<Eigen::MatrixXd>;
am_t g0;
stan::test::expect_ad(f, g0);
stan::test::expect_ad_matvar(f, g0);
am_t g1{c0};
stan::test::expect_ad(f, g1);
stan::test::expect_ad_matvar(f, g1);
am_t g2{c2, c6};
stan::test::expect_ad(f, g2);
stan::test::expect_ad_matvar(f, g2);
// VectorXcd
using vc_t = Eigen::VectorXcd;
vc_t h0(0);
stan::test::expect_ad(f, h0);
vc_t h1(1);
h1 << c_t{1.9, -1.8};
stan::test::expect_ad(f, h1);
vc_t h2(2);
h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
stan::test::expect_ad(f, h2);
// RowVectorXcd
using rvc_t = Eigen::RowVectorXcd;
rvc_t j0(0);
stan::test::expect_ad(f, j0);
rvc_t j1(1);
j1 << c_t{1.9, -1.8};
stan::test::expect_ad(f, j1);
rvc_t j2(2);
j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
stan::test::expect_ad(f, j2);
// MatrixXcd
using mc_t = Eigen::MatrixXcd;
mc_t k0(0, 0);
stan::test::expect_ad(f, k0);
mc_t k2(1, 2);
k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};
stan::test::expect_ad(f, k2);
mc_t k6(3, 2);
k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},
c_t{-13, 125.7}, c_t{-12.5, -10.5};
stan::test::expect_ad(f, k6);
// vector<VectorXcd>
using avc_t = std::vector<vc_t>;
avc_t m0;
stan::test::expect_ad(f, m0);
avc_t m1{h1};
stan::test::expect_ad(f, m1);
avc_t m2{h1, h2};
stan::test::expect_ad(f, m2);
// vector<RowVectorXcd>
using arvc_t = std::vector<rvc_t>;
arvc_t p0(0);
stan::test::expect_ad(f, p0);
arvc_t p1{j1};
stan::test::expect_ad(f, p1);
arvc_t p2{j1, j2};
stan::test::expect_ad(f, p2);
// vector<MatrixXcd>
using amc_t = std::vector<mc_t>;
amc_t q0;
stan::test::expect_ad(f, q0);
amc_t q1{k2};
stan::test::expect_ad(f, q1);
amc_t q2{k2, k6};
stan::test::expect_ad(f, q2);
}
TEST(mixFun, absReturnType) {
// validate return types not overpromoted to complex by assignability
std::complex<stan::math::var> a = 3;
stan::math::var b = abs(a);
std::complex<stan::math::fvar<double>> c = 3;
stan::math::fvar<double> d = abs(c);
SUCCEED();
}
TEST(mathMixMatFun, abs_varmat) {
using stan::math::vec_concat;
using stan::test::expect_ad_vector_matvar;
using stan::test::internal::common_nonzero_args;
auto f = [](const auto& x1) {
using stan::math::abs;
return abs(x1);
};
std::vector<double> com_args = common_nonzero_args();
std::vector<double> args{-3, 2, -0.68, 1};
auto all_args = vec_concat(com_args, args);
Eigen::VectorXd A(all_args.size());
for (int i = 0; i < all_args.size(); ++i) {
A(i) = all_args[i];
}
expect_ad_vector_matvar(f, A);
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2008 by Daniel Schwen *
* daniel@schwen.de *
* *
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <queue>
/*#include <mytrim/simconf.h>
#include <mytrim/element.h>
#include <mytrim/material.h>
#include <mytrim/sample_wire.h>
#include <mytrim/ion.h>
#include <mytrim/trim.h>
#include <mytrim/invert.h>*/
#include "simconf.h"
#include "element.h"
#include "material.h"
#include "sample_wire.h"
#include "ion.h"
#include "trim.h"
#include "invert.h"
#include "functions.h"
int main(int argc, char *argv[])
{
char fname[200];
if( argc != 7 )
{
fprintf( stderr, "syntax:\nmytrim_wire basename Eion[eV] angle[deg] numpka zpka mpka\n" );
return 1;
}
double epka = atof(argv[2]);
double theta = atof(argv[3]) * M_PI/180.0; // 0 = perpendicular to wire
int numpka = atoi(argv[4]);
int zpka = atoi(argv[5]);
double mpka = atof(argv[6]);
// seed randomnumber generator from system entropy pool
FILE *urand = fopen( "/dev/random", "r" );
int seed;
fread( &seed, sizeof(int), 1, urand );
fclose( urand );
r250_init( seed<0 ? -seed : seed ); // random generator goes haywire with neg. seed
// initialize global parameter structure and read data tables from file
simconf = new simconfType;
// initialize sample structure
sampleWire *sample = new sampleWire( 800.0, 800.0, 100.0 );
// initialize trim engine for the sample
const int z1 = 31; //Ga
const int z2 = 6; //C
const int z3 = 74; //W
trimVacMap *trim = new trimVacMap( sample, z1, z2, z3 ); // GaCW
materialBase *material;
elementBase *element;
// GaCW
material = new materialBase( 5.31 ); // rho
element = new elementBase;
element->z = z1; // Ga
element->m = 70.0;
element->t = 0.1;
material->element.push_back( element );
element = new elementBase;
element->z = z2; // C
element->m = 12.0;
element->t = 0.65;
material->element.push_back( element );
element = new elementBase;
element->z = z3; // W
element->m = 184.0;
element->t = 0.25;
material->element.push_back( element );
material->prepare(); // all materials added
sample->material.push_back( material ); // add material to sample
// create a FIFO for recoils
queue<ionBase*> recoils;
double norm;
double jmp = 2.7; // diffusion jump distance
int jumps;
double dif[3];
//snprintf( fname, 199, "%s.Erec", argv[1] );
//FILE *erec = fopen( fname, "wt" );
//snprintf( fname, 199, "%s.dist", argv[1] );
//FILE *rdist = fopen( fname, "wt" );
ionBase *pka;
const int mx = 20, my = 20;
int imap[mx][my][3];
for( int e = 0; e < 3; e++ )
for( int x = 0; x < mx; x++ )
for( int y = 0; y < my; y++ )
imap[x][y][e] = 0;
// 10000 ions
for( int n = 0; n < numpka; n++ )
{
if( n % 1000 == 0 ) fprintf( stderr, "pka #%d\n", n+1 );
pka = new ionBase;
pka->gen = 0; // generation (0 = PKA)
pka->tag = -1;
pka->md = 0;
pka->z1 = zpka; // S
pka->m1 = mpka;
pka->e = epka;
pka->dir[0] = 0.0;
pka->dir[1] = -cos( theta );
pka->dir[2] = sin( theta );
v_norm( pka->dir );
pka->pos[0] = dr250() * sample->w[0];
pka->pos[2] = dr250() * sample->w[2];
// wire surface
pka->pos[1] = sample->w[1] / 2.0 * ( 1.0 + sqrt( 1.0 - sqr( ( pka->pos[0] / sample->w[0] ) * 2.0 - 1.0 ) ) ) - 0.5;
pka->set_ef();
recoils.push( pka );
while( !recoils.empty() )
{
pka = recoils.front();
recoils.pop();
sample->averages( pka );
// do ion analysis/processing BEFORE the cascade here
if( pka->z1 == zpka )
{
//printf( "p1 %f\t%f\t%f\n", pka->pos[0], pka->pos[1], pka->pos[2] );
}
// follow this ion's trajectory and store recoils
// printf( "%f\t%d\n", pka->e, pka->z1 );
trim->trim( pka, recoils );
// do ion analysis/processing AFTER the cascade here
// ion is still in sample
if( sample->lookupMaterial( pka->pos ) != 0 )
{
int x, y;
x = ( ( pka->pos[0] * mx ) / sample->w[0] );
y = ( ( pka->pos[1] * my ) / sample->w[1] );
x -= int(x/mx) * mx;
y -= int(y/my) * my;
// keep track of interstitials for the two constituents
if( pka->z1 == z1 ) imap[x][y][0]++;
else if( pka->z1 == z2 ) imap[x][y][1]++;
else if( pka->z1 == z3 ) imap[x][y][2]++;
}
// done with this recoil
delete pka;
}
}
char *elnam[3] = { "Ga", "C", "W" };
FILE *intf, *vacf, *netf;
for( int e = 0; e < 3; e++ )
{
snprintf( fname, 199, "%s.%s.int", argv[1], elnam[e] );
intf = fopen( fname, "wt" );
snprintf( fname, 199, "%s.%s.vac", argv[1], elnam[e] );
vacf = fopen( fname, "wt" );
snprintf( fname, 199, "%s.%s.net", argv[1], elnam[e] );
netf = fopen( fname, "wt" );
for( int y = 0; y <= my; y++ )
{
for( int x = 0; x <= mx; x++ )
{
double x1 = double(x)/double(mx)*sample->w[0];
double y1 = double(y)/double(my)*sample->w[1];
fprintf( intf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? imap[x][y][e] : 0 );
fprintf( vacf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? trim->vmap[x][y][e] : 0 );
fprintf( netf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? ( imap[x][y][e] - trim->vmap[x][y][e] ) : 0 );
}
fprintf( intf, "\n" );
fprintf( vacf, "\n" );
fprintf( netf, "\n" );
}
fclose( intf );
fclose( vacf );
fclose( netf );
}
return EXIT_SUCCESS;
}
<commit_msg>switch to Si wire<commit_after>/***************************************************************************
* Copyright (C) 2008 by Daniel Schwen *
* daniel@schwen.de *
* *
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <queue>
/*#include <mytrim/simconf.h>
#include <mytrim/element.h>
#include <mytrim/material.h>
#include <mytrim/sample_wire.h>
#include <mytrim/ion.h>
#include <mytrim/trim.h>
#include <mytrim/invert.h>*/
#include "simconf.h"
#include "element.h"
#include "material.h"
#include "sample_wire.h"
#include "ion.h"
#include "trim.h"
#include "invert.h"
#include "functions.h"
int main(int argc, char *argv[])
{
char fname[200];
if( argc != 7 )
{
fprintf( stderr, "syntax:\nmytrim_wire basename Eion[eV] angle[deg] numpka zpka mpka\n" );
return 1;
}
double epka = atof(argv[2]);
double theta = atof(argv[3]) * M_PI/180.0; // 0 = perpendicular to wire
int numpka = atoi(argv[4]);
int zpka = atoi(argv[5]);
double mpka = atof(argv[6]);
// seed randomnumber generator from system entropy pool
FILE *urand = fopen( "/dev/random", "r" );
int seed;
fread( &seed, sizeof(int), 1, urand );
fclose( urand );
r250_init( seed<0 ? -seed : seed ); // random generator goes haywire with neg. seed
// initialize global parameter structure and read data tables from file
simconf = new simconfType;
// initialize sample structure
sampleWire *sample = new sampleWire( 500.0, 500.0, 100.0 );
// initialize trim engine for the sample
const int z1 = 14; //Si
//const int z2 = 6; //C
//const int z3 = 74; //W
trimVacMap *trim = new trimVacMap( sample, z1, 0, 0 ); // GaCW
materialBase *material;
elementBase *element;
// Si
material = new materialBase( 2.33 ); // rho
element = new elementBase;
element->z = z1; // Si
element->m = 28.0;
element->t = 1;
material->element.push_back( element );
/*element = new elementBase;
element->z = z2; // C
element->m = 12.0;
element->t = 0.65;
material->element.push_back( element );
element = new elementBase;
element->z = z3; // W
element->m = 184.0;
element->t = 0.25;
material->element.push_back( element );*/
material->prepare(); // all materials added
sample->material.push_back( material ); // add material to sample
// create a FIFO for recoils
queue<ionBase*> recoils;
double norm;
double jmp = 2.7; // diffusion jump distance
int jumps;
double dif[3];
//snprintf( fname, 199, "%s.Erec", argv[1] );
//FILE *erec = fopen( fname, "wt" );
//snprintf( fname, 199, "%s.dist", argv[1] );
//FILE *rdist = fopen( fname, "wt" );
ionBase *pka;
const int mx = 20, my = 20;
int imap[mx][my][3];
for( int e = 0; e < 3; e++ )
for( int x = 0; x < mx; x++ )
for( int y = 0; y < my; y++ )
imap[x][y][e] = 0;
// 10000 ions
for( int n = 0; n < numpka; n++ )
{
if( n % 1000 == 0 ) fprintf( stderr, "pka #%d\n", n+1 );
pka = new ionBase;
pka->gen = 0; // generation (0 = PKA)
pka->tag = -1;
pka->md = 0;
pka->z1 = zpka; // S
pka->m1 = mpka;
pka->e = epka;
pka->dir[0] = 0.0;
pka->dir[1] = -cos( theta );
pka->dir[2] = sin( theta );
v_norm( pka->dir );
pka->pos[0] = dr250() * sample->w[0];
pka->pos[2] = dr250() * sample->w[2];
// wire surface
pka->pos[1] = sample->w[1] / 2.0 * ( 1.0 + sqrt( 1.0 - sqr( ( pka->pos[0] / sample->w[0] ) * 2.0 - 1.0 ) ) ) - 0.5;
pka->set_ef();
recoils.push( pka );
while( !recoils.empty() )
{
pka = recoils.front();
recoils.pop();
sample->averages( pka );
// do ion analysis/processing BEFORE the cascade here
if( pka->z1 == zpka )
{
//printf( "p1 %f\t%f\t%f\n", pka->pos[0], pka->pos[1], pka->pos[2] );
}
// follow this ion's trajectory and store recoils
// printf( "%f\t%d\n", pka->e, pka->z1 );
trim->trim( pka, recoils );
// do ion analysis/processing AFTER the cascade here
// ion is still in sample
if( sample->lookupMaterial( pka->pos ) != 0 )
{
int x, y;
x = ( ( pka->pos[0] * mx ) / sample->w[0] );
y = ( ( pka->pos[1] * my ) / sample->w[1] );
x -= int(x/mx) * mx;
y -= int(y/my) * my;
// keep track of interstitials for the two constituents
if( pka->z1 == z1 ) imap[x][y][0]++;
else if( pka->z1 == z2 ) imap[x][y][1]++;
else if( pka->z1 == z3 ) imap[x][y][2]++;
}
// done with this recoil
delete pka;
}
}
char *elnam[3] = { "Ga", "C", "W" };
FILE *intf, *vacf, *netf;
// e<numberofelementsinwire
for( int e = 0; e < 1; e++ )
{
snprintf( fname, 199, "%s.%s.int", argv[1], elnam[e] );
intf = fopen( fname, "wt" );
snprintf( fname, 199, "%s.%s.vac", argv[1], elnam[e] );
vacf = fopen( fname, "wt" );
snprintf( fname, 199, "%s.%s.net", argv[1], elnam[e] );
netf = fopen( fname, "wt" );
for( int y = 0; y <= my; y++ )
{
for( int x = 0; x <= mx; x++ )
{
double x1 = double(x)/double(mx)*sample->w[0];
double y1 = double(y)/double(my)*sample->w[1];
fprintf( intf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? imap[x][y][e] : 0 );
fprintf( vacf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? trim->vmap[x][y][e] : 0 );
fprintf( netf, "%f %f %d\n", x1, y1, (x<mx && y<my) ? ( imap[x][y][e] - trim->vmap[x][y][e] ) : 0 );
}
fprintf( intf, "\n" );
fprintf( vacf, "\n" );
fprintf( netf, "\n" );
}
fclose( intf );
fclose( vacf );
fclose( netf );
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
#include <usTestingConfig.h>
#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"
#include <assert.h>
#include <set>
US_USE_NAMESPACE
namespace {
std::string GetResourceContent(const ModuleResource& resource)
{
std::string line;
ModuleResourceStream rs(resource);
std::getline(rs, line);
return line;
}
struct ResourceComparator {
bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
{
return mr1 < mr2;
}
};
void testResourceOperators(Module* module)
{
std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}
void testResourcesWithStaticImport(Module* module)
{
ModuleResource resource = module->GetResource("res.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
std::string line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")
resource = module->GetResource("dynamic.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")
resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "static", "Check dynamic resource content")
std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
line = GetResourceContent(resources[1]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
// skip foo.txt
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
// skip special_chars.dummy.txt
line = GetResourceContent(resources[5]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}
} // end unnamed namespace
int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("StaticModuleResourceTest");
assert(GetModuleContext());
#ifdef US_BUILD_SHARED_LIBS
SharedLibraryHandle libB("TestModuleB");
try
{
libB.Load();
}
catch (const std::exception& e)
{
US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
}
Module* module = ModuleRegistry::GetModule("TestModuleB Module");
US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")
US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
Module* module = mc->GetModule();
#endif
testResourceOperators(module);
testResourcesWithStaticImport(module);
#ifdef US_BUILD_SHARED_LIBS
ModuleResource resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
libB.Unload();
US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif
US_TEST_END()
}
<commit_msg>Fixed compile error for static builds.<commit_after>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
#include <usTestingConfig.h>
#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"
#include <assert.h>
#include <set>
US_USE_NAMESPACE
namespace {
std::string GetResourceContent(const ModuleResource& resource)
{
std::string line;
ModuleResourceStream rs(resource);
std::getline(rs, line);
return line;
}
struct ResourceComparator {
bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
{
return mr1 < mr2;
}
};
void testResourceOperators(Module* module)
{
std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}
void testResourcesWithStaticImport(Module* module)
{
ModuleResource resource = module->GetResource("res.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
std::string line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")
resource = module->GetResource("dynamic.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")
resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "static", "Check dynamic resource content")
std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
line = GetResourceContent(resources[1]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
// skip foo.txt
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
// skip special_chars.dummy.txt
line = GetResourceContent(resources[5]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}
} // end unnamed namespace
int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("StaticModuleResourceTest");
assert(GetModuleContext());
#ifdef US_BUILD_SHARED_LIBS
SharedLibraryHandle libB("TestModuleB");
try
{
libB.Load();
}
catch (const std::exception& e)
{
US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
}
Module* module = ModuleRegistry::GetModule("TestModuleB Module");
US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")
US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
Module* module = GetModuleContext()->GetModule();
#endif
testResourceOperators(module);
testResourcesWithStaticImport(module);
#ifdef US_BUILD_SHARED_LIBS
ModuleResource resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
libB.Unload();
US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif
US_TEST_END()
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "bench.hpp"
#ifdef MFEM_USE_BENCHMARK
/*
This benchmark contains the implementation of the CEED's bake-off problems:
high-order kernels/benchmarks designed to test and compare the performance
of high-order codes.
See: ceed.exascaleproject.org/bps and github.com/CEED/benchmarks
*/
struct BakeOff
{
const AssemblyLevel assembly;
const int N, p, q, dim = 3;
Mesh mesh;
H1_FECollection fec;
FiniteElementSpace fes;
const Geometry::Type geom_type;
IntegrationRules IntRulesGLL;
const IntegrationRule *irGLL;
const IntegrationRule *ir;
ConstantCoefficient one;
const int dofs;
GridFunction x,y;
BilinearForm a;
double mdofs;
BakeOff(AssemblyLevel assembly, int p, int vdim, bool GLL):
assembly(assembly),
N(Device::IsEnabled()?32:8),
p(p),
q(2*p + (GLL?-1:3)),
mesh(Mesh::MakeCartesian3D(N,N,N,Element::HEXAHEDRON)),
fec(p, dim, BasisType::GaussLobatto),
fes(&mesh, &fec, vdim),
geom_type(fes.GetFE(0)->GetGeomType()),
IntRulesGLL(0, Quadrature1D::GaussLobatto),
irGLL(&IntRulesGLL.Get(geom_type, q)),
ir(&IntRules.Get(geom_type, q)),
one(1.0),
dofs(fes.GetTrueVSize()),
x(&fes),
y(&fes),
a(&fes),
mdofs(0.0) {}
virtual void setup() = 0;
virtual void benchmark() = 0;
double SumMdofs() const { return mdofs; }
double MDofs() const { return 1e-6 * dofs; }
};
/// Bake-off Problems (BPs)
template<typename BFI, int VDIM = 1, bool GLL = false>
struct Problem: public BakeOff
{
const double rtol = 1e-12;
const int max_it = 32;
const int print_lvl = -1;
Array<int> ess_tdof_list;
Array<int> ess_bdr;
LinearForm b;
OperatorPtr A;
Vector B, X;
CGSolver cg;
Problem(AssemblyLevel assembly, int order):
BakeOff(assembly,order,VDIM,GLL),
ess_bdr(mesh.bdr_attributes.Max()),
b(&fes)
{
ess_bdr = 1;
fes.GetEssentialTrueDofs(ess_bdr,ess_tdof_list);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
a.SetAssemblyLevel(assembly);
a.AddDomainIntegrator(new BFI(one, GLL?irGLL:ir));
a.Assemble();
a.Mult(x, y);
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
cg.SetRelTol(rtol);
cg.SetOperator(*A);
cg.SetMaxIter(max_it);
cg.SetPrintLevel(print_lvl);
cg.iterative_mode = false;
MFEM_DEVICE_SYNC;
}
void setup() override
{
a.Assemble();
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
void benchmark() override
{
cg.Mult(B,X);
MFEM_DEVICE_SYNC;
mdofs += MDofs() * cg.GetNumIterations();
}
};
/// Bake-off Problems (BPs)
#define BakeOff_Problem(assembly,i,Kernel,VDIM,p_eq_q)\
static void SetupBP##i##assembly(bm::State &state){\
Problem<Kernel##Integrator,VDIM,p_eq_q> ker(AssemblyLevel::assembly,state.range(0));\
while (state.KeepRunning()) { ker.setup(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);}\
BENCHMARK(SetupBP##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);\
static void BP##i##assembly(bm::State &state){\
Problem<Kernel##Integrator,VDIM,p_eq_q> ker(AssemblyLevel::assembly,state.range(0));\
while (state.KeepRunning()) { ker.benchmark(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);}\
BENCHMARK(BP##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);
// PARTIAL:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(PARTIAL,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
BakeOff_Problem(PARTIAL,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(PARTIAL,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
BakeOff_Problem(PARTIAL,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(PARTIAL,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
BakeOff_Problem(PARTIAL,6,VectorDiffusion,3,true)
// ELEMENT:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(ELEMENT,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
// BakeOff_Problem(ELEMENT,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(ELEMENT,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
// BakeOff_Problem(ELEMENT,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(ELEMENT,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
// BakeOff_Problem(ELEMENT,6,VectorDiffusion,3,true)
// FULL:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(FULL,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
// BakeOff_Problem(FULL,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(FULL,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
// BakeOff_Problem(FULL,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(FULL,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
// BakeOff_Problem(FULL,6,VectorDiffusion,3,true)
/// Bake-off Kernels (BKs)
template <typename BFI, int VDIM = 1, bool GLL = false>
struct Kernel: public BakeOff
{
GridFunction y;
Kernel(AssemblyLevel assembly, int order)
: BakeOff(assembly,order,VDIM,GLL), y(&fes)
{
x.Randomize(1);
a.SetAssemblyLevel(assembly);
a.AddDomainIntegrator(new BFI(one, GLL?irGLL:ir));
a.Assemble();
a.Mult(x, y);
MFEM_DEVICE_SYNC;
}
void setup() override
{
a.Assemble();
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
void benchmark() override
{
a.Mult(x, y);
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
};
/// Generic CEED BKi
#define BakeOff_Kernel(assembly,i,KER,VDIM,GLL)\
static void BK##i##assembly(bm::State &state){\
Kernel<KER##Integrator,VDIM,GLL> ker(AssemblyLevel::assembly, state.range(0));\
while (state.KeepRunning()) { ker.benchmark(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);}\
BENCHMARK(BK##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);\
// PARTIAL:
/// BK1PARTIAL: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(PARTIAL,1,Mass,1,false)
/// BK2PARTIAL: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(PARTIAL,2,VectorMass,3,false)
/// BK3PARTIAL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(PARTIAL,3,Diffusion,1,false)
/// BK4PARTIAL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(PARTIAL,4,VectorDiffusion,3,false)
/// BK5PARTIAL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(PARTIAL,5,Diffusion,1,true)
/// BK6PARTIAL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(PARTIAL,6,VectorDiffusion,3,true)
// ELEMENT
/// BK1ELEMENT: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(ELEMENT,1,Mass,1,false)
/// BK2ELEMENT: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
// BakeOff_Kernel(ELEMENT,2,VectorMass,3,false)
/// BK3ELEMENT: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(ELEMENT,3,Diffusion,1,false)
/// BK4ELEMENT: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
// BakeOff_Kernel(ELEMENT,4,VectorDiffusion,3,false)
/// BK5ELEMENT: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(ELEMENT,5,Diffusion,1,true)
/// BK6ELEMENT: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
// BakeOff_Kernel(ELEMENT,6,VectorDiffusion,3,true)
// FULL
/// BK1FULL: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(FULL,1,Mass,1,false)
/// BK2FULL: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
// BakeOff_Kernel(FULL,2,VectorMass,3,false)
/// BK3FULL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(FULL,3,Diffusion,1,false)
/// BK4FULL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
// BakeOff_Kernel(FULL,4,VectorDiffusion,3,false)
/// BK5FULL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(FULL,5,Diffusion,1,true)
/// BK6FULL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
// BakeOff_Kernel(FULL,6,VectorDiffusion,3,true)
/**
* @brief main entry point
* --benchmark_filter=BK1/6
* --benchmark_context=device=cpu
*/
int main(int argc, char *argv[])
{
bm::ConsoleReporter CR;
bm::Initialize(&argc, argv);
// Device setup, cpu by default
std::string device_config = "cpu";
if (bmi::global_context != nullptr)
{
const auto device = bmi::global_context->find("device");
if (device != bmi::global_context->end())
{
mfem::out << device->first << " : " << device->second << std::endl;
device_config = device->second;
}
}
Device device(device_config.c_str());
device.Print();
if (bm::ReportUnrecognizedArguments(argc, argv)) { return 1; }
bm::RunSpecifiedBenchmarks(&CR);
return 0;
}
#endif // MFEM_USE_BENCHMARK
<commit_msg>Add Dofs prints.<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "bench.hpp"
#ifdef MFEM_USE_BENCHMARK
/*
This benchmark contains the implementation of the CEED's bake-off problems:
high-order kernels/benchmarks designed to test and compare the performance
of high-order codes.
See: ceed.exascaleproject.org/bps and github.com/CEED/benchmarks
*/
struct BakeOff
{
const AssemblyLevel assembly;
const int N, p, q, dim = 3;
Mesh mesh;
H1_FECollection fec;
FiniteElementSpace fes;
const Geometry::Type geom_type;
IntegrationRules IntRulesGLL;
const IntegrationRule *irGLL;
const IntegrationRule *ir;
ConstantCoefficient one;
const int dofs;
GridFunction x,y;
BilinearForm a;
double mdofs;
BakeOff(AssemblyLevel assembly, int p, int vdim, bool GLL):
assembly(assembly),
N(Device::IsEnabled()?32:8),
p(p),
q(2*p + (GLL?-1:3)),
mesh(Mesh::MakeCartesian3D(N,N,N,Element::HEXAHEDRON)),
fec(p, dim, BasisType::GaussLobatto),
fes(&mesh, &fec, vdim),
geom_type(fes.GetFE(0)->GetGeomType()),
IntRulesGLL(0, Quadrature1D::GaussLobatto),
irGLL(&IntRulesGLL.Get(geom_type, q)),
ir(&IntRules.Get(geom_type, q)),
one(1.0),
dofs(fes.GetTrueVSize()),
x(&fes),
y(&fes),
a(&fes),
mdofs(0.0) {}
virtual void setup() = 0;
virtual void benchmark() = 0;
double SumMdofs() const { return mdofs; }
double MDofs() const { return 1e-6 * dofs; }
};
/// Bake-off Problems (BPs)
template<typename BFI, int VDIM = 1, bool GLL = false>
struct Problem: public BakeOff
{
const double rtol = 1e-12;
const int max_it = 32;
const int print_lvl = -1;
Array<int> ess_tdof_list;
Array<int> ess_bdr;
LinearForm b;
OperatorPtr A;
Vector B, X;
CGSolver cg;
Problem(AssemblyLevel assembly, int order):
BakeOff(assembly,order,VDIM,GLL),
ess_bdr(mesh.bdr_attributes.Max()),
b(&fes)
{
ess_bdr = 1;
fes.GetEssentialTrueDofs(ess_bdr,ess_tdof_list);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
a.SetAssemblyLevel(assembly);
a.AddDomainIntegrator(new BFI(one, GLL?irGLL:ir));
a.Assemble();
a.Mult(x, y);
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
cg.SetRelTol(rtol);
cg.SetOperator(*A);
cg.SetMaxIter(max_it);
cg.SetPrintLevel(print_lvl);
cg.iterative_mode = false;
MFEM_DEVICE_SYNC;
}
void setup() override
{
a.Assemble();
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
void benchmark() override
{
cg.Mult(B,X);
MFEM_DEVICE_SYNC;
mdofs += MDofs() * cg.GetNumIterations();
}
};
/// Bake-off Problems (BPs)
#define BakeOff_Problem(assembly,i,Kernel,VDIM,p_eq_q)\
static void SetupBP##i##assembly(bm::State &state){\
Problem<Kernel##Integrator,VDIM,p_eq_q> ker(AssemblyLevel::assembly,state.range(0));\
while (state.KeepRunning()) { ker.setup(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);\
state.counters["Dofs"] = bm::Counter(ker.dofs, bm::Counter::kDefaults);}\
BENCHMARK(SetupBP##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);\
static void BP##i##assembly(bm::State &state){\
Problem<Kernel##Integrator,VDIM,p_eq_q> ker(AssemblyLevel::assembly,state.range(0));\
while (state.KeepRunning()) { ker.benchmark(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);\
state.counters["Dofs"] = bm::Counter(ker.dofs, bm::Counter::kDefaults);}\
BENCHMARK(BP##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);
// PARTIAL:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(PARTIAL,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
BakeOff_Problem(PARTIAL,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(PARTIAL,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
BakeOff_Problem(PARTIAL,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(PARTIAL,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
BakeOff_Problem(PARTIAL,6,VectorDiffusion,3,true)
// ELEMENT:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(ELEMENT,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
// BakeOff_Problem(ELEMENT,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(ELEMENT,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
// BakeOff_Problem(ELEMENT,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(ELEMENT,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
// BakeOff_Problem(ELEMENT,6,VectorDiffusion,3,true)
// FULL:
/// BP1: scalar PCG with mass matrix, q=p+2
BakeOff_Problem(FULL,1,Mass,1,false)
/// BP2: vector PCG with mass matrix, q=p+2
// BakeOff_Problem(FULL,2,VectorMass,3,false)
/// BP3: scalar PCG with stiffness matrix, q=p+2
BakeOff_Problem(FULL,3,Diffusion,1,false)
/// BP4: vector PCG with stiffness matrix, q=p+2
// BakeOff_Problem(FULL,4,VectorDiffusion,3,false)
/// BP5: scalar PCG with stiffness matrix, q=p+1
BakeOff_Problem(FULL,5,Diffusion,1,true)
/// BP6: vector PCG with stiffness matrix, q=p+1
// BakeOff_Problem(FULL,6,VectorDiffusion,3,true)
/// Bake-off Kernels (BKs)
template <typename BFI, int VDIM = 1, bool GLL = false>
struct Kernel: public BakeOff
{
GridFunction y;
Kernel(AssemblyLevel assembly, int order)
: BakeOff(assembly,order,VDIM,GLL), y(&fes)
{
x.Randomize(1);
a.SetAssemblyLevel(assembly);
a.AddDomainIntegrator(new BFI(one, GLL?irGLL:ir));
a.Assemble();
a.Mult(x, y);
MFEM_DEVICE_SYNC;
}
void setup() override
{
a.Assemble();
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
void benchmark() override
{
a.Mult(x, y);
MFEM_DEVICE_SYNC;
mdofs += MDofs();
}
};
/// Generic CEED BKi
#define BakeOff_Kernel(assembly,i,KER,VDIM,GLL)\
static void BK##i##assembly(bm::State &state){\
Kernel<KER##Integrator,VDIM,GLL> ker(AssemblyLevel::assembly, state.range(0));\
while (state.KeepRunning()) { ker.benchmark(); }\
state.counters["MDof/s"] = bm::Counter(ker.SumMdofs(), bm::Counter::kIsRate);\
state.counters["Dofs"] = bm::Counter(ker.dofs, bm::Counter::kDefaults);}\
BENCHMARK(BK##i##assembly)->DenseRange(1,6)->Unit(bm::kMillisecond);\
// PARTIAL:
/// BK1PARTIAL: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(PARTIAL,1,Mass,1,false)
/// BK2PARTIAL: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(PARTIAL,2,VectorMass,3,false)
/// BK3PARTIAL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(PARTIAL,3,Diffusion,1,false)
/// BK4PARTIAL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(PARTIAL,4,VectorDiffusion,3,false)
/// BK5PARTIAL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(PARTIAL,5,Diffusion,1,true)
/// BK6PARTIAL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(PARTIAL,6,VectorDiffusion,3,true)
// ELEMENT
/// BK1ELEMENT: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(ELEMENT,1,Mass,1,false)
/// BK2ELEMENT: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
// BakeOff_Kernel(ELEMENT,2,VectorMass,3,false)
/// BK3ELEMENT: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(ELEMENT,3,Diffusion,1,false)
/// BK4ELEMENT: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
// BakeOff_Kernel(ELEMENT,4,VectorDiffusion,3,false)
/// BK5ELEMENT: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(ELEMENT,5,Diffusion,1,true)
/// BK6ELEMENT: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
// BakeOff_Kernel(ELEMENT,6,VectorDiffusion,3,true)
// FULL
/// BK1FULL: scalar E-vector-to-E-vector evaluation of mass matrix, q=p+2
BakeOff_Kernel(FULL,1,Mass,1,false)
/// BK2FULL: vector E-vector-to-E-vector evaluation of mass matrix, q=p+2
// BakeOff_Kernel(FULL,2,VectorMass,3,false)
/// BK3FULL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
BakeOff_Kernel(FULL,3,Diffusion,1,false)
/// BK4FULL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+2
// BakeOff_Kernel(FULL,4,VectorDiffusion,3,false)
/// BK5FULL: scalar E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
BakeOff_Kernel(FULL,5,Diffusion,1,true)
/// BK6FULL: vector E-vector-to-E-vector evaluation of stiffness matrix, q=p+1
// BakeOff_Kernel(FULL,6,VectorDiffusion,3,true)
/**
* @brief main entry point
* --benchmark_filter=BK1/6
* --benchmark_context=device=cpu
*/
int main(int argc, char *argv[])
{
bm::ConsoleReporter CR;
bm::Initialize(&argc, argv);
// Device setup, cpu by default
std::string device_config = "cpu";
if (bmi::global_context != nullptr)
{
const auto device = bmi::global_context->find("device");
if (device != bmi::global_context->end())
{
mfem::out << device->first << " : " << device->second << std::endl;
device_config = device->second;
}
}
Device device(device_config.c_str());
device.Print();
if (bm::ReportUnrecognizedArguments(argc, argv)) { return 1; }
bm::RunSpecifiedBenchmarks(&CR);
return 0;
}
#endif // MFEM_USE_BENCHMARK
<|endoftext|> |
<commit_before>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com
Copyright(c) 2014 jwellbelove
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 <UnitTest++/UnitTest++.h>
#include "ExtraCheckMacros.h"
#include "data.h"
#include <set>
#include <vector>
#include "../src/pool.h"
typedef TestDataDC<std::string> Test_Data;
typedef TestDataNDC<std::string> Test_Data2;
namespace
{
SUITE(test_pool)
{
//*************************************************************************
TEST(test_allocate)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1;
Test_Data* p2;
Test_Data* p3;
Test_Data* p4;
CHECK_NO_THROW(p1 = pool.allocate());
CHECK_NO_THROW(p2 = pool.allocate());
CHECK_NO_THROW(p3 = pool.allocate());
CHECK_NO_THROW(p4 = pool.allocate());
CHECK(p1 != p2);
CHECK(p1 != p3);
CHECK(p1 != p4);
CHECK(p2 != p3);
CHECK(p2 != p4);
CHECK(p3 != p4);
CHECK_THROW(pool.allocate(), etl::pool_no_allocation);
}
//*************************************************************************
TEST(test_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Test_Data* p3 = pool.allocate();
Test_Data* p4 = pool.allocate();
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(*p3));
CHECK_NO_THROW(pool.release(p1));
CHECK_NO_THROW(pool.release(*p4));
CHECK_EQUAL(4U, pool.available());
Test_Data not_in_pool;
CHECK_THROW(pool.release(not_in_pool), etl::pool_object_not_in_pool);
}
//*************************************************************************
TEST(test_allocate_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Test_Data* p3 = pool.allocate();
Test_Data* p4 = pool.allocate();
// Allocated p1, p2, p3, p4
CHECK_EQUAL(0U, pool.available());
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(p3));
// Allocated p1, p4
CHECK_EQUAL(2U, pool.available());
Test_Data* p5 = pool.allocate();
Test_Data* p6 = pool.allocate();
// Allocated p1, p4, p5, p6
CHECK_EQUAL(0U, pool.available());
CHECK(p5 != p1);
CHECK(p5 != p4);
CHECK(p6 != p1);
CHECK(p6 != p4);
CHECK_NO_THROW(pool.release(p5));
// Allocated p1, p4, p6
CHECK_EQUAL(1U, pool.available());
Test_Data* p7 = pool.allocate();
// Allocated p1, p4, p6, p7
CHECK(p7 != p1);
CHECK(p7 != p4);
CHECK(p7 != p6);
CHECK(pool.full());
}
//*************************************************************************
TEST(test_available)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(4, pool.available());
Test_Data* p;
p = pool.allocate();
CHECK_EQUAL(3U, pool.available());
p = pool.allocate();
CHECK_EQUAL(2U, pool.available());
p = pool.allocate();
CHECK_EQUAL(1U, pool.available());
p = pool.allocate();
CHECK_EQUAL(0U, pool.available());
}
//*************************************************************************
TEST(test_max_size)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.max_size() == 4U);
}
//*************************************************************************
TEST(test_size)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(0U, pool.size());
Test_Data* p;
p = pool.allocate();
CHECK_EQUAL(1U, pool.size());
p = pool.allocate();
CHECK_EQUAL(2U, pool.size());
p = pool.allocate();
CHECK_EQUAL(3U, pool.size());
p = pool.allocate();
CHECK_EQUAL(4U, pool.size());
}
//*************************************************************************
TEST(test_empty_full)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.empty());
CHECK(!pool.full());
Test_Data* p;
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(pool.full());
}
//*************************************************************************
TEST(test_is_in_pool)
{
etl::pool<Test_Data, 4> pool;
Test_Data not_in_pool;
Test_Data* p1 = pool.allocate();
CHECK(pool.is_in_pool(p1));
CHECK(!pool.is_in_pool(not_in_pool));
}
//*************************************************************************
TEST(test_begin_empty)
{
etl::pool<Test_Data, 4> pool;
etl::pool<Test_Data, 4>::iterator it = pool.begin();
CHECK(it == pool.end());
etl::pool<Test_Data, 4>::const_iterator cit = pool.begin();
CHECK(cit == pool.end());
cit = pool.cbegin();
CHECK(cit == pool.end());
}
//*************************************************************************
TEST(test_iterator)
{
etl::pool<Test_Data2, 10> pool;
std::set<Test_Data2> compare = { Test_Data2("0"), Test_Data2("2"), Test_Data2("4"), Test_Data2("6"), Test_Data2("8") };
std::set<Test_Data2> test;
std::vector<Test_Data2*> objects;
// Build the set of objects.
objects.push_back(pool.allocate(Test_Data2("9")));
objects.push_back(pool.allocate(Test_Data2("7")));
objects.push_back(pool.allocate(Test_Data2("8")));
objects.push_back(pool.allocate(Test_Data2("6")));
objects.push_back(pool.allocate(Test_Data2("5")));
objects.push_back(pool.allocate(Test_Data2("3")));
objects.push_back(pool.allocate(Test_Data2("4")));
objects.push_back(pool.allocate(Test_Data2("2")));
objects.push_back(pool.allocate(Test_Data2("0")));
objects.push_back(pool.allocate(Test_Data2("1")));
// Release "1", "3", "5", "7", "9".
pool.release(objects[0]);
pool.release(objects[1]);
pool.release(objects[4]);
pool.release(objects[5]);
pool.release(objects[9]);
// Fill the test set with what we get from the iterator.
etl::pool<Test_Data2, 10>::iterator i_pool = pool.begin();
while (i_pool != pool.end())
{
test.insert(*i_pool);
++i_pool;
}
// Compare the results.
std::set<Test_Data2>::iterator i_compare = compare.begin();
std::set<Test_Data2>::iterator i_test = test.begin();
CHECK_EQUAL(compare.size(), test.size());
while ((i_compare != compare.end()) && (i_test != test.end()))
{
CHECK_EQUAL(*i_compare++, *i_test++);
}
}
//*************************************************************************
TEST(test_const_iterator)
{
etl::pool<Test_Data2, 10> pool;
std::set<Test_Data2> compare = { Test_Data2("0"), Test_Data2("2"), Test_Data2("4"), Test_Data2("6"), Test_Data2("8") };
std::set<Test_Data2> test;
std::vector<Test_Data2*> objects;
// Build the set of objects.
objects.push_back(pool.allocate(Test_Data2("9")));
objects.push_back(pool.allocate(Test_Data2("7")));
objects.push_back(pool.allocate(Test_Data2("8")));
objects.push_back(pool.allocate(Test_Data2("6")));
objects.push_back(pool.allocate(Test_Data2("5")));
objects.push_back(pool.allocate(Test_Data2("3")));
objects.push_back(pool.allocate(Test_Data2("4")));
objects.push_back(pool.allocate(Test_Data2("2")));
objects.push_back(pool.allocate(Test_Data2("0")));
objects.push_back(pool.allocate(Test_Data2("1")));
// Release "1", "3", "5", "7", "9".
pool.release(objects[0]);
pool.release(objects[1]);
pool.release(objects[4]);
pool.release(objects[5]);
pool.release(objects[9]);
// Fill the test set with what we get from the iterator.
etl::pool<Test_Data2, 10>::const_iterator i_pool = pool.begin();
while (i_pool != pool.end())
{
test.insert(*i_pool);
++i_pool;
}
// Compare the results.
std::set<Test_Data2>::const_iterator i_compare = compare.begin();
std::set<Test_Data2>::const_iterator i_test = test.begin();
CHECK_EQUAL(compare.size(), test.size());
while ((i_compare != compare.end()) && (i_test != test.end()))
{
CHECK_EQUAL(*i_compare++, *i_test++);
}
}
//*************************************************************************
TEST(test_get_iterator)
{
typedef etl::pool<Test_Data, 4> Pool;
Pool pool;
Test_Data not_in_pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Pool::iterator i_data = pool.get_iterator(*p1);
Pool::iterator i_data2 = pool.get_iterator(*p2);
Pool::iterator i_ndata = pool.get_iterator(not_in_pool);
CHECK(p1 == &*i_data);
CHECK(p2 != &*i_data);
CHECK(p2 == &*i_data2);
CHECK(pool.end() == i_ndata);
}
//*************************************************************************
TEST(test_get_iterator_const)
{
typedef etl::pool<Test_Data, 4> Pool;
Pool pool;
const Test_Data not_in_pool;
const Test_Data* p1 = pool.allocate();
const Test_Data* p2 = pool.allocate();
Pool::const_iterator i_data = pool.get_iterator(*p1);
Pool::const_iterator i_data2 = pool.get_iterator(*p2);
Pool::const_iterator i_ndata = pool.get_iterator(not_in_pool);
CHECK(p1 == &*i_data);
CHECK(p2 != &*i_data);
CHECK(p2 == &*i_data2);
CHECK(pool.end() == i_ndata);
}
};
}
<commit_msg>Fixed GCC warnings<commit_after>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com
Copyright(c) 2014 jwellbelove
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 <UnitTest++/UnitTest++.h>
#include "ExtraCheckMacros.h"
#include "data.h"
#include <set>
#include <vector>
#include "../src/pool.h"
#if defined(ETL_COMPILER_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
typedef TestDataDC<std::string> Test_Data;
typedef TestDataNDC<std::string> Test_Data2;
namespace
{
SUITE(test_pool)
{
//*************************************************************************
TEST(test_allocate)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1;
Test_Data* p2;
Test_Data* p3;
Test_Data* p4;
CHECK_NO_THROW(p1 = pool.allocate());
CHECK_NO_THROW(p2 = pool.allocate());
CHECK_NO_THROW(p3 = pool.allocate());
CHECK_NO_THROW(p4 = pool.allocate());
CHECK(p1 != p2);
CHECK(p1 != p3);
CHECK(p1 != p4);
CHECK(p2 != p3);
CHECK(p2 != p4);
CHECK(p3 != p4);
CHECK_THROW(pool.allocate(), etl::pool_no_allocation);
}
//*************************************************************************
TEST(test_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Test_Data* p3 = pool.allocate();
Test_Data* p4 = pool.allocate();
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(*p3));
CHECK_NO_THROW(pool.release(p1));
CHECK_NO_THROW(pool.release(*p4));
CHECK_EQUAL(4U, pool.available());
Test_Data not_in_pool;
CHECK_THROW(pool.release(not_in_pool), etl::pool_object_not_in_pool);
}
//*************************************************************************
TEST(test_allocate_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Test_Data* p3 = pool.allocate();
Test_Data* p4 = pool.allocate();
// Allocated p1, p2, p3, p4
CHECK_EQUAL(0U, pool.available());
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(p3));
// Allocated p1, p4
CHECK_EQUAL(2U, pool.available());
Test_Data* p5 = pool.allocate();
Test_Data* p6 = pool.allocate();
// Allocated p1, p4, p5, p6
CHECK_EQUAL(0U, pool.available());
CHECK(p5 != p1);
CHECK(p5 != p4);
CHECK(p6 != p1);
CHECK(p6 != p4);
CHECK_NO_THROW(pool.release(p5));
// Allocated p1, p4, p6
CHECK_EQUAL(1U, pool.available());
Test_Data* p7 = pool.allocate();
// Allocated p1, p4, p6, p7
CHECK(p7 != p1);
CHECK(p7 != p4);
CHECK(p7 != p6);
CHECK(pool.full());
}
//*************************************************************************
TEST(test_available)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(4U, pool.available());
Test_Data* p;
p = pool.allocate();
CHECK_EQUAL(3U, pool.available());
p = pool.allocate();
CHECK_EQUAL(2U, pool.available());
p = pool.allocate();
CHECK_EQUAL(1U, pool.available());
p = pool.allocate();
CHECK_EQUAL(0U, pool.available());
}
//*************************************************************************
TEST(test_max_size)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.max_size() == 4U);
}
//*************************************************************************
TEST(test_size)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(0U, pool.size());
Test_Data* p;
p = pool.allocate();
CHECK_EQUAL(1U, pool.size());
p = pool.allocate();
CHECK_EQUAL(2U, pool.size());
p = pool.allocate();
CHECK_EQUAL(3U, pool.size());
p = pool.allocate();
CHECK_EQUAL(4U, pool.size());
}
//*************************************************************************
TEST(test_empty_full)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.empty());
CHECK(!pool.full());
Test_Data* p;
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate();
CHECK(!pool.empty());
CHECK(pool.full());
}
//*************************************************************************
TEST(test_is_in_pool)
{
etl::pool<Test_Data, 4> pool;
Test_Data not_in_pool;
Test_Data* p1 = pool.allocate();
CHECK(pool.is_in_pool(p1));
CHECK(!pool.is_in_pool(not_in_pool));
}
//*************************************************************************
TEST(test_begin_empty)
{
etl::pool<Test_Data, 4> pool;
etl::pool<Test_Data, 4>::iterator it = pool.begin();
CHECK(it == pool.end());
etl::pool<Test_Data, 4>::const_iterator cit = pool.begin();
CHECK(cit == pool.end());
cit = pool.cbegin();
CHECK(cit == pool.end());
}
//*************************************************************************
TEST(test_iterator)
{
etl::pool<Test_Data2, 10> pool;
std::set<Test_Data2> compare = { Test_Data2("0"), Test_Data2("2"), Test_Data2("4"), Test_Data2("6"), Test_Data2("8") };
std::set<Test_Data2> test;
std::vector<Test_Data2*> objects;
// Build the set of objects.
objects.push_back(pool.allocate(Test_Data2("9")));
objects.push_back(pool.allocate(Test_Data2("7")));
objects.push_back(pool.allocate(Test_Data2("8")));
objects.push_back(pool.allocate(Test_Data2("6")));
objects.push_back(pool.allocate(Test_Data2("5")));
objects.push_back(pool.allocate(Test_Data2("3")));
objects.push_back(pool.allocate(Test_Data2("4")));
objects.push_back(pool.allocate(Test_Data2("2")));
objects.push_back(pool.allocate(Test_Data2("0")));
objects.push_back(pool.allocate(Test_Data2("1")));
// Release "1", "3", "5", "7", "9".
pool.release(objects[0]);
pool.release(objects[1]);
pool.release(objects[4]);
pool.release(objects[5]);
pool.release(objects[9]);
// Fill the test set with what we get from the iterator.
etl::pool<Test_Data2, 10>::iterator i_pool = pool.begin();
while (i_pool != pool.end())
{
test.insert(*i_pool);
++i_pool;
}
// Compare the results.
std::set<Test_Data2>::iterator i_compare = compare.begin();
std::set<Test_Data2>::iterator i_test = test.begin();
CHECK_EQUAL(compare.size(), test.size());
while ((i_compare != compare.end()) && (i_test != test.end()))
{
CHECK_EQUAL(*i_compare++, *i_test++);
}
}
//*************************************************************************
TEST(test_const_iterator)
{
etl::pool<Test_Data2, 10> pool;
std::set<Test_Data2> compare = { Test_Data2("0"), Test_Data2("2"), Test_Data2("4"), Test_Data2("6"), Test_Data2("8") };
std::set<Test_Data2> test;
std::vector<Test_Data2*> objects;
// Build the set of objects.
objects.push_back(pool.allocate(Test_Data2("9")));
objects.push_back(pool.allocate(Test_Data2("7")));
objects.push_back(pool.allocate(Test_Data2("8")));
objects.push_back(pool.allocate(Test_Data2("6")));
objects.push_back(pool.allocate(Test_Data2("5")));
objects.push_back(pool.allocate(Test_Data2("3")));
objects.push_back(pool.allocate(Test_Data2("4")));
objects.push_back(pool.allocate(Test_Data2("2")));
objects.push_back(pool.allocate(Test_Data2("0")));
objects.push_back(pool.allocate(Test_Data2("1")));
// Release "1", "3", "5", "7", "9".
pool.release(objects[0]);
pool.release(objects[1]);
pool.release(objects[4]);
pool.release(objects[5]);
pool.release(objects[9]);
// Fill the test set with what we get from the iterator.
etl::pool<Test_Data2, 10>::const_iterator i_pool = pool.begin();
while (i_pool != pool.end())
{
test.insert(*i_pool);
++i_pool;
}
// Compare the results.
std::set<Test_Data2>::const_iterator i_compare = compare.begin();
std::set<Test_Data2>::const_iterator i_test = test.begin();
CHECK_EQUAL(compare.size(), test.size());
while ((i_compare != compare.end()) && (i_test != test.end()))
{
CHECK_EQUAL(*i_compare++, *i_test++);
}
}
//*************************************************************************
TEST(test_get_iterator)
{
typedef etl::pool<Test_Data, 4> Pool;
Pool pool;
Test_Data not_in_pool;
Test_Data* p1 = pool.allocate();
Test_Data* p2 = pool.allocate();
Pool::iterator i_data = pool.get_iterator(*p1);
Pool::iterator i_data2 = pool.get_iterator(*p2);
Pool::iterator i_ndata = pool.get_iterator(not_in_pool);
CHECK(p1 == &*i_data);
CHECK(p2 != &*i_data);
CHECK(p2 == &*i_data2);
CHECK(pool.end() == i_ndata);
}
//*************************************************************************
TEST(test_get_iterator_const)
{
typedef etl::pool<Test_Data, 4> Pool;
Pool pool;
const Test_Data not_in_pool;
const Test_Data* p1 = pool.allocate();
const Test_Data* p2 = pool.allocate();
Pool::const_iterator i_data = pool.get_iterator(*p1);
Pool::const_iterator i_data2 = pool.get_iterator(*p2);
Pool::const_iterator i_ndata = pool.get_iterator(not_in_pool);
CHECK(p1 == &*i_data);
CHECK(p2 != &*i_data);
CHECK(p2 == &*i_data2);
CHECK(pool.end() == i_ndata);
}
};
}
#if defined(ETL_COMPILER_GCC)
#pragma GCC diagnostic pop
#endif
<|endoftext|> |
<commit_before>/*
*
* Author: Jeffrey Leung
* Last edited: 2015-09-19
*
* This C++ file tests the functionality of room.cpp.
*
*/
#include <iostream>
#include "../include/room_properties.hpp"
#include "../include/room.hpp"
// This function returns the given type of room border as a string.
std::string RoomBorderPrint( RoomBorder r )
{
switch( r )
{
case( RoomBorder::kWall ):
return "Wall";
case( RoomBorder::kRoom ):
return "Room";
case( RoomBorder::kExit ):
return "Exit";
}
return "Error: RoomBorderPrint() was given a type of RoomBorder which "\
"could not be detected.";
}
// This function returns the given type of inhabitant as a string.
std::string InhabitantPrint( Inhabitant inh )
{
switch( inh )
{
case( Inhabitant::kNone ):
return "nothing";
case( Inhabitant::kMinotaur ):
return "a Minotaur";
case( Inhabitant::kMinotaurDead ):
return "a dead Minotaur";
case( Inhabitant::kMirror ):
return "a mirror";
case( Inhabitant::kMirrorCracked ):
return "a cracked mirror";
}
return "Error: InhabitantPrint() was given a type of Inhabitant which "\
"could not be detected.";
}
// This function returns the given type of item as a string.
std::string ItemPrint( Item itm )
{
switch( itm )
{
case( Item::kNone ):
return "nothing";
case( Item::kBullet ):
return "a bullet";
case( Item::kTreasure ):
return "the treasure";
case( Item::kTreasureGone ):
return "a missing treasure";
}
return "Error: ItemPrint() was given a type of Item which "\
"could not be detected.";
}
int main()
{
std::cout << std::endl;
std::cout << "TESTING ROOM.CPP IMPLEMENTATION" << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Creating a room with:" << std::endl;
std::cout << " A minotaur" << std::endl;
std::cout << " A bullet" << std::endl;
std::cout << " An exit north of the room" << std::endl;
std::cout << " Walls to the south and west of the room" << std::endl;
std::cout << " Entrances to other rooms to the east of the room "
<< std::endl;
Room rm_1( Inhabitant::kMinotaur,
Item::kBullet,
Direction::kNorth,
false, false, true, true );
std::cout << "Completed." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing GetInhabitant() and SetInhabitant():" << std::endl;
std::cout << " The current inhabitant of the room is "
<< InhabitantPrint( rm_1.GetInhabitant() )
<< "." << std::endl;
rm_1.SetInhabitant( Inhabitant::kMirrorCracked );
std::cout << " After changing the inhabitant to a cracked mirror, the "
<< "new inhabitant is (by GetInhabitant()) "
<< InhabitantPrint( rm_1.GetInhabitant() )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing GetItem() and SetItem():" << std::endl;
std::cout << " The current item in the room is "
<< ItemPrint( rm_1.GetItem() )
<< "." << std::endl;
rm_1.SetItem( Item::kTreasureGone );
std::cout << " After changing the item to a missing treasure, the "
<< "new inhabitant is (by GetItem()) "
<< ItemPrint( rm_1.GetItem() )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing BreakWall():" << std::endl;
std::cout << " Breaking the west wall... ";
rm_1.BreakWall( Direction::kWest );
std::cout << "Completed."
<< std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing DirectionCheck():" << std::endl;
std::cout << " To the north of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kNorth) )
<< "." << std::endl;
std::cout << " To the east of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kEast) )
<< "." << std::endl;
std::cout << " To the south of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kSouth) )
<< "." << std::endl;
std::cout << " To the west of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kWest) )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "All tests completed." << std::endl;
std::cout << std::endl;
std::cout << "Press enter to exit.";
getchar();
std::cout << std::endl;
return 0;
}
<commit_msg>Room testing: Atom doing formatting mojo.<commit_after>/*
*
* Author: Jeffrey Leung
* Last edited: 2016-01-07
*
* This C++ file tests the functionality of room.cpp.
*
*/
#include <iostream>
#include "../include/room_properties.hpp"
#include "../include/room.hpp"
// This function returns the given type of room border as a string.
std::string RoomBorderPrint( RoomBorder r )
{
switch( r )
{
case( RoomBorder::kWall ):
return "Wall";
case( RoomBorder::kRoom ):
return "Room";
case( RoomBorder::kExit ):
return "Exit";
}
return "Error: RoomBorderPrint() was given a type of RoomBorder which "\
"could not be detected.";
}
// This function returns the given type of inhabitant as a string.
std::string InhabitantPrint( Inhabitant inh )
{
switch( inh )
{
case( Inhabitant::kNone ):
return "nothing";
case( Inhabitant::kMinotaur ):
return "a Minotaur";
case( Inhabitant::kMinotaurDead ):
return "a dead Minotaur";
case( Inhabitant::kMirror ):
return "a mirror";
case( Inhabitant::kMirrorCracked ):
return "a cracked mirror";
}
return "Error: InhabitantPrint() was given a type of Inhabitant which "\
"could not be detected.";
}
// This function returns the given type of item as a string.
std::string ItemPrint( Item itm )
{
switch( itm )
{
case( Item::kNone ):
return "nothing";
case( Item::kBullet ):
return "a bullet";
case( Item::kTreasure ):
return "the treasure";
case( Item::kTreasureGone ):
return "a missing treasure";
}
return "Error: ItemPrint() was given a type of Item which "\
"could not be detected.";
}
int main()
{
std::cout << std::endl;
std::cout << "TESTING ROOM.CPP IMPLEMENTATION" << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Creating a room with:" << std::endl;
std::cout << " A minotaur" << std::endl;
std::cout << " A bullet" << std::endl;
std::cout << " An exit north of the room" << std::endl;
std::cout << " Walls to the south and west of the room" << std::endl;
std::cout << " Entrances to other rooms to the east of the room "
<< std::endl;
Room rm_1( Inhabitant::kMinotaur,
Item::kBullet,
Direction::kNorth,
false, false, true, true );
std::cout << "Completed." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing GetInhabitant() and SetInhabitant():" << std::endl;
std::cout << " The current inhabitant of the room is "
<< InhabitantPrint( rm_1.GetInhabitant() )
<< "." << std::endl;
rm_1.SetInhabitant( Inhabitant::kMirrorCracked );
std::cout << " After changing the inhabitant to a cracked mirror, the "
<< "new inhabitant is (by GetInhabitant()) "
<< InhabitantPrint( rm_1.GetInhabitant() )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing GetItem() and SetItem():" << std::endl;
std::cout << " The current item in the room is "
<< ItemPrint( rm_1.GetItem() )
<< "." << std::endl;
rm_1.SetItem( Item::kTreasureGone );
std::cout << " After changing the item to a missing treasure, the "
<< "new inhabitant is (by GetItem()) "
<< ItemPrint( rm_1.GetItem() )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing BreakWall():" << std::endl;
std::cout << " Breaking the west wall... ";
rm_1.BreakWall( Direction::kWest );
std::cout << "Completed."
<< std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "Testing DirectionCheck():" << std::endl;
std::cout << " To the north of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kNorth) )
<< "." << std::endl;
std::cout << " To the east of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kEast) )
<< "." << std::endl;
std::cout << " To the south of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kSouth) )
<< "." << std::endl;
std::cout << " To the west of the room is a "
<< RoomBorderPrint( rm_1.DirectionCheck(Direction::kWest) )
<< "." << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "All tests completed." << std::endl;
std::cout << std::endl;
std::cout << "Press enter to exit.";
getchar();
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/thread.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
void check_timer_loop(mutex& m, time_point& last, condition_variable& cv)
{
mutex::scoped_lock l(m);
cv.wait(l);
l.unlock();
for (int i = 0; i < 10000; ++i)
{
mutex::scoped_lock l(m);
time_point now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
}
int test_main()
{
// make sure the time classes have correct semantics
TEST_EQUAL(total_milliseconds(milliseconds(100)), 100);
TEST_EQUAL(total_milliseconds(milliseconds(1)), 1);
TEST_EQUAL(total_milliseconds(seconds(1)), 1000);
TEST_EQUAL(total_seconds(minutes(1)), 60);
TEST_EQUAL(total_seconds(hours(1)), 3600);
// make sure it doesn't wrap at 32 bit arithmetic
TEST_EQUAL(total_seconds(seconds(281474976)), 281474976);
TEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);
// make sure the timer is monotonic
time_point now = clock_type::now();
time_point last = now;
for (int i = 0; i < 1000; ++i)
{
now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
mutex m;
condition_variable cv;
thread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
sleep(100);
cv.notify_all();
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
<commit_msg>fix test_time build<commit_after>/*
Copyright (c) 2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/thread.hpp"
#include <boost/bind.hpp>
using namespace libtorrent;
void check_timer_loop(mutex& m, time_point& last, condition_variable& cv)
{
mutex::scoped_lock l(m);
cv.wait(l);
l.unlock();
for (int i = 0; i < 10000; ++i)
{
mutex::scoped_lock l(m);
time_point now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
}
int test_main()
{
// make sure the time classes have correct semantics
TEST_EQUAL(total_milliseconds(milliseconds(100)), 100);
TEST_EQUAL(total_milliseconds(milliseconds(1)), 1);
TEST_EQUAL(total_milliseconds(seconds(1)), 1000);
TEST_EQUAL(total_seconds(minutes(1)), 60);
TEST_EQUAL(total_seconds(hours(1)), 3600);
// make sure it doesn't wrap at 32 bit arithmetic
TEST_EQUAL(total_seconds(seconds(281474976)), 281474976);
TEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);
// make sure the timer is monotonic
time_point now = clock_type::now();
time_point last = now;
for (int i = 0; i < 1000; ++i)
{
now = clock_type::now();
TEST_CHECK(now >= last);
last = now;
}
mutex m;
condition_variable cv;
thread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
thread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));
test_sleep(100);
cv.notify_all();
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include <sys/socket.h>
#include "utils.h"
#include "client_base.h"
const int WRITE_QUEUE_SIZE = -1;
int BaseClient::total_clients = 0;
BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: io(loop),
async(loop),
destroyed(false),
closed(false),
sock(sock_),
database_pool(database_pool_),
write_queue(WRITE_QUEUE_SIZE)
{
sig.set<BaseClient, &BaseClient::signal_cb>(this);
sig.start(SIGINT);
async.set<BaseClient, &BaseClient::async_cb>(this);
async.start();
io.set<BaseClient, &BaseClient::io_cb>(this);
io.start(sock, ev::READ);
}
BaseClient::~BaseClient()
{
destroy();
sig.stop();
LOG_OBJ(this, "DELETED!\n");
}
void BaseClient::signal_cb(ev::sig &signal, int revents)
{
LOG_EV(this, "Signaled destroy!!\n");
destroy();
delete this;
}
void BaseClient::destroy()
{
if (destroyed) {
return;
}
destroyed = true;
close();
// Stop and free watcher if client socket is closing
io.stop();
async.stop();
::close(sock);
LOG_OBJ(this, "DESTROYED!\n");
}
void BaseClient::close() {
if (closed) {
return;
}
closed = true;
LOG_OBJ(this, "CLOSED!\n");
}
void BaseClient::async_cb(ev::async &watcher, int revents)
{
if (destroyed) {
return;
}
LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);
if (write_queue.empty()) {
if (closed) {
destroy();
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::io_cb(ev::io &watcher, int revents)
{
if (destroyed) {
return;
}
assert(sock == watcher.fd);
LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);
if (revents & EV_ERROR) {
LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
destroy();
return;
}
if (revents & EV_READ)
read_cb(watcher);
if (revents & EV_WRITE)
write_cb(watcher);
if (write_queue.empty()) {
if (closed) {
destroy();
} else {
io.set(ev::READ);
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::write_cb(ev::io &watcher)
{
if (!write_queue.empty()) {
Buffer* buffer = write_queue.front();
size_t buf_size = buffer->nbytes();
const char * buf = buffer->dpos();
LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());
ssize_t written = ::write(sock, buf, buf_size);
if (written < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (written == 0) {
// nothing written?
} else {
buffer->pos += written;
if (buffer->nbytes() == 0) {
write_queue.pop(buffer);
delete buffer;
}
}
}
}
void BaseClient::read_cb(ev::io &watcher)
{
char buf[1024];
ssize_t received = ::read(sock, buf, sizeof(buf));
if (received < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (received == 0) {
// The peer has closed its half side of the connection.
LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
destroy();
} else {
LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
on_read(buf, received);
}
}
void BaseClient::write(const char *buf, size_t buf_size)
{
Buffer *buffer = new Buffer('\0', buf, buf_size);
write_queue.push(buffer);
async.send();
}
<commit_msg>Check for destroyed objects<commit_after>#include <assert.h>
#include <sys/socket.h>
#include "utils.h"
#include "client_base.h"
const int WRITE_QUEUE_SIZE = -1;
int BaseClient::total_clients = 0;
BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: io(loop),
async(loop),
destroyed(false),
closed(false),
sock(sock_),
database_pool(database_pool_),
write_queue(WRITE_QUEUE_SIZE)
{
sig.set<BaseClient, &BaseClient::signal_cb>(this);
sig.start(SIGINT);
async.set<BaseClient, &BaseClient::async_cb>(this);
async.start();
io.set<BaseClient, &BaseClient::io_cb>(this);
io.start(sock, ev::READ);
}
BaseClient::~BaseClient()
{
destroy();
sig.stop();
LOG_OBJ(this, "DELETED!\n");
}
void BaseClient::signal_cb(ev::sig &signal, int revents)
{
LOG_EV(this, "Signaled destroy!!\n");
destroy();
delete this;
}
void BaseClient::destroy()
{
if (destroyed) {
return;
}
destroyed = true;
close();
// Stop and free watcher if client socket is closing
io.stop();
async.stop();
::close(sock);
LOG_OBJ(this, "DESTROYED!\n");
}
void BaseClient::close() {
if (closed) {
return;
}
closed = true;
LOG_OBJ(this, "CLOSED!\n");
}
void BaseClient::async_cb(ev::async &watcher, int revents)
{
if (destroyed) {
return;
}
LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);
if (write_queue.empty()) {
if (closed) {
destroy();
}
} else {
io.set(ev::READ|ev::WRITE);
}
if (destroyed) {
delete this;
}
}
void BaseClient::io_cb(ev::io &watcher, int revents)
{
if (destroyed) {
return;
}
assert(sock == watcher.fd);
LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);
if (revents & EV_ERROR) {
LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
destroy();
return;
}
if (!destroyed && revents & EV_READ)
read_cb(watcher);
if (!destroyed && revents & EV_WRITE)
write_cb(watcher);
if (!destroyed) {
if (write_queue.empty()) {
if (closed) {
destroy();
} else {
io.set(ev::READ);
}
} else {
io.set(ev::READ|ev::WRITE);
}
}
if (destroyed) {
delete this;
}
}
void BaseClient::write_cb(ev::io &watcher)
{
if (!write_queue.empty()) {
Buffer* buffer = write_queue.front();
size_t buf_size = buffer->nbytes();
const char * buf = buffer->dpos();
LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());
ssize_t written = ::write(sock, buf, buf_size);
if (written < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (written == 0) {
// nothing written?
} else {
buffer->pos += written;
if (buffer->nbytes() == 0) {
write_queue.pop(buffer);
delete buffer;
}
}
}
}
void BaseClient::read_cb(ev::io &watcher)
{
char buf[1024];
ssize_t received = ::read(sock, buf, sizeof(buf));
if (received < 0) {
if (errno != EAGAIN) {
LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
destroy();
}
} else if (received == 0) {
// The peer has closed its half side of the connection.
LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
destroy();
} else {
LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
on_read(buf, received);
}
}
void BaseClient::write(const char *buf, size_t buf_size)
{
Buffer *buffer = new Buffer('\0', buf, buf_size);
write_queue.push(buffer);
async.send();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
*
* 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 "roommembersjob.h"
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include "../room.h"
#include "../state.h"
using namespace QMatrixClient;
class RoomMembersJob::Private
{
public:
Room* room;
QList<State*> states;
};
RoomMembersJob::RoomMembersJob(ConnectionData* data, Room* room)
: BaseJob(data, JobHttpType::GetJob, "RoomMembersJob")
, d(new Private)
{
d->room = room;
}
RoomMembersJob::~RoomMembersJob()
{
delete d;
}
QList< State* > RoomMembersJob::states()
{
return d->states;
}
QString RoomMembersJob::apiPath() const
{
return QString("_matrix/client/r0/rooms/%1/members").arg(d->room->id());
}
void RoomMembersJob::parseJson(const QJsonDocument& data)
{
QJsonObject obj = data.object();
QJsonArray chunk = obj.value("chunk").toArray();
for( const QJsonValue& val : chunk )
{
State* state = State::fromJson(val.toObject());
if( state )
d->states.append(state);
}
qDebug() << "States: " << d->states.count();
emitResult();
}
<commit_msg>Added a missing #include.<commit_after>/******************************************************************************
* Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
*
* 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 "roommembersjob.h"
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QtCore/QDebug>
#include "../room.h"
#include "../state.h"
using namespace QMatrixClient;
class RoomMembersJob::Private
{
public:
Room* room;
QList<State*> states;
};
RoomMembersJob::RoomMembersJob(ConnectionData* data, Room* room)
: BaseJob(data, JobHttpType::GetJob, "RoomMembersJob")
, d(new Private)
{
d->room = room;
}
RoomMembersJob::~RoomMembersJob()
{
delete d;
}
QList< State* > RoomMembersJob::states()
{
return d->states;
}
QString RoomMembersJob::apiPath() const
{
return QString("_matrix/client/r0/rooms/%1/members").arg(d->room->id());
}
void RoomMembersJob::parseJson(const QJsonDocument& data)
{
QJsonObject obj = data.object();
QJsonArray chunk = obj.value("chunk").toArray();
for( const QJsonValue& val : chunk )
{
State* state = State::fromJson(val.toObject());
if( state )
d->states.append(state);
}
qDebug() << "States: " << d->states.count();
emitResult();
}
<|endoftext|> |
<commit_before><commit_msg>planning: load the model file only when it exists.<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <ctype.h>
#include <cstdlib>
#include <stdexcept>
class Calculator {
private:
std::string source;
int pos;
public:
Calculator(std::string s) {
source = s;
pos = 0;
};
// Utilities
char peek() {
return source[pos];
};
bool isNumber (char ch) {
return isdigit(ch);
};
bool eof () {
return (unsigned int)pos >= source.length();
};
char consume(char ch) {
if (peek() != ch) {
throw std::runtime_error("Expected " + ch);
}
return source[pos++];
};
char consume() {
return source[pos++];
};
// Parser
float parseAdditive() {
float first = parseMultiplicative(), next;
char op;
while (peek() == '+' || peek() == '-') {
op = consume();
next = parseMultiplicative();
if (op == '+') first = first + next;
if (op == '-') first = first - next;
}
return first;
};
float parseMultiplicative() {
float first = parsePrimary(), next;
char op;
while (peek() == '*' || peek() == '/') {
op = consume();
next = parsePrimary();
if (op == '*') first = first * next;
if (op == '/') first = first / next;
}
return first;
};
float parsePrimary() {
if (peek() == '(') {
consume('(');
int expr = parseExpression();
consume(')');
return expr;
} else if (isNumber(peek())) {
return parseNum();
} else {
throw std::runtime_error("Unexpected token.");
}
return 0;
};
float parseNum() {
std::string source;
float value;
while (!eof()) {
if (isNumber(peek())) {
source += this->source[pos++];
} else {
break;
}
}
if (peek() == '.') {
source += consume('.');
while (!eof()) {
if (isNumber(peek())) {
source += this->source[pos++];
} else {
break;
}
}
}
value = atof(source.c_str());
return value;
};
float parseExpression() {
return parseAdditive();
};
};
int main() {
std::string source;
std::cout << "Enter equation (do not include space):\n";
std::getline(std::cin, source);
Calculator calc(source);
std::cout << "Result: " << calc.parseExpression();
return 0;
};
<commit_msg>Add Parsing Whitespace<commit_after>#include <iostream>
#include <string>
#include <ctype.h>
#include <cstdlib>
#include <stdexcept>
class Calculator {
private:
std::string source;
int pos;
public:
Calculator(std::string s) {
source = s;
pos = 0;
};
// Utilities
char peek() {
return source[pos];
};
bool isNumber (char ch) {
return std::isdigit(ch);
};
bool eof () {
return (unsigned int)pos >= source.length();
};
char consume(char ch) {
if (peek() != ch) {
throw std::runtime_error("Expected " + ch);
}
return source[pos++];
};
char consume() {
return source[pos++];
};
void consumeWhitespace() {
while (!eof()) {
if ( peek() == ' ' || peek() == ' ' || peek() == '\n' || peek() == '\r' ) {
pos++;
} else {
break;
}
}
};
// Parser
float parseAdditive() {
float first = parseMultiplicative(), next;
char op;
consumeWhitespace();
while (peek() == '+' || peek() == '-') {
op = consume();
consumeWhitespace();
next = parseMultiplicative();
if (op == '+') first = first + next;
if (op == '-') first = first - next;
consumeWhitespace();
}
return first;
};
float parseMultiplicative() {
float first = parsePrimary(), next;
char op;
consumeWhitespace();
while (peek() == '*' || peek() == '/') {
op = consume();
consumeWhitespace();
next = parsePrimary();
if (op == '*') first = first * next;
if (op == '/') first = first / next;
consumeWhitespace();
}
return first;
};
float parsePrimary() {
if (peek() == '(') {
consume();
consumeWhitespace();
int expr = parseExpression();
consumeWhitespace();
consume(')');
return expr;
} else if (isNumber(peek())) {
return parseNum();
} else {
throw std::runtime_error("Unexpected token.");
}
return 0;
};
float parseNum() {
std::string source;
float value;
while (!eof()) {
if (isNumber(peek())) {
source += this->source[pos++];
} else {
break;
}
}
if (peek() == '.') {
source += consume();
while (!eof()) {
if (isNumber(peek())) {
source += consume();
} else {
break;
}
}
}
value = atof(source.c_str());
return value;
};
float parseExpression() {
return parseAdditive();
};
};
int main() {
std::string source;
std::cout << "Enter equation: ";
std::getline(std::cin, source);
Calculator calc(source);
std::cout << "Result: " << calc.parseExpression();
return 0;
};
<|endoftext|> |
<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the top-down data structure graphs to implement a simple
// context sensitive alias analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
using namespace llvm;
namespace {
class DSAA : public ModulePass, public AliasAnalysis {
TDDataStructures *TD;
BUDataStructures *BU;
public:
DSAA() : TD(0) {}
//------------------------------------------------
// Implement the Pass API
//
// run - Build up the result graph, representing the pointer graph for the
// program.
//
bool runOnModule(Module &M) {
InitializeAliasAnalysis(this);
TD = &getAnalysis<TDDataStructures>();
BU = &getAnalysis<BUDataStructures>();
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll(); // Does not transform code
AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures
AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures
}
//------------------------------------------------
// Implement the AliasAnalysis API
//
AliasResult alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size);
void getMustAliases(Value *P, std::vector<Value*> &RetVals);
ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
return AliasAnalysis::getModRefInfo(CS1,CS2);
}
virtual void deleteValue(Value *V) {
BU->deleteValue(V);
TD->deleteValue(V);
}
virtual void copyValue(Value *From, Value *To) {
if (From == To) return;
BU->copyValue(From, To);
TD->copyValue(From, To);
}
private:
DSGraph *getGraphForValue(const Value *V);
};
// Register the pass...
RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis");
// Register as an implementation of AliasAnalysis
RegisterAnalysisGroup<AliasAnalysis, DSAA> Y;
}
ModulePass *llvm::createDSAAPass() { return new DSAA(); }
// getGraphForValue - Return the DSGraph to use for queries about the specified
// value...
//
DSGraph *DSAA::getGraphForValue(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return &TD->getDSGraph(*I->getParent()->getParent());
else if (const Argument *A = dyn_cast<Argument>(V))
return &TD->getDSGraph(*A->getParent());
else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return &TD->getDSGraph(*BB->getParent());
return 0;
}
// isSinglePhysicalObject - For now, the only case that we know that there is
// only one memory object in the node is when there is a single global in the
// node, and the only composition bit set is Global.
//
static bool isSinglePhysicalObject(DSNode *N) {
assert(N->isComplete() && "Can only tell if this is a complete object!");
return N->isGlobalNode() && N->getGlobals().size() == 1 &&
!N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode();
}
// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size) {
if (V1 == V2) return MustAlias;
DSGraph *G1 = getGraphForValue(V1);
DSGraph *G2 = getGraphForValue(V2);
assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?");
// Get the graph to use...
DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph()));
const DSGraph::ScalarMapTy &GSM = G.getScalarMap();
DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1);
if (I == GSM.end()) return NoAlias;
assert(I->second.getNode() && "Scalar map points to null node?");
DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2);
if (J == GSM.end()) return NoAlias;
assert(J->second.getNode() && "Scalar map points to null node?");
DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode();
unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
// We can only make a judgment of one of the nodes is complete...
if (N1->isComplete() || N2->isComplete()) {
if (N1 != N2)
return NoAlias; // Completely different nodes.
#if 0 // This does not correctly handle arrays!
// Both point to the same node and same offset, and there is only one
// physical memory object represented in the node, return must alias.
//
// FIXME: This isn't correct because we do not handle array indexing
// correctly.
if (O1 == O2 && isSinglePhysicalObject(N1))
return MustAlias; // Exactly the same object & offset
#endif
// See if they point to different offsets... if so, we may be able to
// determine that they do not alias...
if (O1 != O2) {
if (O2 < O1) { // Ensure that O1 <= O2
std::swap(V1, V2);
std::swap(O1, O2);
std::swap(V1Size, V2Size);
}
// FIXME: This is not correct because we do not handle array
// indexing correctly with this check!
//if (O1+V1Size <= O2) return NoAlias;
}
}
// FIXME: we could improve on this by checking the globals graph for aliased
// global queries...
return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}
/// getModRefInfo - does a callsite modify or reference a value?
///
AliasAnalysis::ModRefResult
DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
Function *F = CS.getCalledFunction();
if (!F) return pointsToConstantMemory(P) ? Ref : ModRef;
if (F->isExternal()) return ModRef;
// Clone the function TD graph, clearing off Mod/Ref flags
const Function *csParent = CS.getInstruction()->getParent()->getParent();
DSGraph TDGraph(TD->getDSGraph(*csParent));
TDGraph.maskNodeTypes(0);
// Insert the callee's BU graph into the TD graph
const DSGraph &BUGraph = BU->getDSGraph(*F);
TDGraph.mergeInGraph(TDGraph.getDSCallSiteForCallSite(CS),
*F, BUGraph, 0);
// Report the flags that have been added
const DSNodeHandle &DSH = TDGraph.getNodeForValue(P);
if (const DSNode *N = DSH.getNode())
if (N->isModified())
return N->isRead() ? ModRef : Mod;
else
return N->isRead() ? Ref : NoModRef;
return NoModRef;
}
/// getMustAliases - If there are any pointers known that must alias this
/// pointer, return them now. This allows alias-set based alias analyses to
/// perform a form a value numbering (which is exposed by load-vn). If an alias
/// analysis supports this, it should ADD any must aliased pointers to the
/// specified vector.
///
void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
#if 0 // This does not correctly handle arrays!
// Currently the only must alias information we can provide is to say that
// something is equal to a global value. If we already have a global value,
// don't get worked up about it.
if (!isa<GlobalValue>(P)) {
DSGraph *G = getGraphForValue(P);
if (!G) G = &TD->getGlobalsGraph();
// The only must alias information we can currently determine occurs when
// the node for P is a global node with only one entry.
DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P);
if (I != G->getScalarMap().end()) {
DSNode *N = I->second.getNode();
if (N->isComplete() && isSinglePhysicalObject(N))
RetVals.push_back(N->getGlobals()[0]);
}
}
#endif
return AliasAnalysis::getMustAliases(P, RetVals);
}
<commit_msg>Two changes: 1. Chain to the parent implementation of M/R analysis if we can't find any information. It has some heuristics that often do well. 2. Do not clear all flags, this can make invalid nodes by turning nodes that used to be collapsed into non-collapsed nodes (fixing crashes)<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the top-down data structure graphs to implement a simple
// context sensitive alias analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
using namespace llvm;
namespace {
class DSAA : public ModulePass, public AliasAnalysis {
TDDataStructures *TD;
BUDataStructures *BU;
public:
DSAA() : TD(0) {}
//------------------------------------------------
// Implement the Pass API
//
// run - Build up the result graph, representing the pointer graph for the
// program.
//
bool runOnModule(Module &M) {
InitializeAliasAnalysis(this);
TD = &getAnalysis<TDDataStructures>();
BU = &getAnalysis<BUDataStructures>();
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll(); // Does not transform code
AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures
AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures
}
//------------------------------------------------
// Implement the AliasAnalysis API
//
AliasResult alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size);
void getMustAliases(Value *P, std::vector<Value*> &RetVals);
ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
return AliasAnalysis::getModRefInfo(CS1,CS2);
}
virtual void deleteValue(Value *V) {
BU->deleteValue(V);
TD->deleteValue(V);
}
virtual void copyValue(Value *From, Value *To) {
if (From == To) return;
BU->copyValue(From, To);
TD->copyValue(From, To);
}
private:
DSGraph *getGraphForValue(const Value *V);
};
// Register the pass...
RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis");
// Register as an implementation of AliasAnalysis
RegisterAnalysisGroup<AliasAnalysis, DSAA> Y;
}
ModulePass *llvm::createDSAAPass() { return new DSAA(); }
// getGraphForValue - Return the DSGraph to use for queries about the specified
// value...
//
DSGraph *DSAA::getGraphForValue(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return &TD->getDSGraph(*I->getParent()->getParent());
else if (const Argument *A = dyn_cast<Argument>(V))
return &TD->getDSGraph(*A->getParent());
else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return &TD->getDSGraph(*BB->getParent());
return 0;
}
// isSinglePhysicalObject - For now, the only case that we know that there is
// only one memory object in the node is when there is a single global in the
// node, and the only composition bit set is Global.
//
static bool isSinglePhysicalObject(DSNode *N) {
assert(N->isComplete() && "Can only tell if this is a complete object!");
return N->isGlobalNode() && N->getGlobals().size() == 1 &&
!N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode();
}
// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size) {
if (V1 == V2) return MustAlias;
DSGraph *G1 = getGraphForValue(V1);
DSGraph *G2 = getGraphForValue(V2);
assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?");
// Get the graph to use...
DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph()));
const DSGraph::ScalarMapTy &GSM = G.getScalarMap();
DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1);
if (I == GSM.end()) return NoAlias;
assert(I->second.getNode() && "Scalar map points to null node?");
DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2);
if (J == GSM.end()) return NoAlias;
assert(J->second.getNode() && "Scalar map points to null node?");
DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode();
unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
// We can only make a judgment of one of the nodes is complete...
if (N1->isComplete() || N2->isComplete()) {
if (N1 != N2)
return NoAlias; // Completely different nodes.
#if 0 // This does not correctly handle arrays!
// Both point to the same node and same offset, and there is only one
// physical memory object represented in the node, return must alias.
//
// FIXME: This isn't correct because we do not handle array indexing
// correctly.
if (O1 == O2 && isSinglePhysicalObject(N1))
return MustAlias; // Exactly the same object & offset
#endif
// See if they point to different offsets... if so, we may be able to
// determine that they do not alias...
if (O1 != O2) {
if (O2 < O1) { // Ensure that O1 <= O2
std::swap(V1, V2);
std::swap(O1, O2);
std::swap(V1Size, V2Size);
}
// FIXME: This is not correct because we do not handle array
// indexing correctly with this check!
//if (O1+V1Size <= O2) return NoAlias;
}
}
// FIXME: we could improve on this by checking the globals graph for aliased
// global queries...
return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}
/// getModRefInfo - does a callsite modify or reference a value?
///
AliasAnalysis::ModRefResult
DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
Function *F = CS.getCalledFunction();
if (!F || F->isExternal())
return AliasAnalysis::getModRefInfo(CS, P, Size);
// Clone the function TD graph, clearing off Mod/Ref flags
const Function *csParent = CS.getInstruction()->getParent()->getParent();
DSGraph TDGraph(TD->getDSGraph(*csParent));
TDGraph.maskNodeTypes(~(DSNode::Modified|DSNode::Read));
// Insert the callee's BU graph into the TD graph
const DSGraph &BUGraph = BU->getDSGraph(*F);
TDGraph.mergeInGraph(TDGraph.getDSCallSiteForCallSite(CS),
*F, BUGraph, 0);
// Report the flags that have been added
const DSNodeHandle &DSH = TDGraph.getNodeForValue(P);
if (const DSNode *N = DSH.getNode())
if (N->isModified())
return N->isRead() ? ModRef : Mod;
else
return N->isRead() ? Ref : NoModRef;
return NoModRef;
}
/// getMustAliases - If there are any pointers known that must alias this
/// pointer, return them now. This allows alias-set based alias analyses to
/// perform a form a value numbering (which is exposed by load-vn). If an alias
/// analysis supports this, it should ADD any must aliased pointers to the
/// specified vector.
///
void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
#if 0 // This does not correctly handle arrays!
// Currently the only must alias information we can provide is to say that
// something is equal to a global value. If we already have a global value,
// don't get worked up about it.
if (!isa<GlobalValue>(P)) {
DSGraph *G = getGraphForValue(P);
if (!G) G = &TD->getGlobalsGraph();
// The only must alias information we can currently determine occurs when
// the node for P is a global node with only one entry.
DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P);
if (I != G->getScalarMap().end()) {
DSNode *N = I->second.getNode();
if (N->isComplete() && isSinglePhysicalObject(N))
RetVals.push_back(N->getGlobals()[0]);
}
}
#endif
return AliasAnalysis::getMustAliases(P, RetVals);
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <cstdio>
#include <cstdarg>
#include "ir_reader.h"
#include "glsl_parser_extras.h"
#include "glsl_types.h"
#include "s_expression.h"
static void ir_read_error(s_expression *expr, const char *fmt, ...);
static glsl_type *read_type(_mesa_glsl_parse_state *, s_expression *);
static ir_rvalue *read_rvalue(_mesa_glsl_parse_state *, s_expression *);
static ir_assignment *read_assignment(_mesa_glsl_parse_state *, s_list *);
static ir_expression *read_expression(_mesa_glsl_parse_state *, s_list *);
static ir_swizzle *read_swizzle(_mesa_glsl_parse_state *, s_list *);
static ir_constant *read_constant(_mesa_glsl_parse_state *, s_list *);
void
_mesa_glsl_read_ir(_mesa_glsl_parse_state *state, exec_list *instructions,
const char *src)
{
s_expression *expr = s_expression::read_expression(src);
if (expr == NULL) {
ir_read_error(NULL, "couldn't parse S-Expression.");
state->error = true;
return;
}
printf("S-Expression:\n");
expr->print();
printf("\n-------------\n");
_mesa_glsl_initialize_types(state);
_mesa_glsl_initialize_variables(instructions, state);
_mesa_glsl_initialize_constructors(instructions, state);
_mesa_glsl_initialize_functions(instructions, state);
// FINISHME: Only reading rvalues...for testing.
ir_instruction *ir = read_rvalue(state, SX_AS_LIST(expr));
if (ir == NULL) {
ir_read_error(NULL, "No IR\n");
state->error = true;
return;
}
instructions->push_tail(ir);
}
static void
ir_read_error(s_expression *expr, const char *fmt, ...)
{
char buf[1024];
int len;
va_list ap;
// FIXME: state->error = true;
len = snprintf(buf, sizeof(buf), "error: ");
va_start(ap, fmt);
vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
va_end(ap);
printf("%s\n", buf);
}
static glsl_type *
read_type(_mesa_glsl_parse_state *st, s_expression *expr)
{
s_list *list = SX_AS_LIST(expr);
if (list != NULL) {
s_symbol *type_sym = SX_AS_SYMBOL(list->subexpressions.get_head());
if (type_sym == NULL) {
ir_read_error(expr, "expected type (array (...)) or (struct (...))");
return NULL;
}
if (strcmp(type_sym->value(), "array") == 0)
assert(false); // FINISHME
if (strcmp(type_sym->value(), "struct") == 0)
assert(false); // FINISHME
}
s_symbol *type_sym = SX_AS_SYMBOL(expr);
if (type_sym == NULL) {
ir_read_error(expr, "expected <type> (symbol or list)");
return NULL;
}
glsl_type *type = st->symbols->get_type(type_sym->value());
if (type == NULL)
ir_read_error(expr, "invalid type: %s", type_sym->value());
return type;
}
static ir_rvalue *
read_rvalue(_mesa_glsl_parse_state *st, s_expression *expr)
{
s_list *list = SX_AS_LIST(expr);
if (list == NULL || list->subexpressions.is_empty())
return NULL;
s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
if (tag == NULL) {
ir_read_error(expr, "expected rvalue tag");
return NULL;
}
ir_rvalue *rvalue = NULL;
if (strcmp(tag->value(), "swiz") == 0)
rvalue = read_swizzle(st, list);
else if (strcmp(tag->value(), "assign") == 0)
rvalue = read_assignment(st, list);
else if (strcmp(tag->value(), "expression") == 0)
rvalue = read_expression(st, list);
// FINISHME: ir_call
// FINISHME: dereference
else if (strcmp(tag->value(), "constant") == 0)
rvalue = read_constant(st, list);
else
ir_read_error(expr, "unrecognized rvalue tag: %s", tag->value());
return rvalue;
}
static ir_assignment *
read_assignment(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 4) {
ir_read_error(list, "expected (assign <condition> <lhs> <rhs>)");
return NULL;
}
s_expression *cond_expr = (s_expression*) list->subexpressions.head->next;
s_expression *lhs_expr = (s_expression*) cond_expr->next;
s_expression *rhs_expr = (s_expression*) lhs_expr->next;
// FINISHME: Deal with "true" condition
ir_rvalue *condition = read_rvalue(st, cond_expr);
if (condition == NULL) {
ir_read_error(list, "when reading condition of assignment");
return NULL;
}
ir_rvalue *lhs = read_rvalue(st, lhs_expr);
if (lhs == NULL) {
ir_read_error(list, "when reading left-hand side of assignment");
return NULL;
}
ir_rvalue *rhs = read_rvalue(st, rhs_expr);
if (rhs == NULL) {
ir_read_error(list, "when reading right-hand side of assignment");
return NULL;
}
return new ir_assignment(lhs, rhs, condition);
}
static ir_expression *
read_expression(_mesa_glsl_parse_state *st, s_list *list)
{
const unsigned list_length = list->length();
if (list_length < 4) {
ir_read_error(list, "expected (expression <type> <operator> <operand> "
"[<operand>])");
return NULL;
}
s_expression *type_expr = (s_expression*) list->subexpressions.head->next;
glsl_type *type = read_type(st, type_expr);
if (type == NULL)
return NULL;
/* Read the operator */
s_symbol *op_sym = SX_AS_SYMBOL(type_expr->next);
if (op_sym == NULL) {
ir_read_error(list, "expected operator, found non-symbol");
return NULL;
}
ir_expression_operation op = ir_expression::get_operator(op_sym->value());
if (op == (ir_expression_operation) -1) {
ir_read_error(list, "invalid operator: %s", op_sym->value());
return NULL;
}
/* Now that we know the operator, check for the right number of operands */
if (ir_expression::get_num_operands(op) == 2) {
if (list_length != 5) {
ir_read_error(list, "expected (expression %s <operand1> <operand2>)",
op_sym->value());
return NULL;
}
} else {
if (list_length != 4) {
ir_read_error(list, "expected (expression %s <operand>)",
op_sym->value());
return NULL;
}
}
s_expression *exp1 = (s_expression*) (op_sym->next);
ir_rvalue *arg1 = read_rvalue(st, exp1);
if (arg1 == NULL) {
ir_read_error(list, "when reading first operand of %s", op_sym->value());
return NULL;
}
ir_rvalue *arg2 = NULL;
if (ir_expression::get_num_operands(op) == 2) {
s_expression *exp2 = (s_expression*) (exp1->next);
arg2 = read_rvalue(st, exp2);
if (arg2 == NULL) {
ir_read_error(list, "when reading second operand of %s",
op_sym->value());
return NULL;
}
}
return new ir_expression(op, type, arg1, arg2);
}
static ir_swizzle *
read_swizzle(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 3) {
ir_read_error(list, "expected (swiz <swizzle> <rvalue>)");
return NULL;
}
s_symbol *swiz = SX_AS_SYMBOL(list->subexpressions.head->next);
if (swiz == NULL) {
ir_read_error(list, "expected a valid swizzle; found non-symbol");
return NULL;
}
unsigned num_components = strlen(swiz->value());
if (num_components > 4) {
ir_read_error(list, "expected a valid swizzle; found %s", swiz->value());
return NULL;
}
s_expression *sub = (s_expression*) swiz->next;
if (sub == NULL) {
ir_read_error(list, "expected rvalue: (swizzle %s <rvalue>)", swiz->value());
return NULL;
}
ir_rvalue *rvalue = read_rvalue(st, sub);
if (rvalue == NULL)
return NULL;
return ir_swizzle::create(rvalue, swiz->value(), num_components);
}
static ir_constant *
read_constant(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 3) {
ir_read_error(list, "expected (constant <type> (<num> ... <num>))");
return NULL;
}
s_expression *type_expr = (s_expression*) list->subexpressions.head->next;
glsl_type *type = read_type(st, type_expr);
if (type == NULL)
return NULL;
s_list *values = SX_AS_LIST(type_expr->next);
if (values == NULL) {
ir_read_error(list, "expected (constant <type> (<num> ... <num>))");
return NULL;
}
const glsl_type *const base_type = type->get_base_type();
unsigned u[16];
int i[16];
float f[16];
bool b[16];
// Read in list of values (at most 16).
int k = 0;
foreach_iter(exec_list_iterator, it, values->subexpressions) {
if (k >= 16) {
ir_read_error(values, "expected at most 16 numbers");
return NULL;
}
s_expression *expr = (s_expression*) it.get();
if (base_type->base_type == GLSL_TYPE_FLOAT) {
s_number *value = SX_AS_NUMBER(expr);
if (value == NULL) {
ir_read_error(values, "expected numbers");
return NULL;
}
f[k] = value->fvalue();
} else {
s_int *value = SX_AS_INT(expr);
if (value == NULL) {
ir_read_error(values, "expected integers");
return NULL;
}
switch (base_type->base_type) {
case GLSL_TYPE_UINT: {
u[k] = value->value();
break;
}
case GLSL_TYPE_INT: {
i[k] = value->value();
break;
}
case GLSL_TYPE_BOOL: {
b[k] = value->value();
break;
}
default:
ir_read_error(values, "unsupported constant type");
return NULL;
}
}
++k;
}
switch (base_type->base_type) {
case GLSL_TYPE_UINT:
return new ir_constant(type, u);
case GLSL_TYPE_INT:
return new ir_constant(type, i);
case GLSL_TYPE_BOOL:
return new ir_constant(type, b);
case GLSL_TYPE_FLOAT:
return new ir_constant(type, f);
}
return NULL; // should not be reached
}
<commit_msg>ir_reader: Add support for reading variable declarations.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <cstdio>
#include <cstdarg>
#include "ir_reader.h"
#include "glsl_parser_extras.h"
#include "glsl_types.h"
#include "s_expression.h"
static void ir_read_error(s_expression *expr, const char *fmt, ...);
static glsl_type *read_type(_mesa_glsl_parse_state *, s_expression *);
static ir_instruction *read_instruction(_mesa_glsl_parse_state *,
s_expression *);
static ir_variable *read_declaration(_mesa_glsl_parse_state *, s_list *);
static ir_rvalue *read_rvalue(_mesa_glsl_parse_state *, s_expression *);
static ir_assignment *read_assignment(_mesa_glsl_parse_state *, s_list *);
static ir_expression *read_expression(_mesa_glsl_parse_state *, s_list *);
static ir_swizzle *read_swizzle(_mesa_glsl_parse_state *, s_list *);
static ir_constant *read_constant(_mesa_glsl_parse_state *, s_list *);
void
_mesa_glsl_read_ir(_mesa_glsl_parse_state *state, exec_list *instructions,
const char *src)
{
s_expression *expr = s_expression::read_expression(src);
if (expr == NULL) {
ir_read_error(NULL, "couldn't parse S-Expression.");
state->error = true;
return;
}
printf("S-Expression:\n");
expr->print();
printf("\n-------------\n");
_mesa_glsl_initialize_types(state);
_mesa_glsl_initialize_variables(instructions, state);
_mesa_glsl_initialize_constructors(instructions, state);
_mesa_glsl_initialize_functions(instructions, state);
// Read in a list of instructions
s_list *list = SX_AS_LIST(expr);
if (list == NULL) {
ir_read_error(expr, "Expected (<instruction> ...); found an atom.");
state->error = true;
return;
}
foreach_iter(exec_list_iterator, it, list->subexpressions) {
s_expression *sub = (s_expression*) it.get();
ir_instruction *ir = read_instruction(state, sub);
if (ir == NULL) {
ir_read_error(sub, "Invalid instruction.\n");
state->error = true;
return;
}
instructions->push_tail(ir);
}
}
static void
ir_read_error(s_expression *expr, const char *fmt, ...)
{
char buf[1024];
int len;
va_list ap;
// FIXME: state->error = true;
len = snprintf(buf, sizeof(buf), "error: ");
va_start(ap, fmt);
vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
va_end(ap);
printf("%s\n", buf);
}
static glsl_type *
read_type(_mesa_glsl_parse_state *st, s_expression *expr)
{
s_list *list = SX_AS_LIST(expr);
if (list != NULL) {
s_symbol *type_sym = SX_AS_SYMBOL(list->subexpressions.get_head());
if (type_sym == NULL) {
ir_read_error(expr, "expected type (array (...)) or (struct (...))");
return NULL;
}
if (strcmp(type_sym->value(), "array") == 0)
assert(false); // FINISHME
if (strcmp(type_sym->value(), "struct") == 0)
assert(false); // FINISHME
}
s_symbol *type_sym = SX_AS_SYMBOL(expr);
if (type_sym == NULL) {
ir_read_error(expr, "expected <type> (symbol or list)");
return NULL;
}
glsl_type *type = st->symbols->get_type(type_sym->value());
if (type == NULL)
ir_read_error(expr, "invalid type: %s", type_sym->value());
return type;
}
static ir_instruction *
read_instruction(_mesa_glsl_parse_state *st, s_expression *expr)
{
s_list *list = SX_AS_LIST(expr);
if (list == NULL || list->subexpressions.is_empty())
return NULL;
s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
if (tag == NULL) {
ir_read_error(expr, "expected instruction tag");
return NULL;
}
ir_instruction *inst = NULL;
if (strcmp(tag->value(), "declare") == 0)
inst = read_declaration(st, list);
else
ir_read_error(expr, "unrecognized instruction tag: %s", tag->value());
return inst;
}
static ir_variable *
read_declaration(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 4) {
ir_read_error(list, "expected (declare (<qualifiers>) <type> <name>)");
return NULL;
}
s_list *quals = SX_AS_LIST(list->subexpressions.head->next);
if (quals == NULL) {
ir_read_error(list, "expected a list of variable qualifiers");
return NULL;
}
s_expression *type_expr = (s_expression*) quals->next;
glsl_type *type = read_type(st, type_expr);
if (type == NULL)
return NULL;
s_symbol *var_name = SX_AS_SYMBOL(type_expr->next);
if (var_name == NULL) {
ir_read_error(list, "expected variable name, found non-symbol");
return NULL;
}
ir_variable *var = new ir_variable(type, var_name->value());
foreach_iter(exec_list_iterator, it, quals->subexpressions) {
s_symbol *qualifier = SX_AS_SYMBOL(it.get());
if (qualifier == NULL) {
ir_read_error(list, "qualifier list must contain only symbols");
delete var;
return NULL;
}
// FINISHME: Check for duplicate/conflicting qualifiers.
if (strcmp(qualifier->value(), "centroid") == 0) {
var->centroid = 1;
} else if (strcmp(qualifier->value(), "invariant") == 0) {
var->invariant = 1;
} else if (strcmp(qualifier->value(), "uniform") == 0) {
var->mode = ir_var_uniform;
} else if (strcmp(qualifier->value(), "auto") == 0) {
var->mode = ir_var_auto;
} else if (strcmp(qualifier->value(), "in") == 0) {
var->mode = ir_var_in;
} else if (strcmp(qualifier->value(), "out") == 0) {
var->mode = ir_var_out;
} else if (strcmp(qualifier->value(), "inout") == 0) {
var->mode = ir_var_inout;
} else if (strcmp(qualifier->value(), "smooth") == 0) {
var->interpolation = ir_var_smooth;
} else if (strcmp(qualifier->value(), "flat") == 0) {
var->interpolation = ir_var_flat;
} else if (strcmp(qualifier->value(), "noperspective") == 0) {
var->interpolation = ir_var_noperspective;
} else {
ir_read_error(list, "unknown qualifier: %s", qualifier->value());
delete var;
return NULL;
}
}
// Add the variable to the symbol table
st->symbols->add_variable(var_name->value(), var);
return var;
}
static ir_rvalue *
read_rvalue(_mesa_glsl_parse_state *st, s_expression *expr)
{
s_list *list = SX_AS_LIST(expr);
if (list == NULL || list->subexpressions.is_empty())
return NULL;
s_symbol *tag = SX_AS_SYMBOL(list->subexpressions.get_head());
if (tag == NULL) {
ir_read_error(expr, "expected rvalue tag");
return NULL;
}
ir_rvalue *rvalue = NULL;
if (strcmp(tag->value(), "swiz") == 0)
rvalue = read_swizzle(st, list);
else if (strcmp(tag->value(), "assign") == 0)
rvalue = read_assignment(st, list);
else if (strcmp(tag->value(), "expression") == 0)
rvalue = read_expression(st, list);
// FINISHME: ir_call
// FINISHME: dereference
else if (strcmp(tag->value(), "constant") == 0)
rvalue = read_constant(st, list);
else
ir_read_error(expr, "unrecognized rvalue tag: %s", tag->value());
return rvalue;
}
static ir_assignment *
read_assignment(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 4) {
ir_read_error(list, "expected (assign <condition> <lhs> <rhs>)");
return NULL;
}
s_expression *cond_expr = (s_expression*) list->subexpressions.head->next;
s_expression *lhs_expr = (s_expression*) cond_expr->next;
s_expression *rhs_expr = (s_expression*) lhs_expr->next;
// FINISHME: Deal with "true" condition
ir_rvalue *condition = read_rvalue(st, cond_expr);
if (condition == NULL) {
ir_read_error(list, "when reading condition of assignment");
return NULL;
}
ir_rvalue *lhs = read_rvalue(st, lhs_expr);
if (lhs == NULL) {
ir_read_error(list, "when reading left-hand side of assignment");
return NULL;
}
ir_rvalue *rhs = read_rvalue(st, rhs_expr);
if (rhs == NULL) {
ir_read_error(list, "when reading right-hand side of assignment");
return NULL;
}
return new ir_assignment(lhs, rhs, condition);
}
static ir_expression *
read_expression(_mesa_glsl_parse_state *st, s_list *list)
{
const unsigned list_length = list->length();
if (list_length < 4) {
ir_read_error(list, "expected (expression <type> <operator> <operand> "
"[<operand>])");
return NULL;
}
s_expression *type_expr = (s_expression*) list->subexpressions.head->next;
glsl_type *type = read_type(st, type_expr);
if (type == NULL)
return NULL;
/* Read the operator */
s_symbol *op_sym = SX_AS_SYMBOL(type_expr->next);
if (op_sym == NULL) {
ir_read_error(list, "expected operator, found non-symbol");
return NULL;
}
ir_expression_operation op = ir_expression::get_operator(op_sym->value());
if (op == (ir_expression_operation) -1) {
ir_read_error(list, "invalid operator: %s", op_sym->value());
return NULL;
}
/* Now that we know the operator, check for the right number of operands */
if (ir_expression::get_num_operands(op) == 2) {
if (list_length != 5) {
ir_read_error(list, "expected (expression %s <operand1> <operand2>)",
op_sym->value());
return NULL;
}
} else {
if (list_length != 4) {
ir_read_error(list, "expected (expression %s <operand>)",
op_sym->value());
return NULL;
}
}
s_expression *exp1 = (s_expression*) (op_sym->next);
ir_rvalue *arg1 = read_rvalue(st, exp1);
if (arg1 == NULL) {
ir_read_error(list, "when reading first operand of %s", op_sym->value());
return NULL;
}
ir_rvalue *arg2 = NULL;
if (ir_expression::get_num_operands(op) == 2) {
s_expression *exp2 = (s_expression*) (exp1->next);
arg2 = read_rvalue(st, exp2);
if (arg2 == NULL) {
ir_read_error(list, "when reading second operand of %s",
op_sym->value());
return NULL;
}
}
return new ir_expression(op, type, arg1, arg2);
}
static ir_swizzle *
read_swizzle(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 3) {
ir_read_error(list, "expected (swiz <swizzle> <rvalue>)");
return NULL;
}
s_symbol *swiz = SX_AS_SYMBOL(list->subexpressions.head->next);
if (swiz == NULL) {
ir_read_error(list, "expected a valid swizzle; found non-symbol");
return NULL;
}
unsigned num_components = strlen(swiz->value());
if (num_components > 4) {
ir_read_error(list, "expected a valid swizzle; found %s", swiz->value());
return NULL;
}
s_expression *sub = (s_expression*) swiz->next;
if (sub == NULL) {
ir_read_error(list, "expected rvalue: (swizzle %s <rvalue>)", swiz->value());
return NULL;
}
ir_rvalue *rvalue = read_rvalue(st, sub);
if (rvalue == NULL)
return NULL;
return ir_swizzle::create(rvalue, swiz->value(), num_components);
}
static ir_constant *
read_constant(_mesa_glsl_parse_state *st, s_list *list)
{
if (list->length() != 3) {
ir_read_error(list, "expected (constant <type> (<num> ... <num>))");
return NULL;
}
s_expression *type_expr = (s_expression*) list->subexpressions.head->next;
glsl_type *type = read_type(st, type_expr);
if (type == NULL)
return NULL;
s_list *values = SX_AS_LIST(type_expr->next);
if (values == NULL) {
ir_read_error(list, "expected (constant <type> (<num> ... <num>))");
return NULL;
}
const glsl_type *const base_type = type->get_base_type();
unsigned u[16];
int i[16];
float f[16];
bool b[16];
// Read in list of values (at most 16).
int k = 0;
foreach_iter(exec_list_iterator, it, values->subexpressions) {
if (k >= 16) {
ir_read_error(values, "expected at most 16 numbers");
return NULL;
}
s_expression *expr = (s_expression*) it.get();
if (base_type->base_type == GLSL_TYPE_FLOAT) {
s_number *value = SX_AS_NUMBER(expr);
if (value == NULL) {
ir_read_error(values, "expected numbers");
return NULL;
}
f[k] = value->fvalue();
} else {
s_int *value = SX_AS_INT(expr);
if (value == NULL) {
ir_read_error(values, "expected integers");
return NULL;
}
switch (base_type->base_type) {
case GLSL_TYPE_UINT: {
u[k] = value->value();
break;
}
case GLSL_TYPE_INT: {
i[k] = value->value();
break;
}
case GLSL_TYPE_BOOL: {
b[k] = value->value();
break;
}
default:
ir_read_error(values, "unsupported constant type");
return NULL;
}
}
++k;
}
switch (base_type->base_type) {
case GLSL_TYPE_UINT:
return new ir_constant(type, u);
case GLSL_TYPE_INT:
return new ir_constant(type, i);
case GLSL_TYPE_BOOL:
return new ir_constant(type, b);
case GLSL_TYPE_FLOAT:
return new ir_constant(type, f);
}
return NULL; // should not be reached
}
<|endoftext|> |
<commit_before>// @(#)root/net:$Id$
// Author: Fons Rademakers 18/12/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TServerSocket //
// //
// This class implements server sockets. A server socket waits for //
// requests to come in over the network. It performs some operation //
// based on that request and then possibly returns a full duplex socket //
// to the requester. The actual work is done via the TSystem class //
// (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TServerSocket.h"
#include "TSocket.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TError.h"
#include <string>
#include "TVirtualMutex.h"
// Hook to server authentication wrapper
SrvAuth_t TServerSocket::fgSrvAuthHook = 0;
SrvClup_t TServerSocket::fgSrvAuthClupHook = 0;
// Defaul options for accept
UChar_t TServerSocket::fgAcceptOpt = kSrvNoAuth;
TVirtualMutex *gSrvAuthenticateMutex = 0;
ClassImp(TServerSocket)
//______________________________________________________________________________
static void setaccopt(UChar_t &Opt, UChar_t Mod)
{
// Kind of macro to parse input options
// Modify Opt according to modifier Mod
R__LOCKGUARD2(gSrvAuthenticateMutex);
if (!Mod) return;
if ((Mod & kSrvAuth)) Opt |= kSrvAuth;
if ((Mod & kSrvNoAuth)) Opt &= ~kSrvAuth;
}
//______________________________________________________________________________
TServerSocket::TServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize)
{
// Create a server socket object for a named service. Set reuse to true
// to force reuse of the server socket (i.e. do not wait for the time
// out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
R__ASSERT(gROOT);
R__ASSERT(gSystem);
SetName("ServerSocket");
fSecContext = 0;
fSecContexts = new TList;
// If this is a local path, try announcing a UNIX socket service
ResetBit(TSocket::kIsUnix);
if (service && (!gSystem->AccessPathName(service) ||
#ifndef WIN32
service[0] == '/')) {
#else
service[0] == '/' || (service[1] == ':' && service[2] == '/'))) {
#endif
SetBit(TSocket::kIsUnix);
fService = "unix:";
fService += service;
fSocket = gSystem->AnnounceUnixService(service, backlog);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
} else {
// TCP / UDP socket
fService = service;
int port = gSystem->GetServiceByName(service);
if (port != -1) {
fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
} else {
fSocket = -1;
}
}
}
//______________________________________________________________________________
TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize)
{
// Create a server socket object on a specified port. Set reuse to true
// to force reuse of the server socket (i.e. do not wait for the time
// out to pass). Using backlog one can set the desirable queue length
// for pending connections. If port is 0 a port scan will be done to
// find a free port. This option is mutual exlusive with the reuse option.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
R__ASSERT(gROOT);
R__ASSERT(gSystem);
SetName("ServerSocket");
fSecContext = 0;
fSecContexts = new TList;
fService = gSystem->GetServiceByPort(port);
SetTitle(fService);
fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
}
//______________________________________________________________________________
TServerSocket::~TServerSocket()
{
// Destructor: cleanup authentication stuff (if any) and close
R__LOCKGUARD2(gSrvAuthenticateMutex);
if (fSecContexts && fgSrvAuthClupHook) {
// Cleanup the security contexts
(*fgSrvAuthClupHook)(fSecContexts);
// Remove the list
fSecContexts->Delete();
SafeDelete(fSecContexts);
fSecContexts = 0;
}
Close();
}
//______________________________________________________________________________
TSocket *TServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a server socket. Returns a full-duplex
// communication TSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
//
// Opt can be used to require client authentication; valid options are
//
// kSrvAuth = require client authentication
// kSrvNoAuth = force no client authentication
//
// Example: use Opt = kSrvAuth to require client authentication.
//
// Default options are taken from fgAcceptOpt and are initially
// equivalent to kSrvNoAuth; they can be changed with the static
// method TServerSocket::SetAcceptOptions(Opt).
// The active defaults can be visualized using the static method
// TServerSocket::ShowAcceptOptions().
//
if (fSocket == -1) { return 0; }
TSocket *socket = new TSocket;
Int_t soc = gSystem->AcceptConnection(fSocket);
if (soc == -1) { delete socket; return 0; }
if (soc == -2) { delete socket; return (TSocket*) -1; }
// Parse Opt
UChar_t acceptOpt = fgAcceptOpt;
setaccopt(acceptOpt,Opt);
Bool_t auth = (Bool_t)(acceptOpt & kSrvAuth);
socket->fSocket = soc;
socket->fSecContext = 0;
socket->fService = fService;
if (!TestBit(TSocket::kIsUnix))
socket->fAddress = gSystem->GetPeerName(socket->fSocket);
if (socket->fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(socket);
}
// Perform authentication, if required
if (auth) {
if (!Authenticate(socket)) {
delete socket;
socket = 0;
}
}
return socket;
}
//______________________________________________________________________________
TInetAddress TServerSocket::GetLocalInetAddress()
{
// Return internet address of host to which the server socket is bound,
// i.e. the local host. In case of error TInetAddress::IsValid() returns
// kFALSE.
if (fSocket != -1) {
if (fAddress.GetPort() == -1)
fAddress = gSystem->GetSockName(fSocket);
return fAddress;
}
return TInetAddress();
}
//______________________________________________________________________________
Int_t TServerSocket::GetLocalPort()
{
// Get port # to which server socket is bound. In case of error returns -1.
if (fSocket != -1) {
if (fAddress.GetPort() == -1)
fAddress = GetLocalInetAddress();
return fAddress.GetPort();
}
return -1;
}
//______________________________________________________________________________
UChar_t TServerSocket::GetAcceptOptions()
{
// Return default options for Accept
return fgAcceptOpt;
}
//______________________________________________________________________________
void TServerSocket::SetAcceptOptions(UChar_t mod)
{
// Set default options for Accept according to modifier 'mod'.
// Use:
// kSrvAuth require client authentication
// kSrvNoAuth do not require client authentication
setaccopt(fgAcceptOpt,mod);
}
//______________________________________________________________________________
void TServerSocket::ShowAcceptOptions()
{
// Print default options for Accept
::Info("ShowAcceptOptions"," Auth: %d",(Bool_t)(fgAcceptOpt & kSrvAuth));
}
//______________________________________________________________________________
Bool_t TServerSocket::Authenticate(TSocket *sock)
{
// Check authentication request from the client on new
// open connection
if (!fgSrvAuthHook) {
R__LOCKGUARD2(gSrvAuthenticateMutex);
// Load libraries needed for (server) authentication ...
TString srvlib = "libSrvAuth";
char *p = 0;
// The generic one
if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) {
delete[] p;
if (gSystem->Load(srvlib) == -1) {
Error("Authenticate", "can't load %s",srvlib.Data());
return kFALSE;
}
} else {
Error("Authenticate", "can't locate %s",srvlib.Data());
return kFALSE;
}
//
// Locate SrvAuthenticate
Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate");
if (f)
fgSrvAuthHook = (SrvAuth_t)(f);
else {
Error("Authenticate", "can't find SrvAuthenticate");
return kFALSE;
}
//
// Locate SrvAuthCleanup
f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup");
if (f)
fgSrvAuthClupHook = (SrvClup_t)(f);
else {
Warning("Authenticate", "can't find SrvAuthCleanup");
}
}
TString confdir;
#ifndef ROOTPREFIX
// try to guess the config directory...
if (gSystem->Getenv("ROOTSYS")) {
confdir = TString(gSystem->Getenv("ROOTSYS"));
} else {
// Try to guess it from 'root.exe' path
confdir = TString(gSystem->Which(gSystem->Getenv("PATH"),
"root.exe", kExecutePermission));
confdir.Resize(confdir.Last('/'));
}
#else
confdir = TString(ROOTPREFIX);
#endif
if (!confdir.Length()) {
Error("Authenticate", "config dir undefined");
return kFALSE;
}
// dir for temporary files
TString tmpdir = TString(gSystem->TempDirectory());
if (gSystem->AccessPathName(tmpdir, kWritePermission))
tmpdir = TString("/tmp");
// Get Host name
TString openhost(sock->GetInetAddress().GetHostName());
if (gDebug > 2)
Info("Authenticate","OpenHost = %s", openhost.Data());
// Run Authentication now
std::string user;
Int_t meth = -1;
Int_t auth = 0;
Int_t type = 0;
std::string ctkn = "";
if (fgSrvAuthHook)
auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user,
meth, type, ctkn, fSecContexts);
if (gDebug > 2)
Info("Authenticate","auth = %d, type= %d, ctkn= %s",
auth, type, ctkn.c_str());
return auth;
}
<commit_msg>From Gerri: fix for a tiny mem leak in cleaning up security contexts.<commit_after>// @(#)root/net:$Id$
// Author: Fons Rademakers 18/12/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TServerSocket //
// //
// This class implements server sockets. A server socket waits for //
// requests to come in over the network. It performs some operation //
// based on that request and then possibly returns a full duplex socket //
// to the requester. The actual work is done via the TSystem class //
// (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TServerSocket.h"
#include "TSocket.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TError.h"
#include <string>
#include "TVirtualMutex.h"
// Hook to server authentication wrapper
SrvAuth_t TServerSocket::fgSrvAuthHook = 0;
SrvClup_t TServerSocket::fgSrvAuthClupHook = 0;
// Defaul options for accept
UChar_t TServerSocket::fgAcceptOpt = kSrvNoAuth;
TVirtualMutex *gSrvAuthenticateMutex = 0;
ClassImp(TServerSocket)
//______________________________________________________________________________
static void setaccopt(UChar_t &Opt, UChar_t Mod)
{
// Kind of macro to parse input options
// Modify Opt according to modifier Mod
R__LOCKGUARD2(gSrvAuthenticateMutex);
if (!Mod) return;
if ((Mod & kSrvAuth)) Opt |= kSrvAuth;
if ((Mod & kSrvNoAuth)) Opt &= ~kSrvAuth;
}
//______________________________________________________________________________
TServerSocket::TServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize)
{
// Create a server socket object for a named service. Set reuse to true
// to force reuse of the server socket (i.e. do not wait for the time
// out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
R__ASSERT(gROOT);
R__ASSERT(gSystem);
SetName("ServerSocket");
fSecContext = 0;
fSecContexts = new TList;
// If this is a local path, try announcing a UNIX socket service
ResetBit(TSocket::kIsUnix);
if (service && (!gSystem->AccessPathName(service) ||
#ifndef WIN32
service[0] == '/')) {
#else
service[0] == '/' || (service[1] == ':' && service[2] == '/'))) {
#endif
SetBit(TSocket::kIsUnix);
fService = "unix:";
fService += service;
fSocket = gSystem->AnnounceUnixService(service, backlog);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
} else {
// TCP / UDP socket
fService = service;
int port = gSystem->GetServiceByName(service);
if (port != -1) {
fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
} else {
fSocket = -1;
}
}
}
//______________________________________________________________________________
TServerSocket::TServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize)
{
// Create a server socket object on a specified port. Set reuse to true
// to force reuse of the server socket (i.e. do not wait for the time
// out to pass). Using backlog one can set the desirable queue length
// for pending connections. If port is 0 a port scan will be done to
// find a free port. This option is mutual exlusive with the reuse option.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
R__ASSERT(gROOT);
R__ASSERT(gSystem);
SetName("ServerSocket");
fSecContext = 0;
fSecContexts = new TList;
fService = gSystem->GetServiceByPort(port);
SetTitle(fService);
fSocket = gSystem->AnnounceTcpService(port, reuse, backlog, tcpwindowsize);
if (fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(this);
}
}
//______________________________________________________________________________
TServerSocket::~TServerSocket()
{
// Destructor: cleanup authentication stuff (if any) and close
R__LOCKGUARD2(gSrvAuthenticateMutex);
if (fSecContexts) {
if (fgSrvAuthClupHook) {
// Cleanup the security contexts
(*fgSrvAuthClupHook)(fSecContexts);
}
// Remove the list
fSecContexts->Delete();
SafeDelete(fSecContexts);
fSecContexts = 0;
}
Close();
}
//______________________________________________________________________________
TSocket *TServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a server socket. Returns a full-duplex
// communication TSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
//
// Opt can be used to require client authentication; valid options are
//
// kSrvAuth = require client authentication
// kSrvNoAuth = force no client authentication
//
// Example: use Opt = kSrvAuth to require client authentication.
//
// Default options are taken from fgAcceptOpt and are initially
// equivalent to kSrvNoAuth; they can be changed with the static
// method TServerSocket::SetAcceptOptions(Opt).
// The active defaults can be visualized using the static method
// TServerSocket::ShowAcceptOptions().
//
if (fSocket == -1) { return 0; }
TSocket *socket = new TSocket;
Int_t soc = gSystem->AcceptConnection(fSocket);
if (soc == -1) { delete socket; return 0; }
if (soc == -2) { delete socket; return (TSocket*) -1; }
// Parse Opt
UChar_t acceptOpt = fgAcceptOpt;
setaccopt(acceptOpt,Opt);
Bool_t auth = (Bool_t)(acceptOpt & kSrvAuth);
socket->fSocket = soc;
socket->fSecContext = 0;
socket->fService = fService;
if (!TestBit(TSocket::kIsUnix))
socket->fAddress = gSystem->GetPeerName(socket->fSocket);
if (socket->fSocket >= 0) {
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Add(socket);
}
// Perform authentication, if required
if (auth) {
if (!Authenticate(socket)) {
delete socket;
socket = 0;
}
}
return socket;
}
//______________________________________________________________________________
TInetAddress TServerSocket::GetLocalInetAddress()
{
// Return internet address of host to which the server socket is bound,
// i.e. the local host. In case of error TInetAddress::IsValid() returns
// kFALSE.
if (fSocket != -1) {
if (fAddress.GetPort() == -1)
fAddress = gSystem->GetSockName(fSocket);
return fAddress;
}
return TInetAddress();
}
//______________________________________________________________________________
Int_t TServerSocket::GetLocalPort()
{
// Get port # to which server socket is bound. In case of error returns -1.
if (fSocket != -1) {
if (fAddress.GetPort() == -1)
fAddress = GetLocalInetAddress();
return fAddress.GetPort();
}
return -1;
}
//______________________________________________________________________________
UChar_t TServerSocket::GetAcceptOptions()
{
// Return default options for Accept
return fgAcceptOpt;
}
//______________________________________________________________________________
void TServerSocket::SetAcceptOptions(UChar_t mod)
{
// Set default options for Accept according to modifier 'mod'.
// Use:
// kSrvAuth require client authentication
// kSrvNoAuth do not require client authentication
setaccopt(fgAcceptOpt,mod);
}
//______________________________________________________________________________
void TServerSocket::ShowAcceptOptions()
{
// Print default options for Accept
::Info("ShowAcceptOptions"," Auth: %d",(Bool_t)(fgAcceptOpt & kSrvAuth));
}
//______________________________________________________________________________
Bool_t TServerSocket::Authenticate(TSocket *sock)
{
// Check authentication request from the client on new
// open connection
if (!fgSrvAuthHook) {
R__LOCKGUARD2(gSrvAuthenticateMutex);
// Load libraries needed for (server) authentication ...
TString srvlib = "libSrvAuth";
char *p = 0;
// The generic one
if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) {
delete[] p;
if (gSystem->Load(srvlib) == -1) {
Error("Authenticate", "can't load %s",srvlib.Data());
return kFALSE;
}
} else {
Error("Authenticate", "can't locate %s",srvlib.Data());
return kFALSE;
}
//
// Locate SrvAuthenticate
Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate");
if (f)
fgSrvAuthHook = (SrvAuth_t)(f);
else {
Error("Authenticate", "can't find SrvAuthenticate");
return kFALSE;
}
//
// Locate SrvAuthCleanup
f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup");
if (f)
fgSrvAuthClupHook = (SrvClup_t)(f);
else {
Warning("Authenticate", "can't find SrvAuthCleanup");
}
}
TString confdir;
#ifndef ROOTPREFIX
// try to guess the config directory...
if (gSystem->Getenv("ROOTSYS")) {
confdir = TString(gSystem->Getenv("ROOTSYS"));
} else {
// Try to guess it from 'root.exe' path
confdir = TString(gSystem->Which(gSystem->Getenv("PATH"),
"root.exe", kExecutePermission));
confdir.Resize(confdir.Last('/'));
}
#else
confdir = TString(ROOTPREFIX);
#endif
if (!confdir.Length()) {
Error("Authenticate", "config dir undefined");
return kFALSE;
}
// dir for temporary files
TString tmpdir = TString(gSystem->TempDirectory());
if (gSystem->AccessPathName(tmpdir, kWritePermission))
tmpdir = TString("/tmp");
// Get Host name
TString openhost(sock->GetInetAddress().GetHostName());
if (gDebug > 2)
Info("Authenticate","OpenHost = %s", openhost.Data());
// Run Authentication now
std::string user;
Int_t meth = -1;
Int_t auth = 0;
Int_t type = 0;
std::string ctkn = "";
if (fgSrvAuthHook)
auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user,
meth, type, ctkn, fSecContexts);
if (gDebug > 2)
Info("Authenticate","auth = %d, type= %d, ctkn= %s",
auth, type, ctkn.c_str());
return auth;
}
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "ngraph/op/fused/fake_quantize.hpp"
#include "pyngraph/ops/fused/fake_quantize.hpp"
namespace py = pybind11;
void regclass_pyngraph_op_FakeQuantize(py::module m)
{
py::class_<ngraph::op::FakeQuantize, std::shared_ptr<ngraph::op::FakeQuantize>, ngraph::op::Op>
fakequantize(m, "FakeQuantize");
fakequantize.doc() = "ngraph.impl.op.FakeQuantize wraps ngraph::op::FakeQuantize";
fakequantize.def(py::init<const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
int&>());
}
<commit_msg>[Py] Bugfix. (#3580)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "ngraph/op/fused/fake_quantize.hpp"
#include "pyngraph/ops/fused/fake_quantize.hpp"
namespace py = pybind11;
void regclass_pyngraph_op_FakeQuantize(py::module m)
{
py::class_<ngraph::op::FakeQuantize, std::shared_ptr<ngraph::op::FakeQuantize>, ngraph::op::Op>
fakequantize(m, "FakeQuantize");
fakequantize.doc() = "ngraph.impl.op.FakeQuantize wraps ngraph::op::FakeQuantize";
fakequantize.def(py::init<const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
const std::shared_ptr<ngraph::Node>&,
std::size_t>());
}
<|endoftext|> |
<commit_before>//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass hoists instructions to enable speculative execution on
// targets where branches are expensive. This is aimed at GPUs. It
// currently works on simple if-then and if-then-else
// patterns.
//
// Removing branches is not the only motivation for this
// pass. E.g. consider this code and assume that there is no
// addressing mode for multiplying by sizeof(*a):
//
// if (b > 0)
// c = a[i + 1]
// if (d > 0)
// e = a[i + 2]
//
// turns into
//
// p = &a[i + 1];
// if (b > 0)
// c = *p;
// q = &a[i + 2];
// if (d > 0)
// e = *q;
//
// which could later be optimized to
//
// r = &a[i];
// if (b > 0)
// c = r[1];
// if (d > 0)
// e = r[2];
//
// Later passes sink back much of the speculated code that did not enable
// further optimization.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "speculative-execution"
// The risk that speculation will not pay off increases with the
// number of instructions speculated, so we put a limit on that.
static cl::opt<unsigned> SpecExecMaxSpeculationCost(
"spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where "
"the cost of the instructions to speculatively execute "
"exceeds this limit."));
// Speculating just a few instructions from a larger block tends not
// to be profitable and this limit prevents that. A reason for that is
// that small basic blocks are more likely to be candidates for
// further optimization.
static cl::opt<unsigned> SpecExecMaxNotHoisted(
"spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where the "
"number of instructions that would not be speculatively executed "
"exceeds this limit."));
class SpeculativeExecution : public FunctionPass {
public:
static char ID;
SpeculativeExecution(): FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
private:
bool runOnBasicBlock(BasicBlock &B);
bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
const TargetTransformInfo *TTI = nullptr;
};
char SpeculativeExecution::ID = 0;
INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetTransformInfoWrapperPass>();
}
bool SpeculativeExecution::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
bool Changed = false;
for (auto& B : F) {
Changed |= runOnBasicBlock(B);
}
return Changed;
}
bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
if (BI == nullptr)
return false;
if (BI->getNumSuccessors() != 2)
return false;
BasicBlock &Succ0 = *BI->getSuccessor(0);
BasicBlock &Succ1 = *BI->getSuccessor(1);
if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
return false;
}
// Hoist from if-then (triangle).
if (Succ0.getSinglePredecessor() != nullptr &&
Succ0.getSingleSuccessor() == &Succ1) {
return considerHoistingFromTo(Succ0, B);
}
// Hoist from if-else (triangle).
if (Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() == &Succ0) {
return considerHoistingFromTo(Succ1, B);
}
// Hoist from if-then-else (diamond), but only if it is equivalent to
// an if-else or if-then due to one of the branches doing nothing.
if (Succ0.getSinglePredecessor() != nullptr &&
Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() != nullptr &&
Succ1.getSingleSuccessor() != &B &&
Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
// If a block has only one instruction, then that is a terminator
// instruction so that the block does nothing. This does happen.
if (Succ1.size() == 1) // equivalent to if-then
return considerHoistingFromTo(Succ0, B);
if (Succ0.size() == 1) // equivalent to if-else
return considerHoistingFromTo(Succ1, B);
}
return false;
}
static unsigned ComputeSpeculationCost(const Instruction *I,
const TargetTransformInfo &TTI) {
switch (Operator::getOpcode(I)) {
case Instruction::GetElementPtr:
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Select:
case Instruction::Shl:
case Instruction::Sub:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Xor:
case Instruction::ZExt:
case Instruction::SExt:
return TTI.getUserCost(I);
default:
return UINT_MAX; // Disallow anything not whitelisted.
}
}
bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
BasicBlock &ToBlock) {
SmallSet<const Instruction *, 8> NotHoisted;
const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
for (Value* V : U->operand_values()) {
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (NotHoisted.count(I) > 0)
return false;
}
}
return true;
};
unsigned TotalSpeculationCost = 0;
for (auto& I : FromBlock) {
const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
AllPrecedingUsesFromBlockHoisted(&I)) {
TotalSpeculationCost += Cost;
if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
return false; // too much to hoist
} else {
NotHoisted.insert(&I);
if (NotHoisted.size() > SpecExecMaxNotHoisted)
return false; // too much left behind
}
}
if (TotalSpeculationCost == 0)
return false; // nothing to hoist
for (auto I = FromBlock.begin(); I != FromBlock.end();) {
// We have to increment I before moving Current as moving Current
// changes the list that I is iterating through.
auto Current = I;
++I;
if (!NotHoisted.count(Current)) {
Current->moveBefore(ToBlock.getTerminator());
}
}
return true;
}
namespace llvm {
FunctionPass *createSpeculativeExecutionPass() {
return new SpeculativeExecution();
}
} // namespace llvm
<commit_msg>Move Pass into anonymous namespace. NFC.<commit_after>//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass hoists instructions to enable speculative execution on
// targets where branches are expensive. This is aimed at GPUs. It
// currently works on simple if-then and if-then-else
// patterns.
//
// Removing branches is not the only motivation for this
// pass. E.g. consider this code and assume that there is no
// addressing mode for multiplying by sizeof(*a):
//
// if (b > 0)
// c = a[i + 1]
// if (d > 0)
// e = a[i + 2]
//
// turns into
//
// p = &a[i + 1];
// if (b > 0)
// c = *p;
// q = &a[i + 2];
// if (d > 0)
// e = *q;
//
// which could later be optimized to
//
// r = &a[i];
// if (b > 0)
// c = r[1];
// if (d > 0)
// e = r[2];
//
// Later passes sink back much of the speculated code that did not enable
// further optimization.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "speculative-execution"
// The risk that speculation will not pay off increases with the
// number of instructions speculated, so we put a limit on that.
static cl::opt<unsigned> SpecExecMaxSpeculationCost(
"spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where "
"the cost of the instructions to speculatively execute "
"exceeds this limit."));
// Speculating just a few instructions from a larger block tends not
// to be profitable and this limit prevents that. A reason for that is
// that small basic blocks are more likely to be candidates for
// further optimization.
static cl::opt<unsigned> SpecExecMaxNotHoisted(
"spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
cl::desc("Speculative execution is not applied to basic blocks where the "
"number of instructions that would not be speculatively executed "
"exceeds this limit."));
namespace {
class SpeculativeExecution : public FunctionPass {
public:
static char ID;
SpeculativeExecution(): FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
private:
bool runOnBasicBlock(BasicBlock &B);
bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
const TargetTransformInfo *TTI = nullptr;
};
} // namespace
char SpeculativeExecution::ID = 0;
INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
"Speculatively execute instructions", false, false)
void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetTransformInfoWrapperPass>();
}
bool SpeculativeExecution::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
bool Changed = false;
for (auto& B : F) {
Changed |= runOnBasicBlock(B);
}
return Changed;
}
bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
if (BI == nullptr)
return false;
if (BI->getNumSuccessors() != 2)
return false;
BasicBlock &Succ0 = *BI->getSuccessor(0);
BasicBlock &Succ1 = *BI->getSuccessor(1);
if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
return false;
}
// Hoist from if-then (triangle).
if (Succ0.getSinglePredecessor() != nullptr &&
Succ0.getSingleSuccessor() == &Succ1) {
return considerHoistingFromTo(Succ0, B);
}
// Hoist from if-else (triangle).
if (Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() == &Succ0) {
return considerHoistingFromTo(Succ1, B);
}
// Hoist from if-then-else (diamond), but only if it is equivalent to
// an if-else or if-then due to one of the branches doing nothing.
if (Succ0.getSinglePredecessor() != nullptr &&
Succ1.getSinglePredecessor() != nullptr &&
Succ1.getSingleSuccessor() != nullptr &&
Succ1.getSingleSuccessor() != &B &&
Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
// If a block has only one instruction, then that is a terminator
// instruction so that the block does nothing. This does happen.
if (Succ1.size() == 1) // equivalent to if-then
return considerHoistingFromTo(Succ0, B);
if (Succ0.size() == 1) // equivalent to if-else
return considerHoistingFromTo(Succ1, B);
}
return false;
}
static unsigned ComputeSpeculationCost(const Instruction *I,
const TargetTransformInfo &TTI) {
switch (Operator::getOpcode(I)) {
case Instruction::GetElementPtr:
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Select:
case Instruction::Shl:
case Instruction::Sub:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::Xor:
case Instruction::ZExt:
case Instruction::SExt:
return TTI.getUserCost(I);
default:
return UINT_MAX; // Disallow anything not whitelisted.
}
}
bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
BasicBlock &ToBlock) {
SmallSet<const Instruction *, 8> NotHoisted;
const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
for (Value* V : U->operand_values()) {
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (NotHoisted.count(I) > 0)
return false;
}
}
return true;
};
unsigned TotalSpeculationCost = 0;
for (auto& I : FromBlock) {
const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
AllPrecedingUsesFromBlockHoisted(&I)) {
TotalSpeculationCost += Cost;
if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
return false; // too much to hoist
} else {
NotHoisted.insert(&I);
if (NotHoisted.size() > SpecExecMaxNotHoisted)
return false; // too much left behind
}
}
if (TotalSpeculationCost == 0)
return false; // nothing to hoist
for (auto I = FromBlock.begin(); I != FromBlock.end();) {
// We have to increment I before moving Current as moving Current
// changes the list that I is iterating through.
auto Current = I;
++I;
if (!NotHoisted.count(Current)) {
Current->moveBefore(ToBlock.getTerminator());
}
}
return true;
}
namespace llvm {
FunctionPass *createSpeculativeExecutionPass() {
return new SpeculativeExecution();
}
} // namespace llvm
<|endoftext|> |
<commit_before>/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkData.h"
#include "include/core/SkFont.h"
#include "include/core/SkPaint.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkSurface.h"
#include "include/effects/SkGradientShader.h"
#include "include/effects/SkImageFilters.h"
#include "include/effects/SkRuntimeEffect.h"
#include "include/private/SkSLDefines.h" // for kDefaultInlineThreshold
#include "include/utils/SkRandom.h"
#include "tests/Test.h"
#include "tools/Resources.h"
#include "tools/ToolUtils.h"
static const SkRect kRect = SkRect::MakeWH(1, 1);
template <typename T>
static void set_uniform(SkRuntimeShaderBuilder* builder, const char* name, const T& value) {
SkRuntimeShaderBuilder::BuilderUniform uniform = builder->uniform(name);
if (uniform.fVar) {
uniform = value;
}
}
static void test_one_permutation(skiatest::Reporter* r,
SkSurface* surface,
const char* testFile,
const char* permutationSuffix,
const SkRuntimeEffect::Options& options) {
SkString resourcePath = SkStringPrintf("sksl/%s", testFile);
sk_sp<SkData> shaderData = GetResourceAsData(resourcePath.c_str());
if (!shaderData) {
ERRORF(r, "%s%s: Unable to load file", testFile, permutationSuffix);
return;
}
SkString shaderString{reinterpret_cast<const char*>(shaderData->bytes()), shaderData->size()};
SkRuntimeEffect::Result result = SkRuntimeEffect::Make(shaderString, options);
if (!result.effect) {
ERRORF(r, "%s%s: %s", testFile, permutationSuffix, result.errorText.c_str());
return;
}
SkRuntimeShaderBuilder builder(result.effect);
set_uniform(&builder, "colorBlack", SkV4{0, 0, 0, 1});
set_uniform(&builder, "colorRed", SkV4{1, 0, 0, 1});
set_uniform(&builder, "colorGreen", SkV4{0, 1, 0, 1});
set_uniform(&builder, "colorBlue", SkV4{0, 0, 1, 1});
set_uniform(&builder, "colorWhite", SkV4{1, 1, 1, 1});
set_uniform(&builder, "testInputs", SkV4{-1.25, 0, 0.75, 2.25});
set_uniform(&builder, "testMatrix2x2", std::array<float,4>{1, 2,
3, 4});
set_uniform(&builder, "testMatrix3x3", std::array<float,9>{1, 2, 3,
4, 5, 6,
7, 8, 9});
set_uniform(&builder, "unknownInput", 1.0f);
set_uniform(&builder, "testMatrix2x2", std::array<float,4>{1, 2,
3, 4});
set_uniform(&builder, "testMatrix3x3", std::array<float,9>{1, 2, 3,
4, 5, 6,
7, 8, 9});
sk_sp<SkShader> shader = builder.makeShader(/*localMatrix=*/nullptr, /*isOpaque=*/true);
if (!shader) {
ERRORF(r, "%s%s: Unable to build shader", testFile, permutationSuffix);
return;
}
SkPaint paintShader;
paintShader.setShader(shader);
surface->getCanvas()->drawRect(kRect, paintShader);
SkBitmap bitmap;
REPORTER_ASSERT(r, bitmap.tryAllocPixels(surface->imageInfo()));
REPORTER_ASSERT(r, surface->readPixels(bitmap.info(), bitmap.getPixels(), bitmap.rowBytes(),
/*srcX=*/0, /*srcY=*/0));
SkColor color = bitmap.getColor(0, 0);
REPORTER_ASSERT(r, color == SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00),
"Expected: solid green. Actual: A=%02X R=%02X G=%02X B=%02X.",
SkColorGetA(color), SkColorGetR(color), SkColorGetG(color), SkColorGetB(color));
}
static void test_permutations(skiatest::Reporter* r, SkSurface* surface, const char* testFile) {
SkRuntimeEffect::Options options;
options.inlineThreshold = 0;
test_one_permutation(r, surface, testFile, " (NoInline)", options);
options.inlineThreshold = SkSL::kDefaultInlineThreshold;
test_one_permutation(r, surface, testFile, "", options);
}
static void test_cpu(skiatest::Reporter* r, const char* testFile) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(kRect.width(), kRect.height());
sk_sp<SkSurface> surface(SkSurface::MakeRaster(info));
test_permutations(r, surface.get(), testFile);
}
static void test_gpu(skiatest::Reporter* r, GrDirectContext* ctx, const char* testFile) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(kRect.width(), kRect.height());
sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info));
test_permutations(r, surface.get(), testFile);
}
#define SKSL_TEST_CPU(name, path) \
DEF_TEST(name ## _CPU, r) { \
test_cpu(r, path); \
}
#define SKSL_TEST_GPU(name, path) \
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(name ## _GPU, r, ctxInfo) { \
test_gpu(r, ctxInfo.directContext(), path); \
}
#define SKSL_TEST(name, path) SKSL_TEST_CPU(name, path) SKSL_TEST_GPU(name, path)
SKSL_TEST(SkSLAssignmentOps, "folding/AssignmentOps.sksl")
SKSL_TEST(SkSLBoolFolding, "folding/BoolFolding.sksl")
SKSL_TEST(SkSLIntFoldingES2, "folding/IntFoldingES2.sksl")
SKSL_TEST(SkSLFloatFolding, "folding/FloatFolding.sksl")
SKSL_TEST(SkSLMatrixFoldingES2, "folding/MatrixFoldingES2.sksl")
SKSL_TEST(SkSLSelfAssignment, "folding/SelfAssignment.sksl")
SKSL_TEST(SkSLShortCircuitBoolFolding, "folding/ShortCircuitBoolFolding.sksl")
SKSL_TEST(SkSLVectorScalarFolding, "folding/VectorScalarFolding.sksl")
SKSL_TEST(SkSLVectorVectorFolding, "folding/VectorVectorFolding.sksl")
SKSL_TEST(SkSLIntrinsicAbsFloat, "intrinsics/AbsFloat.sksl")
SKSL_TEST(SkSLIntrinsicCeil, "intrinsics/Ceil.sksl")
SKSL_TEST(SkSLIntrinsicClampFloat, "intrinsics/ClampFloat.sksl")
SKSL_TEST(SkSLIntrinsicMaxFloat, "intrinsics/MaxFloat.sksl")
SKSL_TEST(SkSLIntrinsicMinFloat, "intrinsics/MinFloat.sksl")
SKSL_TEST(SkSLIntrinsicMixFloat, "intrinsics/MixFloat.sksl")
SKSL_TEST(SkSLIntrinsicSignFloat, "intrinsics/SignFloat.sksl")
SKSL_TEST(SkSLArrayTypes, "shared/ArrayTypes.sksl")
SKSL_TEST(SkSLAssignment, "shared/Assignment.sksl")
SKSL_TEST(SkSLCastsRoundTowardZero, "shared/CastsRoundTowardZero.sksl")
SKSL_TEST(SkSLCommaMixedTypes, "shared/CommaMixedTypes.sksl")
SKSL_TEST(SkSLCommaSideEffects, "shared/CommaSideEffects.sksl")
SKSL_TEST(SkSLConstantIf, "shared/ConstantIf.sksl")
SKSL_TEST(SkSLConstVariableComparison, "shared/ConstVariableComparison.sksl")
SKSL_TEST(SkSLDeadIfStatement, "shared/DeadIfStatement.sksl")
SKSL_TEST(SkSLDeadStripFunctions, "shared/DeadStripFunctions.sksl")
SKSL_TEST(SkSLDependentInitializers, "shared/DependentInitializers.sksl")
SKSL_TEST(SkSLEmptyBlocksES2, "shared/EmptyBlocksES2.sksl")
SKSL_TEST(SkSLForLoopControlFlow, "shared/ForLoopControlFlow.sksl")
SKSL_TEST(SkSLFunctionArgTypeMatch, "shared/FunctionArgTypeMatch.sksl")
SKSL_TEST(SkSLFunctionReturnTypeMatch, "shared/FunctionReturnTypeMatch.sksl")
SKSL_TEST(SkSLFunctions, "shared/Functions.sksl")
SKSL_TEST(SkSLGeometricIntrinsics, "shared/GeometricIntrinsics.sksl")
SKSL_TEST(SkSLHelloWorld, "shared/HelloWorld.sksl")
SKSL_TEST(SkSLHex, "shared/Hex.sksl")
SKSL_TEST(SkSLMatrices, "shared/Matrices.sksl")
SKSL_TEST(SkSLMatrixEquality, "shared/MatrixEquality.sksl")
SKSL_TEST(SkSLMultipleAssignments, "shared/MultipleAssignments.sksl")
SKSL_TEST(SkSLNegatedVectorLiteral, "shared/NegatedVectorLiteral.sksl")
SKSL_TEST(SkSLNumberCasts, "shared/NumberCasts.sksl")
SKSL_TEST(SkSLOperatorsES2, "shared/OperatorsES2.sksl")
SKSL_TEST(SkSLOutParams, "shared/OutParams.sksl")
SKSL_TEST(SkSLOutParamsTricky, "shared/OutParamsTricky.sksl")
SKSL_TEST(SkSLResizeMatrix, "shared/ResizeMatrix.sksl")
SKSL_TEST(SkSLReturnsValueOnEveryPathES2, "shared/ReturnsValueOnEveryPathES2.sksl")
SKSL_TEST(SkSLScalarConversionConstructorsES2, "shared/ScalarConversionConstructorsES2.sksl")
SKSL_TEST(SkSLStackingVectorCasts, "shared/StackingVectorCasts.sksl")
SKSL_TEST(SkSLStaticIf, "shared/StaticIf.sksl")
SKSL_TEST(SkSLStructsInFunctions, "shared/StructsInFunctions.sksl")
SKSL_TEST(SkSLSwizzleBoolConstants, "shared/SwizzleBoolConstants.sksl")
SKSL_TEST(SkSLSwizzleByConstantIndex, "shared/SwizzleByConstantIndex.sksl")
SKSL_TEST(SkSLSwizzleConstants, "shared/SwizzleConstants.sksl")
SKSL_TEST(SkSLSwizzleLTRB, "shared/SwizzleLTRB.sksl")
SKSL_TEST(SkSLSwizzleOpt, "shared/SwizzleOpt.sksl")
SKSL_TEST(SkSLSwizzleScalar, "shared/SwizzleScalar.sksl")
SKSL_TEST(SkSLTernaryAsLValueEntirelyFoldable, "shared/TernaryAsLValueEntirelyFoldable.sksl")
SKSL_TEST(SkSLTernaryAsLValueFoldableTest, "shared/TernaryAsLValueFoldableTest.sksl")
SKSL_TEST(SkSLTernaryExpression, "shared/TernaryExpression.sksl")
SKSL_TEST(SkSLUnaryPositiveNegative, "shared/UnaryPositiveNegative.sksl")
SKSL_TEST(SkSLUnusedVariables, "shared/UnusedVariables.sksl")
SKSL_TEST(SkSLVectorConstructors, "shared/VectorConstructors.sksl")
/*
// Incompatible with Runtime Effects because calling a function before its definition is disallowed.
// (This was done to prevent recursion, as required by ES2.)
SKSL_TEST(SkSLFunctionPrototype, "shared/FunctionPrototype.sksl")
*/
/*
TODO(skia:11209): enable these tests when Runtime Effects have support for ES3
SKSL_TEST(SkSLIntFoldingES3, "folding/IntFoldingES3.sksl")
SKSL_TEST(SkSLMatrixFoldingES3, "folding/MatrixFoldingES3.sksl")
SKSL_TEST(SkSLIntrinsicAbsInt, "intrinsics/AbsInt.sksl")
SKSL_TEST(SkSLIntrinsicClampInt, "intrinsics/ClampInt.sksl")
SKSL_TEST(SkSLIntrinsicMaxInt, "intrinsics/MaxInt.sksl")
SKSL_TEST(SkSLIntrinsicMinInt, "intrinsics/MinInt.sksl")
SKSL_TEST(SkSLIntrinsicMixBool, "intrinsics/MixBool.sksl")
SKSL_TEST(SkSLIntrinsicSignInt, "intrinsics/SignInt.sksl")
SKSL_TEST(SkSLArrayConstructors, "shared/ArrayConstructors.sksl")
SKSL_TEST(SkSLDeadLoopVariable, "shared/DeadLoopVariable.sksl")
SKSL_TEST(SkSLDoWhileControlFlow, "shared/DoWhileControlFlow.sksl")
SKSL_TEST(SkSLEmptyBlocksES3, "shared/EmptyBlocksES3.sksl")
SKSL_TEST(SkSLHexUnsigned, "shared/HexUnsigned.sksl")
SKSL_TEST(SkSLMatricesNonsquare, "shared/MatricesNonsquare.sksl")
SKSL_TEST(SkSLOperatorsES3, "shared/OperatorsES3.sksl")
SKSL_TEST(SkSLResizeMatrixNonsquare, "shared/ResizeMatrixNonsquare.sksl")
SKSL_TEST(SkSLReturnsValueOnEveryPathES3, "shared/ReturnsValueOnEveryPathES3.sksl")
SKSL_TEST(SkSLScalarConversionConstructorsES3, "shared/ScalarConversionConstructorsES3.sksl")
SKSL_TEST(SkSLSwizzleByIndex, "shared/SwizzleByIndex.sksl")
SKSL_TEST(SkSLWhileLoopControlFlow, "shared/WhileLoopControlFlow.sksl")
*/
<commit_msg>Disable OutParams test on GPU.<commit_after>/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkData.h"
#include "include/core/SkFont.h"
#include "include/core/SkPaint.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkSurface.h"
#include "include/effects/SkGradientShader.h"
#include "include/effects/SkImageFilters.h"
#include "include/effects/SkRuntimeEffect.h"
#include "include/private/SkSLDefines.h" // for kDefaultInlineThreshold
#include "include/utils/SkRandom.h"
#include "tests/Test.h"
#include "tools/Resources.h"
#include "tools/ToolUtils.h"
static const SkRect kRect = SkRect::MakeWH(1, 1);
template <typename T>
static void set_uniform(SkRuntimeShaderBuilder* builder, const char* name, const T& value) {
SkRuntimeShaderBuilder::BuilderUniform uniform = builder->uniform(name);
if (uniform.fVar) {
uniform = value;
}
}
static void test_one_permutation(skiatest::Reporter* r,
SkSurface* surface,
const char* testFile,
const char* permutationSuffix,
const SkRuntimeEffect::Options& options) {
SkString resourcePath = SkStringPrintf("sksl/%s", testFile);
sk_sp<SkData> shaderData = GetResourceAsData(resourcePath.c_str());
if (!shaderData) {
ERRORF(r, "%s%s: Unable to load file", testFile, permutationSuffix);
return;
}
SkString shaderString{reinterpret_cast<const char*>(shaderData->bytes()), shaderData->size()};
SkRuntimeEffect::Result result = SkRuntimeEffect::Make(shaderString, options);
if (!result.effect) {
ERRORF(r, "%s%s: %s", testFile, permutationSuffix, result.errorText.c_str());
return;
}
SkRuntimeShaderBuilder builder(result.effect);
set_uniform(&builder, "colorBlack", SkV4{0, 0, 0, 1});
set_uniform(&builder, "colorRed", SkV4{1, 0, 0, 1});
set_uniform(&builder, "colorGreen", SkV4{0, 1, 0, 1});
set_uniform(&builder, "colorBlue", SkV4{0, 0, 1, 1});
set_uniform(&builder, "colorWhite", SkV4{1, 1, 1, 1});
set_uniform(&builder, "testInputs", SkV4{-1.25, 0, 0.75, 2.25});
set_uniform(&builder, "testMatrix2x2", std::array<float,4>{1, 2,
3, 4});
set_uniform(&builder, "testMatrix3x3", std::array<float,9>{1, 2, 3,
4, 5, 6,
7, 8, 9});
set_uniform(&builder, "unknownInput", 1.0f);
set_uniform(&builder, "testMatrix2x2", std::array<float,4>{1, 2,
3, 4});
set_uniform(&builder, "testMatrix3x3", std::array<float,9>{1, 2, 3,
4, 5, 6,
7, 8, 9});
sk_sp<SkShader> shader = builder.makeShader(/*localMatrix=*/nullptr, /*isOpaque=*/true);
if (!shader) {
ERRORF(r, "%s%s: Unable to build shader", testFile, permutationSuffix);
return;
}
SkPaint paintShader;
paintShader.setShader(shader);
surface->getCanvas()->drawRect(kRect, paintShader);
SkBitmap bitmap;
REPORTER_ASSERT(r, bitmap.tryAllocPixels(surface->imageInfo()));
REPORTER_ASSERT(r, surface->readPixels(bitmap.info(), bitmap.getPixels(), bitmap.rowBytes(),
/*srcX=*/0, /*srcY=*/0));
SkColor color = bitmap.getColor(0, 0);
REPORTER_ASSERT(r, color == SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00),
"Expected: solid green. Actual: A=%02X R=%02X G=%02X B=%02X.",
SkColorGetA(color), SkColorGetR(color), SkColorGetG(color), SkColorGetB(color));
}
static void test_permutations(skiatest::Reporter* r, SkSurface* surface, const char* testFile) {
SkRuntimeEffect::Options options;
options.inlineThreshold = 0;
test_one_permutation(r, surface, testFile, " (NoInline)", options);
options.inlineThreshold = SkSL::kDefaultInlineThreshold;
test_one_permutation(r, surface, testFile, "", options);
}
static void test_cpu(skiatest::Reporter* r, const char* testFile) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(kRect.width(), kRect.height());
sk_sp<SkSurface> surface(SkSurface::MakeRaster(info));
test_permutations(r, surface.get(), testFile);
}
static void test_gpu(skiatest::Reporter* r, GrDirectContext* ctx, const char* testFile) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(kRect.width(), kRect.height());
sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info));
test_permutations(r, surface.get(), testFile);
}
#define SKSL_TEST_CPU(name, path) \
DEF_TEST(name ## _CPU, r) { \
test_cpu(r, path); \
}
#define SKSL_TEST_GPU(name, path) \
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(name ## _GPU, r, ctxInfo) { \
test_gpu(r, ctxInfo.directContext(), path); \
}
#define SKSL_TEST(name, path) SKSL_TEST_CPU(name, path) SKSL_TEST_GPU(name, path)
SKSL_TEST(SkSLAssignmentOps, "folding/AssignmentOps.sksl")
SKSL_TEST(SkSLBoolFolding, "folding/BoolFolding.sksl")
SKSL_TEST(SkSLIntFoldingES2, "folding/IntFoldingES2.sksl")
SKSL_TEST(SkSLFloatFolding, "folding/FloatFolding.sksl")
SKSL_TEST(SkSLMatrixFoldingES2, "folding/MatrixFoldingES2.sksl")
SKSL_TEST(SkSLSelfAssignment, "folding/SelfAssignment.sksl")
SKSL_TEST(SkSLShortCircuitBoolFolding, "folding/ShortCircuitBoolFolding.sksl")
SKSL_TEST(SkSLVectorScalarFolding, "folding/VectorScalarFolding.sksl")
SKSL_TEST(SkSLVectorVectorFolding, "folding/VectorVectorFolding.sksl")
SKSL_TEST(SkSLIntrinsicAbsFloat, "intrinsics/AbsFloat.sksl")
SKSL_TEST(SkSLIntrinsicCeil, "intrinsics/Ceil.sksl")
SKSL_TEST(SkSLIntrinsicClampFloat, "intrinsics/ClampFloat.sksl")
SKSL_TEST(SkSLIntrinsicMaxFloat, "intrinsics/MaxFloat.sksl")
SKSL_TEST(SkSLIntrinsicMinFloat, "intrinsics/MinFloat.sksl")
SKSL_TEST(SkSLIntrinsicMixFloat, "intrinsics/MixFloat.sksl")
SKSL_TEST(SkSLIntrinsicSignFloat, "intrinsics/SignFloat.sksl")
SKSL_TEST(SkSLArrayTypes, "shared/ArrayTypes.sksl")
SKSL_TEST(SkSLAssignment, "shared/Assignment.sksl")
SKSL_TEST(SkSLCastsRoundTowardZero, "shared/CastsRoundTowardZero.sksl")
SKSL_TEST(SkSLCommaMixedTypes, "shared/CommaMixedTypes.sksl")
SKSL_TEST(SkSLCommaSideEffects, "shared/CommaSideEffects.sksl")
SKSL_TEST(SkSLConstantIf, "shared/ConstantIf.sksl")
SKSL_TEST(SkSLConstVariableComparison, "shared/ConstVariableComparison.sksl")
SKSL_TEST(SkSLDeadIfStatement, "shared/DeadIfStatement.sksl")
SKSL_TEST(SkSLDeadStripFunctions, "shared/DeadStripFunctions.sksl")
SKSL_TEST(SkSLDependentInitializers, "shared/DependentInitializers.sksl")
SKSL_TEST(SkSLEmptyBlocksES2, "shared/EmptyBlocksES2.sksl")
SKSL_TEST(SkSLForLoopControlFlow, "shared/ForLoopControlFlow.sksl")
SKSL_TEST(SkSLFunctionArgTypeMatch, "shared/FunctionArgTypeMatch.sksl")
SKSL_TEST(SkSLFunctionReturnTypeMatch, "shared/FunctionReturnTypeMatch.sksl")
SKSL_TEST(SkSLFunctions, "shared/Functions.sksl")
SKSL_TEST(SkSLGeometricIntrinsics, "shared/GeometricIntrinsics.sksl")
SKSL_TEST(SkSLHelloWorld, "shared/HelloWorld.sksl")
SKSL_TEST(SkSLHex, "shared/Hex.sksl")
SKSL_TEST(SkSLMatrices, "shared/Matrices.sksl")
SKSL_TEST(SkSLMatrixEquality, "shared/MatrixEquality.sksl")
SKSL_TEST(SkSLMultipleAssignments, "shared/MultipleAssignments.sksl")
SKSL_TEST(SkSLNegatedVectorLiteral, "shared/NegatedVectorLiteral.sksl")
SKSL_TEST(SkSLNumberCasts, "shared/NumberCasts.sksl")
SKSL_TEST(SkSLOperatorsES2, "shared/OperatorsES2.sksl")
// TODO(skia:11748): The OutParams test generates invalid SPIR-V when inlining is off.
SKSL_TEST_CPU(SkSLOutParams, "shared/OutParams.sksl")
SKSL_TEST(SkSLOutParamsTricky, "shared/OutParamsTricky.sksl")
SKSL_TEST(SkSLResizeMatrix, "shared/ResizeMatrix.sksl")
SKSL_TEST(SkSLReturnsValueOnEveryPathES2, "shared/ReturnsValueOnEveryPathES2.sksl")
SKSL_TEST(SkSLScalarConversionConstructorsES2, "shared/ScalarConversionConstructorsES2.sksl")
SKSL_TEST(SkSLStackingVectorCasts, "shared/StackingVectorCasts.sksl")
SKSL_TEST(SkSLStaticIf, "shared/StaticIf.sksl")
SKSL_TEST(SkSLStructsInFunctions, "shared/StructsInFunctions.sksl")
SKSL_TEST(SkSLSwizzleBoolConstants, "shared/SwizzleBoolConstants.sksl")
SKSL_TEST(SkSLSwizzleByConstantIndex, "shared/SwizzleByConstantIndex.sksl")
SKSL_TEST(SkSLSwizzleConstants, "shared/SwizzleConstants.sksl")
SKSL_TEST(SkSLSwizzleLTRB, "shared/SwizzleLTRB.sksl")
SKSL_TEST(SkSLSwizzleOpt, "shared/SwizzleOpt.sksl")
SKSL_TEST(SkSLSwizzleScalar, "shared/SwizzleScalar.sksl")
SKSL_TEST(SkSLTernaryAsLValueEntirelyFoldable, "shared/TernaryAsLValueEntirelyFoldable.sksl")
SKSL_TEST(SkSLTernaryAsLValueFoldableTest, "shared/TernaryAsLValueFoldableTest.sksl")
SKSL_TEST(SkSLTernaryExpression, "shared/TernaryExpression.sksl")
SKSL_TEST(SkSLUnaryPositiveNegative, "shared/UnaryPositiveNegative.sksl")
SKSL_TEST(SkSLUnusedVariables, "shared/UnusedVariables.sksl")
SKSL_TEST(SkSLVectorConstructors, "shared/VectorConstructors.sksl")
/*
// Incompatible with Runtime Effects because calling a function before its definition is disallowed.
// (This was done to prevent recursion, as required by ES2.)
SKSL_TEST(SkSLFunctionPrototype, "shared/FunctionPrototype.sksl")
*/
/*
TODO(skia:11209): enable these tests when Runtime Effects have support for ES3
SKSL_TEST(SkSLIntFoldingES3, "folding/IntFoldingES3.sksl")
SKSL_TEST(SkSLMatrixFoldingES3, "folding/MatrixFoldingES3.sksl")
SKSL_TEST(SkSLIntrinsicAbsInt, "intrinsics/AbsInt.sksl")
SKSL_TEST(SkSLIntrinsicClampInt, "intrinsics/ClampInt.sksl")
SKSL_TEST(SkSLIntrinsicMaxInt, "intrinsics/MaxInt.sksl")
SKSL_TEST(SkSLIntrinsicMinInt, "intrinsics/MinInt.sksl")
SKSL_TEST(SkSLIntrinsicMixBool, "intrinsics/MixBool.sksl")
SKSL_TEST(SkSLIntrinsicSignInt, "intrinsics/SignInt.sksl")
SKSL_TEST(SkSLArrayConstructors, "shared/ArrayConstructors.sksl")
SKSL_TEST(SkSLDeadLoopVariable, "shared/DeadLoopVariable.sksl")
SKSL_TEST(SkSLDoWhileControlFlow, "shared/DoWhileControlFlow.sksl")
SKSL_TEST(SkSLEmptyBlocksES3, "shared/EmptyBlocksES3.sksl")
SKSL_TEST(SkSLHexUnsigned, "shared/HexUnsigned.sksl")
SKSL_TEST(SkSLMatricesNonsquare, "shared/MatricesNonsquare.sksl")
SKSL_TEST(SkSLOperatorsES3, "shared/OperatorsES3.sksl")
SKSL_TEST(SkSLResizeMatrixNonsquare, "shared/ResizeMatrixNonsquare.sksl")
SKSL_TEST(SkSLReturnsValueOnEveryPathES3, "shared/ReturnsValueOnEveryPathES3.sksl")
SKSL_TEST(SkSLScalarConversionConstructorsES3, "shared/ScalarConversionConstructorsES3.sksl")
SKSL_TEST(SkSLSwizzleByIndex, "shared/SwizzleByIndex.sksl")
SKSL_TEST(SkSLWhileLoopControlFlow, "shared/WhileLoopControlFlow.sksl")
*/
<|endoftext|> |
<commit_before>/// Test the action helpers that fill roofit datasets from RDataFrame.
///
/// \date Mar 2021
/// \author Stephan Hageboeck (CERN)
#include <RooAbsDataHelper.h>
#include <TROOT.h>
#include <TRandom3.h>
#include "gtest/gtest.h"
#include <vector>
TEST(RooAbsDataHelper, MTConstruction)
{
#ifdef R__USE_IMT
ROOT::EnableImplicitMT(4);
#endif
const auto nSlots = ROOT::IsImplicitMTEnabled() ? ROOT::GetThreadPoolSize() : 1;
std::vector<TRandom3> rngs(nSlots);
for (unsigned int i=0; i < rngs.size(); ++i) {
rngs[i].SetSeed(i+1);
}
// We create an RDataFrame with two columns filled with 2 million random numbers.
constexpr std::size_t nEvent = 200000;
ROOT::RDataFrame d(nEvent);
auto dd = d.DefineSlot("x", [&rngs](unsigned int slot){ return rngs[slot].Uniform(-5., 5.); })
.DefineSlot("y", [&rngs](unsigned int slot){ return rngs[slot].Gaus(1., 3.); });
auto meanX = dd.Mean("x");
auto meanY = dd.Mean("y");
// We create RooFit variables that will represent the dataset.
RooRealVar x("x", "x", -5., 5.);
RooRealVar y("y", "y", -50., 50.);
x.setBins(10);
y.setBins(20);
auto rooDataSet = dd.Book<double, double>(
RooDataSetHelper("dataset", // Name
"Title of dataset", // Title
RooArgSet(x, y) // Variables in this dataset
),
{"x", "y"} // Column names in RDataFrame.
);
RooDataHistHelper rdhMaker{"datahist", // Name
"Title of data hist", // Title
RooArgSet(x, y) // Variables in this dataset
};
// Then, we move it into the RDataFrame action:
auto rooDataHist = dd.Book<double, double>(std::move(rdhMaker), {"x", "y"});
// Run it and inspect the results
// -------------------------------
EXPECT_NEAR(meanX.GetValue(), 0., 1.E-2); // Pretty bad accuracy, but might be the RNG or summation in RDF
EXPECT_NEAR(meanY.GetValue(), 1., 1.E-2);
constexpr double goodPrecision = 1.E-9;
constexpr double middlePrecision = 3.E-3;
constexpr double badPrecision = 2.E-2;
ASSERT_EQ(rooDataSet->numEntries(), nEvent);
EXPECT_NEAR(rooDataSet->sumEntries(), nEvent, nEvent * goodPrecision);
EXPECT_NEAR(rooDataSet->mean(x), meanX.GetValue(), goodPrecision);
EXPECT_NEAR(rooDataSet->moment(x, 2.), 100./12., 100./12. * middlePrecision);
EXPECT_NEAR(rooDataSet->mean(y), meanY.GetValue(), goodPrecision);
EXPECT_NEAR(rooDataSet->moment(y, 2.), 3.*3., 3.*3. * badPrecision);
EXPECT_NEAR(rooDataHist->sumEntries(), nEvent, nEvent * goodPrecision);
EXPECT_NEAR(rooDataHist->mean(x), meanX.GetValue(), badPrecision);
EXPECT_NEAR(rooDataHist->moment(x, 2.), 100./12., 100./12. * badPrecision);
EXPECT_NEAR(rooDataHist->mean(y), meanY.GetValue(), badPrecision);
EXPECT_NEAR(std::sqrt(rooDataHist->moment(y, 2.)), 3., 0.4); // Sigma is hard to measure in a binned distribution
}
<commit_msg>[RF] Prevent intermittent failures in testActionHelpers.<commit_after>/// Test the action helpers that fill roofit datasets from RDataFrame.
///
/// \date Mar 2021
/// \author Stephan Hageboeck (CERN)
#include <RooAbsDataHelper.h>
#include <TROOT.h>
#include <Rtypes.h>
#include "gtest/gtest.h"
TEST(RooAbsDataHelper, MTConstruction)
{
#ifdef R__USE_IMT
ROOT::EnableImplicitMT(4);
#endif
// We create an RDataFrame with two columns filled with 2 million random numbers.
constexpr std::size_t nEvent = 200000;
ROOT::RDataFrame d(nEvent);
auto dd = d.DefineSlot("x", [](unsigned int /*slot*/, ULong64_t entry){ return -5. + 10. * ((double)entry) / nEvent; }, {"rdfentry_"})
.DefineSlot("y", [](unsigned int /*slot*/, ULong64_t entry){ return 0. + 2. * ((double)entry) / nEvent; }, {"rdfentry_"});
auto meanX = dd.Mean("x");
auto meanY = dd.Mean("y");
constexpr double targetXMean = 0.;
constexpr double targetYMean = 1.;
constexpr double targetXVar = 100./12.;
constexpr double targetYVar = 4./12.;
// We create RooFit variables that will represent the dataset.
RooRealVar x("x", "x", -5., 5.);
RooRealVar y("y", "y", -50., 50.);
x.setBins(10);
y.setBins(100);
auto rooDataSet = dd.Book<double, double>(
RooDataSetHelper("dataset", // Name
"Title of dataset", // Title
RooArgSet(x, y) // Variables in this dataset
),
{"x", "y"} // Column names in RDataFrame.
);
RooDataHistHelper rdhMaker{"datahist", // Name
"Title of data hist", // Title
RooArgSet(x, y) // Variables in this dataset
};
// Then, we move it into the RDataFrame action:
auto rooDataHist = dd.Book<double, double>(std::move(rdhMaker), {"x", "y"});
// Run it and inspect the results
// -------------------------------
EXPECT_NEAR(meanX.GetValue(), targetXMean, 1.E-4);
EXPECT_NEAR(meanY.GetValue(), targetYMean, 1.E-4);
ASSERT_EQ(rooDataSet->numEntries(), nEvent);
EXPECT_NEAR(rooDataSet->sumEntries(), nEvent, nEvent * 1.E-9);
EXPECT_NEAR(rooDataSet->mean(x), targetXMean, 1.E-4);
EXPECT_NEAR(rooDataSet->moment(x, 2.), targetXVar, targetXVar * 1.E-4);
EXPECT_NEAR(rooDataSet->mean(y), targetYMean, 1.E-4);
EXPECT_NEAR(rooDataSet->moment(y, 2.), targetYVar, targetYVar * 1.E-4);
EXPECT_NEAR(rooDataHist->sumEntries(), nEvent, nEvent * 1.E-9);
EXPECT_NEAR(rooDataHist->mean(x), targetXMean, 1.E-4);
EXPECT_NEAR(rooDataHist->moment(x, 2.), 8.25, 1.E-2); // Variance is affected in a binned distribution
EXPECT_NEAR(rooDataHist->mean(y), targetYMean, 1.E-4);
EXPECT_NEAR(rooDataHist->moment(y, 2.), 0.25, 1.E-2); // Variance is affected in a binned distribution
}
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Flacon - audio File Encoder
* https://github.com/flacon/flacon
*
* Copyright: 2021
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "flacencoder.h"
QStringList FlacEncoder::programArgs() const
{
QStringList args;
args << programPath();
args << "--force"; // Force overwriting of output files.
args << "--silent"; // Suppress progress indicator
// Settings .................................................
// Compression parametr really looks like --compression-level-N
args << QString("--compression-level-%1").arg(profile().value("Compression").toString());
// Tags .....................................................
if (!track().artist().isEmpty())
args << "--tag" << QString("artist=%1").arg(track().artist());
if (!track().album().isEmpty())
args << "--tag" << QString("album=%1").arg(track().album());
if (!track().genre().isEmpty())
args << "--tag" << QString("genre=%1").arg(track().genre());
if (!track().date().isEmpty())
args << "--tag" << QString("date=%1").arg(track().date());
if (!track().title().isEmpty())
args << "--tag" << QString("title=%1").arg(track().title());
if (!track().tag(TagId::AlbumArtist).isEmpty())
args << "--tag" << QString("albumartist=%1").arg(track().tag(TagId::AlbumArtist));
if (!track().comment().isEmpty())
args << "--tag" << QString("comment=%1").arg(track().comment());
if (!track().discId().isEmpty())
args << "--tag" << QString("discId=%1").arg(track().discId());
args << "--tag" << QString("tracknumber=%1").arg(track().trackNum());
args << "--tag" << QString("totaltracks=%1").arg(track().trackCount());
args << "--tag" << QString("tracktotal=%1").arg(track().trackCount());
args << "--tag" << QString("disc=%1").arg(track().discNum());
args << "--tag" << QString("discnumber=%1").arg(track().discNum());
args << "--tag" << QString("disctotal=%1").arg(track().discCount());
if (!coverFile().isEmpty()) {
args << QString("--picture=%1").arg(coverFile());
}
if (profile().isEmbedCue()) {
args << "--tag" << QString("cuesheet=%1").arg(embeddedCue());
}
args << "-";
args << "-o" << outFile();
return args;
}
<commit_msg>fix(flac): replace `--tag` with `--tag-from-file` to workaround metadata encoding issue<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Flacon - audio File Encoder
* https://github.com/flacon/flacon
*
* Copyright: 2021
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "flacencoder.h"
#include <QFile>
QString writeMetadataFile(const QString &path,const QString &fieldName, const QString &fieldValue)
{
QString metadataFile = path + "." + fieldName;
QFile file(metadataFile);
if (file.open(QFile::WriteOnly)) {
file.write(fieldValue.toUtf8());
}
file.close();
return metadataFile;
}
QStringList FlacEncoder::programArgs() const
{
QStringList args;
args << programPath();
args << "--force"; // Force overwriting of output files.
args << "--silent"; // Suppress progress indicator
/**
* We ensure metadata for flac is utf-8 by using --tag-from-file option.
* flac's internal automatical utf8 conversion may cause unwanted result.
*
* Using `--tag` should be avoided, use `--tag-from-file` instead.
*
* see https://github.com/flacon/flacon/issues/176
*/
args << "--no-utf8-convert";
// Settings .................................................
// Compression parametr really looks like --compression-level-N
args << QString("--compression-level-%1").arg(profile().value("Compression").toString());
// Tags .....................................................
if (!track().artist().isEmpty())
args << "--tag" << QString("artist=%1").arg(track().artist());
if (!track().album().isEmpty())
args << "--tag-from-file" << QString("album=%1").arg(writeMetadataFile(outFile(), QString("album"), track().album()));
if (!track().genre().isEmpty())
args << "--tag-from-file" << QString("genre=%1").arg(writeMetadataFile(outFile(), QString("genre"), track().genre()));
if (!track().date().isEmpty())
args << "--tag-from-file" << QString("date=%1").arg(writeMetadataFile(outFile(), QString("date"), track().date()));
if (!track().title().isEmpty())
args << "--tag-from-file" << QString("title=%1").arg(writeMetadataFile(outFile(), QString("title"), track().title()));
if (!track().tag(TagId::AlbumArtist).isEmpty())
args << "--tag-from-file" << QString("albumartist=%1").arg(writeMetadataFile(outFile(), QString("albumartist"), track().tag(TagId::AlbumArtist)));
if (!track().comment().isEmpty())
args << "--tag-from-file" << QString("comment=%1").arg(writeMetadataFile(outFile(), QString("comment"), track().comment()));
if (!track().discId().isEmpty())
args << "--tag-from-file" << QString("discId=%1").arg(writeMetadataFile(outFile(), QString("discId"), track().discId()));
args << "--tag-from-file" << QString("tracknumber=%1").arg(writeMetadataFile(outFile(), QString("tracknumber"), QString(track().trackNum())));
args << "--tag-from-file" << QString("totaltracks=%1").arg(writeMetadataFile(outFile(), QString("totaltracks"), QString(track().trackCount())));
args << "--tag-from-file" << QString("tracktotal=%1").arg(writeMetadataFile(outFile(), QString("tracktotal"), QString(track().trackCount())));
args << "--tag-from-file" << QString("disc=%1").arg(writeMetadataFile(outFile(), QString("disc"), QString(track().discNum())));
args << "--tag-from-file" << QString("discnumber=%1").arg(writeMetadataFile(outFile(), QString("discnumber"), QString(track().discNum())));
args << "--tag-from-file" << QString("disctotal=%1").arg(writeMetadataFile(outFile(), QString("disctotal"), QString(track().discCount())));
if (!coverFile().isEmpty()) {
args << QString("--picture=%1").arg(coverFile());
}
if (profile().isEmbedCue()) {
args << "--tag-from-file" << QString("cuesheet=%1").arg(writeMetadataFile(outFile(), QString("cuesheet"), embeddedCue()));
}
args << "-";
args << "-o" << outFile();
return args;
}
<|endoftext|> |
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1996,1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <jgallagher@gso.uri.edu>
// Implementation for TestInt32. See TestByte.cc
//
// jhrg 1/12/95
#include "config.h"
#ifndef WIN32
#include <unistd.h>
#else
#include <io.h>
#include <fcntl.h>
#include <process.h>
#endif
#include "TestInt32.h"
extern int test_variable_sleep_interval;
void
TestInt32::_duplicate(const TestInt32 &ts)
{
d_series_values = ts.d_series_values;
}
TestInt32::TestInt32(const string &n) : Int32(n), d_series_values(false)
{
_buf = 1;
}
TestInt32::TestInt32(const TestInt32 &rhs) : Int32(rhs), TestCommon(rhs)
{
_duplicate(rhs);
}
TestInt32 &
TestInt32::operator=(const TestInt32 &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<Int32 &>(*this) = rhs; // run Constructor=
_duplicate(rhs);
return *this;
}
BaseType *
TestInt32::ptr_duplicate()
{
return new TestInt32(*this);
}
bool
TestInt32::read(const string &)
{
if (read_p())
return true;
if (test_variable_sleep_interval > 0)
sleep(test_variable_sleep_interval);
if (get_series_values()) {
_buf = 32 * _buf;
}
else {
_buf = 123456789;
}
set_read_p(true);
return true;
}
<commit_msg>TestInt32.cc: Modified so that on 64-bit machines the overflow of the '* 32' operation does not reset the value of _buf to zero, but instead _buf cycles back to 32.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1995-1996,1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// jhrg,jimg James Gallagher <jgallagher@gso.uri.edu>
// Implementation for TestInt32. See TestByte.cc
//
// jhrg 1/12/95
#include "config.h"
#ifndef WIN32
#include <unistd.h>
#else
#include <io.h>
#include <fcntl.h>
#include <process.h>
#endif
//#define DODS_DEBUG
#include "TestInt32.h"
#include "debug.h"
extern int test_variable_sleep_interval;
void
TestInt32::_duplicate(const TestInt32 &ts)
{
d_series_values = ts.d_series_values;
}
TestInt32::TestInt32(const string &n) : Int32(n), d_series_values(false)
{
_buf = 1;
}
TestInt32::TestInt32(const TestInt32 &rhs) : Int32(rhs), TestCommon(rhs)
{
_duplicate(rhs);
}
TestInt32 &
TestInt32::operator=(const TestInt32 &rhs)
{
if (this == &rhs)
return *this;
dynamic_cast<Int32 &>(*this) = rhs; // run Constructor=
_duplicate(rhs);
return *this;
}
BaseType *
TestInt32::ptr_duplicate()
{
return new TestInt32(*this);
}
bool
TestInt32::read(const string &)
{
DBG(cerr << "Entering TestInt32::read for " << name() << endl);
if (read_p())
return true;
if (test_variable_sleep_interval > 0)
sleep(test_variable_sleep_interval);
if (get_series_values()) {
_buf = 32 * _buf;
if (!_buf)
_buf = 32;
DBG(cerr << "In TestInt32::read, _buf = " << _buf << endl);
}
else {
_buf = 123456789;
}
set_read_p(true);
return true;
}
<|endoftext|> |
<commit_before>#include "parser/lexer.h"
#include "parser/token.h"
#include <stdio.h>
#include <stdlib.h>
namespace ceos {
class LexerTest {
public:
static void testRewind() {
Lexer l("1 (", 4);
l.token(Token::Type::NUMBER);
l.ensure(Token::Type::L_PAREN);
l.rewind();
l.token(Token::Type::L_PAREN);
l.ensure(Token::Type::END);
}
static void test() {
testRewind();
}
};
}
int main() {
ceos::LexerTest::test();
return 0;
}
<commit_msg>Fix lexer tests<commit_after>#include "parser/lexer.h"
#include "parser/token.h"
#include <stdio.h>
#include <stdlib.h>
namespace ceos {
class LexerTest {
public:
static void testRewind() {
Lexer l("1 (", 4);
l.token(Token::Type::NUMBER);
l.match('(');
l.rewind();
l.match('(');
l.token(Token::Type::END);
}
static void testRewindToSpecificLoc() {
Lexer l("1 (", 4);
auto start = l.token().loc;
l.token(Token::Type::NUMBER);
l.match('(');
l.token(Token::Type::END);
l.rewind(start);
l.token(Token::Type::NUMBER);
}
static void test() {
testRewind();
testRewindToSpecificLoc();
}
};
}
int main() {
ceos::LexerTest::test();
return 0;
}
<|endoftext|> |
<commit_before>#include <array>
#include <vorbis/vorbisfile.h>
#include "framework/data.h"
#include "framework/logger.h"
#include "framework/musicloader_interface.h"
#include "framework/sound.h"
namespace OpenApoc
{
namespace detail
{
static MusicTrack::MusicCallbackReturn fillMusicData(sp<MusicTrack> thisTrack,
unsigned int maxSamples, void *sampleBuffer,
unsigned int *returnedSamples);
struct VorbisMusicTrack : public MusicTrack
{
static MusicTrack::MusicCallbackReturn fillMusicData(sp<MusicTrack> thisTrack,
unsigned int maxSamples,
void *sampleBuffer,
unsigned int *returnedSamples)
{
auto music = std::dynamic_pointer_cast<VorbisMusicTrack>(thisTrack);
*returnedSamples = 0;
if (!music)
{
LogError("Trying to play non-vorbis music");
return MusicTrack::MusicCallbackReturn::End;
}
if (!music->_valid)
{
LogError("VorbisMusic: Trying to play non-valid track");
return MusicTrack::MusicCallbackReturn::End;
}
constexpr int bytes_per_sample = 2; // Always use S16
constexpr int samples_are_signed = 1;
constexpr int big_endian = 0; // Little endian only
const auto channels = music->format.channels;
auto buffer_bytes = maxSamples * bytes_per_sample * channels;
unsigned int total_read_bytes = 0;
char *output_buffer_position = static_cast<char *>(sampleBuffer);
while (buffer_bytes)
{
auto read_bytes =
ov_read(&music->_vorbis_file, output_buffer_position, buffer_bytes, big_endian,
bytes_per_sample, samples_are_signed, &music->_bitstream);
if (read_bytes < 0)
{
LogError("VorbisMusic: Error %d decoding music", read_bytes);
return MusicTrack::MusicCallbackReturn::End;
}
if (read_bytes == 0)
{
// EOF
*returnedSamples = total_read_bytes / bytes_per_sample;
return MusicTrack::MusicCallbackReturn::End;
}
LogAssert(read_bytes <= buffer_bytes);
buffer_bytes -= read_bytes;
total_read_bytes += read_bytes;
output_buffer_position += read_bytes;
}
*returnedSamples = total_read_bytes / (bytes_per_sample * channels);
return MusicTrack::MusicCallbackReturn::Continue;
}
public:
UString _name;
IFile _file;
OggVorbis_File _vorbis_file;
bool _valid = false;
int _bitstream = 0;
VorbisMusicTrack(const UString &name, IFile file) : _name(name), _file(std::move(file))
{
this->callback = fillMusicData;
// FIXME: Arbitrary buffer size?
this->requestedSampleBufferSize = 4096;
}
static size_t vorbis_read_func(void *ptr, size_t size, size_t nmemb, void *datasource)
{
// FIXME: May overflow on 32bit machines trying to read a 4gb+ file?
// But then there's no way that *ptr can point to that much memory anyway.....
size_t byte_size = size * nmemb;
auto *file = static_cast<IFile *>(datasource);
file->read(static_cast<char *>(ptr), byte_size);
auto read_bytes = file->gcount();
return read_bytes;
}
~VorbisMusicTrack() override
{
if (_valid)
{
ov_clear(&_vorbis_file);
}
}
const UString &getName() const override { return _name; }
static constexpr ov_callbacks callbacks = {
.read_func = vorbis_read_func,
.seek_func = nullptr,
.close_func = nullptr,
.tell_func = nullptr,
};
};
static constexpr std::array<int, 2> allowed_sample_rates = {22050, 44100};
static constexpr std::array<int, 2> allowed_channel_counts = {1, 2};
class VorbisMusicLoader : public MusicLoader
{
private:
Data &_data;
public:
VorbisMusicLoader(Data &data) : _data(data) {}
~VorbisMusicLoader() override = default;
sp<MusicTrack> loadMusic(UString path) override
{
auto file = _data.fs.open(path);
if (!file)
{
LogInfo("VorbisMusic: Failed to open \"%s\"", path);
return nullptr;
}
auto music = mksp<VorbisMusicTrack>(path, std::move(file));
auto ret = ov_open_callbacks(&music->_file, &music->_vorbis_file, nullptr, 0,
VorbisMusicTrack::callbacks);
if (ret < 0)
{
LogWarning("VorbisMusic: Error %d opening file \"%s\"", ret, path);
return nullptr;
}
music->_valid = true;
auto *info = ov_info(&music->_vorbis_file, -1);
if (!info)
{
LogWarning("VorbisMusic: Failed to read info for \"%s\"", path);
return nullptr;
}
bool valid_sample_rate = false;
for (const auto allowed_sample_rate : allowed_sample_rates)
{
if (allowed_sample_rate == info->rate)
{
valid_sample_rate = true;
break;
}
}
if (!valid_sample_rate)
{
LogWarning("VorbisMusic: \"%s\" has unsupported sample rate \"%d\"", path, info->rate);
return nullptr;
}
bool valid_channel_count = false;
for (const auto allowed_channel_count : allowed_channel_counts)
{
if (allowed_channel_count == info->channels)
{
valid_channel_count = true;
break;
}
}
if (!valid_channel_count)
{
LogWarning("VorbisMusic: \"%s\" has unsupported channel count \"%d\"", path,
info->channels);
return nullptr;
}
LogInfo("VorbisMusic: Successfully opened \"%s\" - channels: %d, samplerate: %d", path,
info->channels, info->rate);
music->format.channels = info->channels;
music->format.frequency = info->rate;
// Always assume sint16 - it'll convert it otherwise
music->format.format = OpenApoc::AudioFormat::SampleFormat::PCM_SINT16;
return music;
}
};
class VorbisMusicLoaderFactory : public MusicLoaderFactory
{
public:
MusicLoader *create(Data &data) override { return new VorbisMusicLoader(data); }
};
}; // namespace detail
MusicLoaderFactory *getVorbisMusicLoaderFactory() { return new detail::VorbisMusicLoaderFactory; }
} // namespace OpenApoc
<commit_msg>Remove unused static function prototype<commit_after>#include <array>
#include <vorbis/vorbisfile.h>
#include "framework/data.h"
#include "framework/logger.h"
#include "framework/musicloader_interface.h"
#include "framework/sound.h"
namespace OpenApoc
{
namespace detail
{
struct VorbisMusicTrack : public MusicTrack
{
static MusicTrack::MusicCallbackReturn fillMusicData(sp<MusicTrack> thisTrack,
unsigned int maxSamples,
void *sampleBuffer,
unsigned int *returnedSamples)
{
auto music = std::dynamic_pointer_cast<VorbisMusicTrack>(thisTrack);
*returnedSamples = 0;
if (!music)
{
LogError("Trying to play non-vorbis music");
return MusicTrack::MusicCallbackReturn::End;
}
if (!music->_valid)
{
LogError("VorbisMusic: Trying to play non-valid track");
return MusicTrack::MusicCallbackReturn::End;
}
constexpr int bytes_per_sample = 2; // Always use S16
constexpr int samples_are_signed = 1;
constexpr int big_endian = 0; // Little endian only
const auto channels = music->format.channels;
auto buffer_bytes = maxSamples * bytes_per_sample * channels;
unsigned int total_read_bytes = 0;
char *output_buffer_position = static_cast<char *>(sampleBuffer);
while (buffer_bytes)
{
auto read_bytes =
ov_read(&music->_vorbis_file, output_buffer_position, buffer_bytes, big_endian,
bytes_per_sample, samples_are_signed, &music->_bitstream);
if (read_bytes < 0)
{
LogError("VorbisMusic: Error %d decoding music", read_bytes);
return MusicTrack::MusicCallbackReturn::End;
}
if (read_bytes == 0)
{
// EOF
*returnedSamples = total_read_bytes / bytes_per_sample;
return MusicTrack::MusicCallbackReturn::End;
}
LogAssert(read_bytes <= buffer_bytes);
buffer_bytes -= read_bytes;
total_read_bytes += read_bytes;
output_buffer_position += read_bytes;
}
*returnedSamples = total_read_bytes / (bytes_per_sample * channels);
return MusicTrack::MusicCallbackReturn::Continue;
}
public:
UString _name;
IFile _file;
OggVorbis_File _vorbis_file;
bool _valid = false;
int _bitstream = 0;
VorbisMusicTrack(const UString &name, IFile file) : _name(name), _file(std::move(file))
{
this->callback = fillMusicData;
// FIXME: Arbitrary buffer size?
this->requestedSampleBufferSize = 4096;
}
static size_t vorbis_read_func(void *ptr, size_t size, size_t nmemb, void *datasource)
{
// FIXME: May overflow on 32bit machines trying to read a 4gb+ file?
// But then there's no way that *ptr can point to that much memory anyway.....
size_t byte_size = size * nmemb;
auto *file = static_cast<IFile *>(datasource);
file->read(static_cast<char *>(ptr), byte_size);
auto read_bytes = file->gcount();
return read_bytes;
}
~VorbisMusicTrack() override
{
if (_valid)
{
ov_clear(&_vorbis_file);
}
}
const UString &getName() const override { return _name; }
static constexpr ov_callbacks callbacks = {
.read_func = vorbis_read_func,
.seek_func = nullptr,
.close_func = nullptr,
.tell_func = nullptr,
};
};
static constexpr std::array<int, 2> allowed_sample_rates = {22050, 44100};
static constexpr std::array<int, 2> allowed_channel_counts = {1, 2};
class VorbisMusicLoader : public MusicLoader
{
private:
Data &_data;
public:
VorbisMusicLoader(Data &data) : _data(data) {}
~VorbisMusicLoader() override = default;
sp<MusicTrack> loadMusic(UString path) override
{
auto file = _data.fs.open(path);
if (!file)
{
LogInfo("VorbisMusic: Failed to open \"%s\"", path);
return nullptr;
}
auto music = mksp<VorbisMusicTrack>(path, std::move(file));
auto ret = ov_open_callbacks(&music->_file, &music->_vorbis_file, nullptr, 0,
VorbisMusicTrack::callbacks);
if (ret < 0)
{
LogWarning("VorbisMusic: Error %d opening file \"%s\"", ret, path);
return nullptr;
}
music->_valid = true;
auto *info = ov_info(&music->_vorbis_file, -1);
if (!info)
{
LogWarning("VorbisMusic: Failed to read info for \"%s\"", path);
return nullptr;
}
bool valid_sample_rate = false;
for (const auto allowed_sample_rate : allowed_sample_rates)
{
if (allowed_sample_rate == info->rate)
{
valid_sample_rate = true;
break;
}
}
if (!valid_sample_rate)
{
LogWarning("VorbisMusic: \"%s\" has unsupported sample rate \"%d\"", path, info->rate);
return nullptr;
}
bool valid_channel_count = false;
for (const auto allowed_channel_count : allowed_channel_counts)
{
if (allowed_channel_count == info->channels)
{
valid_channel_count = true;
break;
}
}
if (!valid_channel_count)
{
LogWarning("VorbisMusic: \"%s\" has unsupported channel count \"%d\"", path,
info->channels);
return nullptr;
}
LogInfo("VorbisMusic: Successfully opened \"%s\" - channels: %d, samplerate: %d", path,
info->channels, info->rate);
music->format.channels = info->channels;
music->format.frequency = info->rate;
// Always assume sint16 - it'll convert it otherwise
music->format.format = OpenApoc::AudioFormat::SampleFormat::PCM_SINT16;
return music;
}
};
class VorbisMusicLoaderFactory : public MusicLoaderFactory
{
public:
MusicLoader *create(Data &data) override { return new VorbisMusicLoader(data); }
};
}; // namespace detail
MusicLoaderFactory *getVorbisMusicLoaderFactory() { return new detail::VorbisMusicLoaderFactory; }
} // namespace OpenApoc
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.