text stringlengths 54 60.6k |
|---|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Image Engine Design 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 Image Engine Design nor the names of
// any other contributors to this software 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 "GafferImage/Resize.h"
#include "GafferImage/Resample.h"
#include "GafferImage/Sampler.h"
#include "Gaffer/StringPlug.h"
using namespace Imath;
using namespace Gaffer;
using namespace GafferImage;
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Resize );
size_t Resize::g_firstPlugIndex = 0;
Resize::Resize( const std::string &name )
: FlatImageProcessor( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new FormatPlug( "format" ) );
addChild( new IntPlug( "fitMode", Plug::In, Horizontal, Horizontal, Distort ) );
addChild( new StringPlug( "filter" ) );
addChild( new M33fPlug( "__matrix", Plug::Out ) );
addChild( new ImagePlug( "__resampledIn", Plug::In, Plug::Default & ~Plug::Serialisable ) );
// We don't really do much work ourselves - we just
// defer to an internal Resample node to do the hard
// work of filtering everything into the right place.
ResamplePtr resample = new Resample( "__resample" );
addChild( resample );
resample->inPlug()->setInput( inPlug() );
resample->filterPlug()->setInput( filterPlug() );
resample->matrixPlug()->setInput( matrixPlug() );
resample->boundingModePlug()->setValue( Sampler::Clamp );
resampledInPlug()->setInput( resample->outPlug() );
outPlug()->metadataPlug()->setInput( inPlug()->metadataPlug() );
outPlug()->channelNamesPlug()->setInput( inPlug()->channelNamesPlug() );
}
Resize::~Resize()
{
}
GafferImage::FormatPlug *Resize::formatPlug()
{
return getChild<FormatPlug>( g_firstPlugIndex );
}
const GafferImage::FormatPlug *Resize::formatPlug() const
{
return getChild<FormatPlug>( g_firstPlugIndex );
}
Gaffer::IntPlug *Resize::fitModePlug()
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::IntPlug *Resize::fitModePlug() const
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
Gaffer::StringPlug *Resize::filterPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::StringPlug *Resize::filterPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
Gaffer::M33fPlug *Resize::matrixPlug()
{
return getChild<M33fPlug>( g_firstPlugIndex + 3 );
}
const Gaffer::M33fPlug *Resize::matrixPlug() const
{
return getChild<M33fPlug>( g_firstPlugIndex + 3 );
}
ImagePlug *Resize::resampledInPlug()
{
return getChild<ImagePlug>( g_firstPlugIndex + 4 );
}
const ImagePlug *Resize::resampledInPlug() const
{
return getChild<ImagePlug>( g_firstPlugIndex + 4 );
}
void Resize::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
FlatImageProcessor::affects( input, outputs );
if(
formatPlug()->isAncestorOf( input ) ||
input == fitModePlug() ||
input == inPlug()->formatPlug() ||
input == inPlug()->dataWindowPlug()
)
{
outputs.push_back( matrixPlug() );
}
if( formatPlug()->isAncestorOf( input ) )
{
outputs.push_back( outPlug()->formatPlug() );
}
if(
input == inPlug()->dataWindowPlug() ||
input == resampledInPlug()->dataWindowPlug()
)
{
outputs.push_back( outPlug()->dataWindowPlug() );
}
if(
input == inPlug()->channelDataPlug() ||
input == resampledInPlug()->channelDataPlug()
)
{
outputs.push_back( outPlug()->channelDataPlug() );
}
}
void Resize::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const
{
FlatImageProcessor::hash( output, context, h );
if( output == matrixPlug() )
{
formatPlug()->hash( h );
fitModePlug()->hash( h );
inPlug()->formatPlug()->hash( h );
inPlug()->dataWindowPlug()->hash( h );
}
}
void Resize::compute( ValuePlug *output, const Context *context ) const
{
if( output == matrixPlug() )
{
const Format inFormat = inPlug()->formatPlug()->getValue();
const Format outFormat = formatPlug()->getValue();
const V2f inSize( inFormat.width(), inFormat.height() );
const V2f outSize( outFormat.width(), outFormat.height() );
const V2f formatScale = outSize / inSize;
const float pixelAspectScale = outFormat.getPixelAspect() / inFormat.getPixelAspect();
FitMode fitMode = (FitMode)fitModePlug()->getValue();
if( fitMode == Fit )
{
fitMode = formatScale.x * pixelAspectScale < formatScale.y ? Horizontal : Vertical;
}
else if( fitMode == Fill )
{
fitMode = formatScale.x * pixelAspectScale < formatScale.y ? Vertical : Horizontal;
}
V2f scale;
switch( fitMode )
{
case Horizontal :
scale = V2f( formatScale.x, formatScale.x * pixelAspectScale );
break;
case Vertical :
scale = V2f( formatScale.y / pixelAspectScale, formatScale.y );
break;
case Distort :
default :
scale = formatScale;
break;
}
const V2f translate = ( outSize - ( inSize * scale ) ) / 2.0f;
M33f matrix;
matrix.translate( translate );
matrix.scale( scale );
static_cast<M33fPlug *>( output )->setValue( matrix );
}
FlatImageProcessor::compute( output, context );
}
void Resize::hashFormat( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = formatPlug()->hash();
}
GafferImage::Format Resize::computeFormat( const Gaffer::Context *context, const ImagePlug *parent ) const
{
return formatPlug()->getValue();
}
void Resize::hashDataWindow( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = source()->dataWindowPlug()->hash();
}
Imath::Box2i Resize::computeDataWindow( const Gaffer::Context *context, const ImagePlug *parent ) const
{
return source()->dataWindowPlug()->getValue();
}
void Resize::hashChannelData( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = source()->channelDataPlug()->hash();
}
IECore::ConstFloatVectorDataPtr Resize::computeChannelData( const std::string &channelName, const Imath::V2i &tileOrigin, const Gaffer::Context *context, const ImagePlug *parent ) const
{
return source()->channelDataPlug()->getValue();
}
const ImagePlug *Resize::source() const
{
ImagePlug::GlobalScope c( Context::current() );
if( formatPlug()->getValue().getDisplayWindow() == inPlug()->formatPlug()->getValue().getDisplayWindow() )
{
return inPlug();
}
else
{
return resampledInPlug();
}
}
<commit_msg>GafferImage::Resize::affects() : Account for plugs used by source()<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Image Engine Design 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 Image Engine Design nor the names of
// any other contributors to this software 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 "GafferImage/Resize.h"
#include "GafferImage/Resample.h"
#include "GafferImage/Sampler.h"
#include "Gaffer/StringPlug.h"
using namespace Imath;
using namespace Gaffer;
using namespace GafferImage;
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Resize );
size_t Resize::g_firstPlugIndex = 0;
Resize::Resize( const std::string &name )
: FlatImageProcessor( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new FormatPlug( "format" ) );
addChild( new IntPlug( "fitMode", Plug::In, Horizontal, Horizontal, Distort ) );
addChild( new StringPlug( "filter" ) );
addChild( new M33fPlug( "__matrix", Plug::Out ) );
addChild( new ImagePlug( "__resampledIn", Plug::In, Plug::Default & ~Plug::Serialisable ) );
// We don't really do much work ourselves - we just
// defer to an internal Resample node to do the hard
// work of filtering everything into the right place.
ResamplePtr resample = new Resample( "__resample" );
addChild( resample );
resample->inPlug()->setInput( inPlug() );
resample->filterPlug()->setInput( filterPlug() );
resample->matrixPlug()->setInput( matrixPlug() );
resample->boundingModePlug()->setValue( Sampler::Clamp );
resampledInPlug()->setInput( resample->outPlug() );
outPlug()->metadataPlug()->setInput( inPlug()->metadataPlug() );
outPlug()->channelNamesPlug()->setInput( inPlug()->channelNamesPlug() );
}
Resize::~Resize()
{
}
GafferImage::FormatPlug *Resize::formatPlug()
{
return getChild<FormatPlug>( g_firstPlugIndex );
}
const GafferImage::FormatPlug *Resize::formatPlug() const
{
return getChild<FormatPlug>( g_firstPlugIndex );
}
Gaffer::IntPlug *Resize::fitModePlug()
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::IntPlug *Resize::fitModePlug() const
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
Gaffer::StringPlug *Resize::filterPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::StringPlug *Resize::filterPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
Gaffer::M33fPlug *Resize::matrixPlug()
{
return getChild<M33fPlug>( g_firstPlugIndex + 3 );
}
const Gaffer::M33fPlug *Resize::matrixPlug() const
{
return getChild<M33fPlug>( g_firstPlugIndex + 3 );
}
ImagePlug *Resize::resampledInPlug()
{
return getChild<ImagePlug>( g_firstPlugIndex + 4 );
}
const ImagePlug *Resize::resampledInPlug() const
{
return getChild<ImagePlug>( g_firstPlugIndex + 4 );
}
void Resize::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
FlatImageProcessor::affects( input, outputs );
if(
formatPlug()->isAncestorOf( input ) ||
input == fitModePlug() ||
input == inPlug()->formatPlug() ||
input == inPlug()->dataWindowPlug()
)
{
outputs.push_back( matrixPlug() );
}
if( formatPlug()->isAncestorOf( input ) )
{
outputs.push_back( outPlug()->formatPlug() );
}
if(
input == inPlug()->dataWindowPlug() ||
input == resampledInPlug()->dataWindowPlug() ||
input == inPlug()->formatPlug() ||
formatPlug()->isAncestorOf( input )
)
{
outputs.push_back( outPlug()->dataWindowPlug() );
}
if(
input == inPlug()->channelDataPlug() ||
input == resampledInPlug()->channelDataPlug() ||
input == inPlug()->formatPlug() ||
formatPlug()->isAncestorOf( input )
)
{
outputs.push_back( outPlug()->channelDataPlug() );
}
}
void Resize::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const
{
FlatImageProcessor::hash( output, context, h );
if( output == matrixPlug() )
{
formatPlug()->hash( h );
fitModePlug()->hash( h );
inPlug()->formatPlug()->hash( h );
inPlug()->dataWindowPlug()->hash( h );
}
}
void Resize::compute( ValuePlug *output, const Context *context ) const
{
if( output == matrixPlug() )
{
const Format inFormat = inPlug()->formatPlug()->getValue();
const Format outFormat = formatPlug()->getValue();
const V2f inSize( inFormat.width(), inFormat.height() );
const V2f outSize( outFormat.width(), outFormat.height() );
const V2f formatScale = outSize / inSize;
const float pixelAspectScale = outFormat.getPixelAspect() / inFormat.getPixelAspect();
FitMode fitMode = (FitMode)fitModePlug()->getValue();
if( fitMode == Fit )
{
fitMode = formatScale.x * pixelAspectScale < formatScale.y ? Horizontal : Vertical;
}
else if( fitMode == Fill )
{
fitMode = formatScale.x * pixelAspectScale < formatScale.y ? Vertical : Horizontal;
}
V2f scale;
switch( fitMode )
{
case Horizontal :
scale = V2f( formatScale.x, formatScale.x * pixelAspectScale );
break;
case Vertical :
scale = V2f( formatScale.y / pixelAspectScale, formatScale.y );
break;
case Distort :
default :
scale = formatScale;
break;
}
const V2f translate = ( outSize - ( inSize * scale ) ) / 2.0f;
M33f matrix;
matrix.translate( translate );
matrix.scale( scale );
static_cast<M33fPlug *>( output )->setValue( matrix );
}
FlatImageProcessor::compute( output, context );
}
void Resize::hashFormat( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = formatPlug()->hash();
}
GafferImage::Format Resize::computeFormat( const Gaffer::Context *context, const ImagePlug *parent ) const
{
return formatPlug()->getValue();
}
void Resize::hashDataWindow( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = source()->dataWindowPlug()->hash();
}
Imath::Box2i Resize::computeDataWindow( const Gaffer::Context *context, const ImagePlug *parent ) const
{
return source()->dataWindowPlug()->getValue();
}
void Resize::hashChannelData( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
h = source()->channelDataPlug()->hash();
}
IECore::ConstFloatVectorDataPtr Resize::computeChannelData( const std::string &channelName, const Imath::V2i &tileOrigin, const Gaffer::Context *context, const ImagePlug *parent ) const
{
return source()->channelDataPlug()->getValue();
}
const ImagePlug *Resize::source() const
{
ImagePlug::GlobalScope c( Context::current() );
if( formatPlug()->getValue().getDisplayWindow() == inPlug()->formatPlug()->getValue().getDisplayWindow() )
{
return inPlug();
}
else
{
return resampledInPlug();
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU 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 *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Inventor/nodes/SoGroup.h>
# include <QHeaderView>
#endif
#include "SceneInspector.h"
#include "ui_SceneInspector.h"
#include "MainWindow.h"
#include "View3DInventor.h"
#include "View3DInventorViewer.h"
using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::SceneModel */
SceneModel::SceneModel(QObject* parent)
: QStandardItemModel(parent)
{
}
SceneModel::~SceneModel()
{
}
int SceneModel::columnCount (const QModelIndex & parent) const
{
return 1;
}
Qt::ItemFlags SceneModel::flags (const QModelIndex & index) const
{
return QAbstractItemModel::flags(index);
}
QVariant SceneModel::headerData (int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role != Qt::DisplayRole)
return QVariant();
if (section == 0)
return tr("Inventor Tree");
}
return QVariant();
}
bool SceneModel::setHeaderData (int, Qt::Orientation, const QVariant &, int)
{
return false;
}
void SceneModel::setNode(SoNode* node)
{
this->clear();
this->setHeaderData(0, Qt::Horizontal, tr("Nodes"), Qt::DisplayRole);
this->insertColumns(0,1);
this->insertRows(0,1);
setNode(this->index(0, 0),node);
}
void SceneModel::setNode(QModelIndex index, SoNode* node)
{
this->setData(index, QVariant(QString::fromAscii(node->getTypeId().getName())));
if (node->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) {
SoGroup *group = static_cast<SoGroup*>(node);
// insert SoGroup icon
this->insertColumns(0,1,index);
this->insertRows(0,group->getNumChildren(), index);
for (int i=0; i<group->getNumChildren();i++) {
SoNode* child = group->getChild(i);
setNode(this->index(i, 0, index), child);
}
}
// insert icon
}
// --------------------------------------------------------
/* TRANSLATOR Gui::Dialog::DlgInspector */
DlgInspector::DlgInspector(QWidget* parent, Qt::WFlags fl)
: QDialog(parent, fl), ui(new Ui_SceneInspector())
{
ui->setupUi(this);
setWindowTitle(tr("Scene Inspector"));
SceneModel* model = new SceneModel(this);
ui->treeView->setModel(model);
ui->treeView->setRootIsDecorated(true);
}
/*
* Destroys the object and frees any allocated resources
*/
DlgInspector::~DlgInspector()
{
// no need to delete child widgets, Qt does it all for us
delete ui;
}
void DlgInspector::setNode(SoNode* node)
{
SceneModel* model = static_cast<SceneModel*>(ui->treeView->model());
model->setNode(node);
QHeaderView* header = ui->treeView->header();
header->setResizeMode(0, QHeaderView::Stretch);
header->setMovable(false);
}
void DlgInspector::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
setWindowTitle(tr("Scene Inspector"));
}
QDialog::changeEvent(e);
}
void DlgInspector::on_refreshButton_clicked()
{
View3DInventor* child = qobject_cast<View3DInventor*>(getMainWindow()->activeWindow());
if (child) {
View3DInventorViewer* viewer = child->getViewer();
setNode(viewer->getSceneGraph());
ui->treeView->expandToDepth(3);
}
else {
SceneModel* model = static_cast<SceneModel*>(ui->treeView->model());
model->clear();
}
}
#include "moc_SceneInspector.cpp"
<commit_msg>+ Show also name of Inventor nodes in Scene Inspector<commit_after>/***************************************************************************
* Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU 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 *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Inventor/nodes/SoGroup.h>
# include <QHeaderView>
#endif
#include "SceneInspector.h"
#include "ui_SceneInspector.h"
#include "MainWindow.h"
#include "View3DInventor.h"
#include "View3DInventorViewer.h"
using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::SceneModel */
SceneModel::SceneModel(QObject* parent)
: QStandardItemModel(parent)
{
}
SceneModel::~SceneModel()
{
}
int SceneModel::columnCount (const QModelIndex & parent) const
{
return 2;
}
Qt::ItemFlags SceneModel::flags (const QModelIndex & index) const
{
return QAbstractItemModel::flags(index);
}
QVariant SceneModel::headerData (int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role != Qt::DisplayRole)
return QVariant();
if (section == 0)
return tr("Inventor Tree");
else if (section == 1)
return tr("Name");
}
return QVariant();
}
bool SceneModel::setHeaderData (int, Qt::Orientation, const QVariant &, int)
{
return false;
}
void SceneModel::setNode(SoNode* node)
{
this->clear();
this->setHeaderData(0, Qt::Horizontal, tr("Nodes"), Qt::DisplayRole);
this->insertColumns(0,2);
this->insertRows(0,1);
setNode(this->index(0, 0), node);
}
void SceneModel::setNode(QModelIndex index, SoNode* node)
{
this->setData(index, QVariant(QString::fromAscii(node->getTypeId().getName())));
if (node->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) {
SoGroup *group = static_cast<SoGroup*>(node);
// insert SoGroup icon
this->insertColumns(0,2,index);
this->insertRows(0,group->getNumChildren(), index);
for (int i=0; i<group->getNumChildren();i++) {
SoNode* child = group->getChild(i);
setNode(this->index(i, 0, index), child);
this->setData(this->index(i, 1, index), QVariant(QString::fromAscii(child->getName())));
}
}
// insert icon
}
// --------------------------------------------------------
/* TRANSLATOR Gui::Dialog::DlgInspector */
DlgInspector::DlgInspector(QWidget* parent, Qt::WFlags fl)
: QDialog(parent, fl), ui(new Ui_SceneInspector())
{
ui->setupUi(this);
setWindowTitle(tr("Scene Inspector"));
SceneModel* model = new SceneModel(this);
ui->treeView->setModel(model);
ui->treeView->setRootIsDecorated(true);
}
/*
* Destroys the object and frees any allocated resources
*/
DlgInspector::~DlgInspector()
{
// no need to delete child widgets, Qt does it all for us
delete ui;
}
void DlgInspector::setNode(SoNode* node)
{
SceneModel* model = static_cast<SceneModel*>(ui->treeView->model());
model->setNode(node);
QHeaderView* header = ui->treeView->header();
header->setResizeMode(0, QHeaderView::Stretch);
header->setMovable(false);
}
void DlgInspector::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
setWindowTitle(tr("Scene Inspector"));
}
QDialog::changeEvent(e);
}
void DlgInspector::on_refreshButton_clicked()
{
View3DInventor* child = qobject_cast<View3DInventor*>(getMainWindow()->activeWindow());
if (child) {
View3DInventorViewer* viewer = child->getViewer();
setNode(viewer->getSceneGraph());
ui->treeView->expandToDepth(3);
}
else {
SceneModel* model = static_cast<SceneModel*>(ui->treeView->model());
model->clear();
}
}
#include "moc_SceneInspector.cpp"
<|endoftext|> |
<commit_before>#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <set>
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include "InotifyFileWatcher.hpp"
#include "../common/FormattedException.hpp"
using namespace std;
namespace logging = boost::log;
struct RC2::InotifyFileWatcher::FSObject
{
string name;
struct stat sb;
int wd;
inline bool is_dir() const { return S_ISDIR(sb.st_mode); }
};
struct RC2::InotifyFileWatcher::Impl
{
int inotifyFd;
struct event_base* eventBase;
string dirPath;
map<int, FSObject> files;
FSObject root;
set<string> addedFiles;
set<string> modifiedFiles;
set<string> deletedFiles;
};
RC2::InotifyFileWatcher::InotifyFileWatcher(struct event_base *eb)
: _impl(new Impl())
{
_impl->eventBase = eb;
_impl->inotifyFd = -1;
}
RC2::InotifyFileWatcher::~InotifyFileWatcher()
{
if (_impl->inotifyFd != -1)
close(_impl->inotifyFd);
}
void
RC2::InotifyFileWatcher::initializeWatcher(std::string dirPath)
{
_impl->dirPath = dirPath;
DIR *dir;
class dirent *ent;
_impl->inotifyFd = inotify_init();
if (_impl->inotifyFd == -1)
throw FormattedException("inotify_init() failed for %s", dirPath.c_str());
_impl->root.wd = inotify_add_watch(_impl->inotifyFd, dirPath.c_str(),
IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF | IN_MOVE);
if (_impl->root.wd == -1)
throw FormattedException("inotify_add_watched failed");
stat(dirPath.c_str(), &_impl->root.sb);
_impl->files[_impl->root.wd] = _impl->root;
BOOST_LOG_TRIVIAL(info) << "watching " << dirPath << endl;
dir = opendir(dirPath.c_str());
while ((ent = readdir(dir)) != NULL) {
//skip "." and ".." but not other files that start with a period
if (ent->d_name[0] == '.' && (strlen(ent->d_name) == 1 || ent->d_name[1] == '.'))
continue;
FSObject fo;
fo.name = ent->d_name;
string fullPath = dirPath + "/" + fo.name;
if (stat(fullPath.c_str(), &fo.sb) == -1)
continue;
fo.wd = inotify_add_watch(_impl->inotifyFd, fullPath.c_str(),
IN_CLOSE_WRITE | IN_DELETE_SELF | IN_MODIFY);
if (fo.wd == -1)
throw FormattedException("inotify_add_warched failed %s", fo.name.c_str());
_impl->files[fo.wd] = fo;
BOOST_LOG_TRIVIAL(info) << "watching " << fo.name << endl;
}
closedir(dir);
struct bufferevent *evt = bufferevent_socket_new(_impl->eventBase, _impl->inotifyFd, 0);
bufferevent_setcb(evt, InotifyFileWatcher::handleInotifyEvent, NULL, NULL, static_cast<void*>(this));
bufferevent_enable(evt, EV_READ);
}
#define I_BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1))
void
RC2::InotifyFileWatcher::handleInotifyEvent(struct bufferevent *bev)
{
BOOST_LOG_TRIVIAL(info) << "handleInotify called" << endl;
char buf[I_BUF_LEN];
size_t numRead = bufferevent_read(bev, buf, I_BUF_LEN);
char *p;
for (p=buf; p < buf + numRead; ) {
struct inotify_event *event = (struct inotify_event*)p;
if(event->mask & IN_CREATE) {
_impl->addedFiles.insert((string)event->name);
} else if (event->mask & IN_CLOSE_WRITE) {
_impl->modifiedFiles.insert((string)event->name);
}
//handle event
p += sizeof(struct inotify_event) + event->len;
}
}
void
RC2::InotifyFileWatcher::startWatch()
{
_impl->addedFiles.clear();
_impl->modifiedFiles.clear();
_impl->deletedFiles.clear();
}
void
RC2::InotifyFileWatcher::stopWatch(std::vector<std::string> &added,
std::vector<std::string> &modified,
std::vector<std::string> &deleted)
{
copy(_impl->addedFiles.begin(), _impl->addedFiles.end(), back_inserter(added));
copy(_impl->modifiedFiles.begin(), _impl->modifiedFiles.end(), back_inserter(modified));
copy(_impl->deletedFiles.begin(), _impl->deletedFiles.end(), back_inserter(deleted));
}
<commit_msg>properly handles create, write, delete events<commit_after>#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <set>
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include "InotifyFileWatcher.hpp"
#include "../common/FormattedException.hpp"
using namespace std;
namespace logging = boost::log;
struct RC2::InotifyFileWatcher::FSObject
{
string name;
struct stat sb;
int wd;
inline bool is_dir() const { return S_ISDIR(sb.st_mode); }
};
struct RC2::InotifyFileWatcher::Impl
{
int inotifyFd;
struct event_base* eventBase;
string dirPath;
map<int, FSObject> files;
FSObject root;
set<string> addedFiles;
set<string> modifiedFiles;
set<string> deletedFiles;
void watchFile(string fname) {
FSObject fo;
fo.name = fname;
string fullPath = dirPath + "/" + fo.name;
if (stat(fullPath.c_str(), &fo.sb) == -1)
return;
fo.wd = inotify_add_watch(inotifyFd, fullPath.c_str(),
IN_CLOSE_WRITE | IN_DELETE_SELF | IN_MODIFY);
if (fo.wd == -1)
throw FormattedException("inotify_add_warched failed %s", fo.name.c_str());
files[fo.wd] = fo;
BOOST_LOG_TRIVIAL(info) << "watching " << fo.name << endl;
}
};
RC2::InotifyFileWatcher::InotifyFileWatcher(struct event_base *eb)
: _impl(new Impl())
{
_impl->eventBase = eb;
_impl->inotifyFd = -1;
}
RC2::InotifyFileWatcher::~InotifyFileWatcher()
{
if (_impl->inotifyFd != -1)
close(_impl->inotifyFd);
}
void
RC2::InotifyFileWatcher::initializeWatcher(std::string dirPath)
{
_impl->dirPath = dirPath;
DIR *dir;
class dirent *ent;
_impl->inotifyFd = inotify_init();
if (_impl->inotifyFd == -1)
throw FormattedException("inotify_init() failed for %s", dirPath.c_str());
_impl->root.wd = inotify_add_watch(_impl->inotifyFd, dirPath.c_str(),
IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF | IN_MOVE);
if (_impl->root.wd == -1)
throw FormattedException("inotify_add_watched failed");
stat(dirPath.c_str(), &_impl->root.sb);
_impl->files[_impl->root.wd] = _impl->root;
BOOST_LOG_TRIVIAL(info) << "watching " << dirPath << endl;
dir = opendir(dirPath.c_str());
while ((ent = readdir(dir)) != NULL) {
//skip "." and ".." but not other files that start with a period
if (ent->d_name[0] == '.' && (strlen(ent->d_name) == 1 || ent->d_name[1] == '.'))
continue;
_impl->watchFile(ent->d_name);
}
closedir(dir);
struct bufferevent *evt = bufferevent_socket_new(_impl->eventBase, _impl->inotifyFd, 0);
bufferevent_setcb(evt, InotifyFileWatcher::handleInotifyEvent, NULL, NULL, static_cast<void*>(this));
bufferevent_enable(evt, EV_READ);
}
#define I_BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1))
void
RC2::InotifyFileWatcher::handleInotifyEvent(struct bufferevent *bev)
{
BOOST_LOG_TRIVIAL(info) << "handleInotify called" << endl;
char buf[I_BUF_LEN];
size_t numRead = bufferevent_read(bev, buf, I_BUF_LEN);
char *p;
for (p=buf; p < buf + numRead; ) {
struct inotify_event *event = (struct inotify_event*)p;
int evtype = event->mask & 0xffff;
cerr << "notify:" << std::hex << evtype << " for " <<
_impl->files[event->wd].name << endl;
if(evtype == IN_CREATE) {
_impl->addedFiles.insert((string)event->name);
_impl->watchFile(event->name);
//need to add a watch for this file
} else if (evtype == IN_CLOSE_WRITE) {
_impl->modifiedFiles.insert((string)event->name);
} else if (evtype == IN_DELETE_SELF) {
cerr << "in delete called for " << event->name << endl;
_impl->deletedFiles.insert((string)event->name);
//discard our records of it
inotify_rm_watch(_impl->inotifyFd, event->wd);
_impl->files.erase(event->wd);
}
//handle event
p += sizeof(struct inotify_event) + event->len;
}
}
void
RC2::InotifyFileWatcher::startWatch()
{
_impl->addedFiles.clear();
_impl->modifiedFiles.clear();
_impl->deletedFiles.clear();
}
void
RC2::InotifyFileWatcher::stopWatch(std::vector<std::string> &added,
std::vector<std::string> &modified,
std::vector<std::string> &deleted)
{
copy(_impl->addedFiles.begin(), _impl->addedFiles.end(), back_inserter(added));
copy(_impl->modifiedFiles.begin(), _impl->modifiedFiles.end(), back_inserter(modified));
copy(_impl->deletedFiles.begin(), _impl->deletedFiles.end(), back_inserter(deleted));
}
<|endoftext|> |
<commit_before>#include "Input/FPGAReceiver.h"
FPGAReceiver::FPGAReceiver(QObject * receiver, QObject * parent) : QObject(parent), m_indexRead(-1), m_lastCommandSent(None), m_receiver(receiver)
{
m_updateTimer.setInterval(8);
connect(&m_updateTimer, &QTimer::timeout, this, &FPGAReceiver::updateFPGA);
m_updateTimer.start();
}
FPGAReceiver::~FPGAReceiver()
{
}
void FPGAReceiver::updateFPGA()
{
#ifdef Q_OS_WIN
if (!m_fpga.estOk()) {
emit fpgaError(QString::fromUtf8(m_fpga.messageErreur()));
return;
}
if (!m_fpga.lireRegistre(0, m_indexRead)) {
emit fpgaError(QString::fromUtf8(m_fpga.messageErreur()));
m_indexRead = -1;
return;
} else {
switch (m_indexRead)
{
case 1:
m_lastCommandSent = Increase;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Increase));
break;
case 2:
if(m_lastCommandSent != Change)
{
m_lastCommandSent = Change;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Change));
}
break;
case 3:
m_lastCommandSent = Decrease;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Decrease));
break;
default:
break;
}
}
#endif
}
void FPGAReceiver::handlePressEvent(QKeyEvent *KeyEvent)
{
switch (KeyEvent->key()){
case Qt::Key_Right:
if (KeyEvent->isAutoRepeat())
return;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Change));
break;
/*case Qt::Key_Left:
if (KeyEvent->isAutoRepeat())
return;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Change));
break;*/
case Qt::Key_Up:
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Increase));
break;
case Qt::Key_Down:
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Decrease));
break;
default:
break;
}
}
<commit_msg>Add FPGA receiver comments<commit_after>#include "Input/FPGAReceiver.h"
FPGAReceiver::FPGAReceiver(QObject * receiver, QObject * parent) : QObject(parent), m_indexRead(-1), m_lastCommandSent(None), m_receiver(receiver)
{
m_updateTimer.setInterval(8);
connect(&m_updateTimer, &QTimer::timeout, this, &FPGAReceiver::updateFPGA);
m_updateTimer.start();
}
FPGAReceiver::~FPGAReceiver()
{
}
void FPGAReceiver::updateFPGA()
{
//If OS is windows, use FPGA
#ifdef Q_OS_WIN
if (!m_fpga.estOk()) {
emit fpgaError(QString::fromUtf8(m_fpga.messageErreur()));
return;
}
if (!m_fpga.lireRegistre(0, m_indexRead)) {
emit fpgaError(QString::fromUtf8(m_fpga.messageErreur()));
m_indexRead = -1;
return;
} else {
switch (m_indexRead)
{
case 1:
m_lastCommandSent = Increase;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Increase));
break;
case 2:
if(m_lastCommandSent != Change)
{
m_lastCommandSent = Change;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Change));
}
break;
case 3:
m_lastCommandSent = Decrease;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Decrease));
break;
default:
break;
}
}
#endif
}
void FPGAReceiver::handlePressEvent(QKeyEvent *KeyEvent)
{
//Handle events
switch (KeyEvent->key()){
case Qt::Key_Right:
if (KeyEvent->isAutoRepeat())
return;
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Change));
break;
case Qt::Key_Up:
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Increase));
break;
case Qt::Key_Down:
QCoreApplication::postEvent(m_receiver, new FPGAEvent(Decrease));
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/**
* @file ModeledReferencePR.hpp
* Class to compute modeled pseudoranges using a reference station
*/
#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Dagoberto Salazar - gAGE. 2006
//
//============================================================================
#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"
#include "TypeID.hpp"
namespace gpstk
{
/** @addtogroup GPSsolutions */
//@{
/**
* This class compute modeled pseudoranges from satellites to a reference station.
*
* @sa ModeledPseudorangeBase.hpp for base class.
*
*/
class ModeledReferencePR : public ModeledPseudorangeBase
{
public:
/// Implicit constructor
ModeledReferencePR() throw(Exception) {
InitializeValues();
};
/** Explicit constructor taking as input reference station coordinates.
*
* Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
* (Latitude, Longitude, Altitude), but defaults to Cartesian.
*
* Also, a pointer to GeoidModel may be specified, but default is NULL
* (in which case WGS84 values will be used).
*
* @param aRx first coordinate [ X(m), or latitude (degrees N) ]
* @param bRx second coordinate [ Y(m), or longitude (degrees E) ]
* @param cRx third coordinate [ Z, height above ellipsoid or radius, in m ]
* @param s coordinate system (default is Cartesian, may be set to Geodetic).
* @param geoid pointer to GeoidModel (default is null, implies WGS84)
*/
ModeledReferencePR(double aRx, double bRx, double cRx,
Position::CoordinateSystem s = Position::Cartesian,
GeoidModel *geoid = NULL) throw(Exception)
{
InitializeValues();
setInitialRxPosition(aRx, bRx, cRx, s, geoid);
};
/// Explicit constructor, taking as input a Position object containing reference station coordinates.
ModeledReferencePR(Position RxCoordinates) throw(Exception) {
InitializeValues();
setInitialRxPosition(RxCoordinates);
};
/** Explicit constructor, taking as input reference station coordinates, default
* ionospheric and tropospheric models, and default observable to be used when
* working with GNSS data structures.
*
* @param RxCoordinates Reference station coordinates.
* @param dIonoModel Ionospheric model to be used by default.
* @param dTropoModel Tropospheric model to be used by default.
* @param dObservable Observable type to be used by default.
*
* @sa DataStructures.hpp.
*/
ModeledReferencePR(Position RxCoordinates, IonoModelStore& dIonoModel, TropModel& dTropoModel, TypeID& dObservable) throw(Exception) {
InitializeValues();
setInitialRxPosition(RxCoordinates);
setDefaultIonoModel(dIonoModel);
setDefaultTropoModel(dTropoModel);
setDefaultObservable(dObservable);
};
/** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
* @param Tr Measured time of reception of the data.
* @param Satellite Vector of satellites; on successful return, satellites that
* were excluded by the algorithm are marked by a negative
* Satellite[i].prn
* @param Pseudorange Vector of raw pseudoranges (parallel to satellite), in meters.
* @param Eph EphemerisStore to be used.
* @param pTropModel Pointer to tropospheric model to be used. By default points to NULL.
* @param pIonoModel Pointer to ionospheric model to be used. By default points to NULL.
* @param extraBiases Vector of extra biases to be added to the model.
*
* @return
* Number of satellites with valid data
*
* @sa TropModel.hpp, IonoModelStore.hpp.
*/
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
*pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
*pIonoModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
throw(Exception);
/** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
* @param Tr Measured time of reception of the data.
* @param Satellite ID's of satellite
* @param Pseudorange Pseudorange (parallel to satellite), in meters.
* @param Eph EphemerisStore to be used.
* @param pTropModel Pointer to tropospheric model to be used. By default points to NULL.
* @param pIonoModel Pointer to ionospheric model to be used. By default points to NULL.
* @param extraBiases Extra bias to be added to the model.
*
* @return
* 1 if satellite has valid data
*
* @sa TropModel.hpp, IonoModelStore.hpp.
*/
int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
IonoModelStore *pIonoModel=NULL) throw(Exception);
/// Boolean variable indicating if SV instrumental delays (TGD) will be included in results. It is true by default.
bool useTGD;
/// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
double getMinElev()
{
return minElev;
};
/// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
void setMinElev(double newElevation)
{
minElev = newElevation;
};
/** Method to set the default ionospheric model.
* @param dIonoModel Ionospheric model to be used by default.
*/
void setDefaultIonoModel(IonoModelStore& dIonoModel)
{
pDefaultIonoModel = &dIonoModel;
};
/** Method to set the default tropospheric model.
* @param dTropoModel Tropospheric model to be used by default.
*/
void setDefaultTropoModel(TropModel& dTropoModel)
{
pDefaultTropoModel = &dTropoModel;
};
/** Method to set the default extra biases.
* @param eBiases Vector with the default extra biases
*/
void setDefaultExtraBiases(Vector<double>& eBiases)
{
extraBiases = eBiases;
};
/** Method to set the default observable to be used when fed with GNSS data structures.
* @param type TypeID object to be used by default
*/
virtual void setDefaultObservable(TypeID& type)
{
defaultObservable = type;
};
/// Method to get the default observable to being used with GNSS data structures.
virtual TypeID getDefaultObservable()
{
return defaultObservable;
};
/// Destructor.
virtual ~ModeledReferencePR() throw() {};
protected:
/// Pointer to default ionospheric model.
IonoModelStore *pDefaultIonoModel;
/// Pointer to default tropospheric model.
TropModel *pDefaultTropoModel;
/// Default observable to be used when fed with GNSS data structures.
TypeID defaultObservable;
/// Initialization method
void InitializeValues() throw(Exception) {
setInitialRxPosition();
geometricRho(0);
svClockBiases(0);
svXvt(0);
svTGD(0);
svRelativity(0);
ionoCorrections(0);
tropoCorrections(0);
modeledPseudoranges(0);
prefitResiduals(0);
extraBiases(0);
availableSV(0);
rejectedSV(0);
useTGD = true;
minElev = 10.0; // By default, cut-off elevation is set to 10 degrees
pDefaultIonoModel = NULL;
pDefaultTropoModel = NULL;
defaultObservable = TypeID::C1; // By default, process C1 code
};
/** Method to set the initial (a priori) position of receiver.
* @return
* 0 if OK
* -1 if problems arose
*/
int setInitialRxPosition(double aRx, double bRx, double cRx,
Position::CoordinateSystem s=Position::Cartesian,
GeoidModel *geoid=NULL) throw(GeometryException)
{
try {
Position rxpos(aRx, bRx, cRx, s, geoid);
setInitialRxPosition(rxpos);
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to set the initial (a priori) position of receiver.
int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
{
try {
rxPos = RxCoordinates;
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to set the initial (a priori) position of receiver.
int setInitialRxPosition() throw(GeometryException)
{
try {
rxPos.setECEF(0.0, 0.0, 0.0);
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to get the tropospheric corrections.
double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
{
double tropoCorr = 0.0;
try {
tropoCorr = pTropModel->correction(elevation);
// Check validity
if(!(pTropModel->isValid())) tropoCorr = 0.0;
}
catch(TropModel::InvalidTropModel& e) {
tropoCorr = 0.0;
}
return tropoCorr;
};
/// Method to get the ionospheric corrections.
double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
{
double ionoCorr = 0.0;
try {
ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
}
catch(IonoModelStore::NoIonoModelFound& e) {
ionoCorr = 0.0;
}
return ionoCorr;
};
/// Method to get TGD corrections.
double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
{
double TGDCorr = 0.0;
try {
TGDCorr = (Eph.getTGD(sat, Tr));
}
catch(EphemerisStore::NoTGDFound& e) {
TGDCorr = 0.0;
}
return TGDCorr;
};
}; // class ModeledReferencePR
//@}
} // namespace
#endif
<commit_msg>Added member pDefaultEphemeris associated methods.<commit_after>/**
* @file ModeledReferencePR.hpp
* Class to compute modeled pseudoranges using a reference station
*/
#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Dagoberto Salazar - gAGE. 2006
//
//============================================================================
#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"
#include "TypeID.hpp"
namespace gpstk
{
/** @addtogroup GPSsolutions */
//@{
/**
* This class compute modeled pseudoranges from satellites to a reference station.
*
* @sa ModeledPseudorangeBase.hpp for base class.
*
*/
class ModeledReferencePR : public ModeledPseudorangeBase
{
public:
/// Implicit constructor
ModeledReferencePR() throw(Exception) {
InitializeValues();
};
/** Explicit constructor taking as input reference station coordinates.
*
* Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
* (Latitude, Longitude, Altitude), but defaults to Cartesian.
*
* Also, a pointer to GeoidModel may be specified, but default is NULL
* (in which case WGS84 values will be used).
*
* @param aRx first coordinate [ X(m), or latitude (degrees N) ]
* @param bRx second coordinate [ Y(m), or longitude (degrees E) ]
* @param cRx third coordinate [ Z, height above ellipsoid or radius, in m ]
* @param s coordinate system (default is Cartesian, may be set to Geodetic).
* @param geoid pointer to GeoidModel (default is null, implies WGS84)
*/
ModeledReferencePR(double aRx, double bRx, double cRx,
Position::CoordinateSystem s = Position::Cartesian,
GeoidModel *geoid = NULL) throw(Exception)
{
InitializeValues();
setInitialRxPosition(aRx, bRx, cRx, s, geoid);
};
/// Explicit constructor, taking as input a Position object containing reference station coordinates.
ModeledReferencePR(Position RxCoordinates) throw(Exception) {
InitializeValues();
setInitialRxPosition(RxCoordinates);
};
/** Explicit constructor, taking as input reference station coordinates, default
* ionospheric and tropospheric models, and default observable.
* This constructor is meant to be used when working with GNSS data structures in
* order to set the basic parameters from the beginning.
*
* @param RxCoordinates Reference station coordinates.
* @param dIonoModel Ionospheric model to be used by default.
* @param dTropoModel Tropospheric model to be used by default.
* @param dObservable Observable type to be used by default.
* @param dEphemeris EphemerisStore object to be used by default.
* @param usetgd Whether TGD will be used by default or not.
*
* @sa DataStructures.hpp.
*/
ModeledReferencePR(Position RxCoordinates, IonoModelStore& dIonoModel, TropModel& dTropoModel, EphemerisStore& dEphemeris, TypeID& dObservable, bool usetgd = true) throw(Exception) {
InitializeValues();
setInitialRxPosition(RxCoordinates);
setDefaultIonoModel(dIonoModel);
setDefaultTropoModel(dTropoModel);
setDefaultObservable(dObservable);
setDefaultEphemeris(dEphemeris);
useTGD = usetgd;
};
/** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
* @param Tr Measured time of reception of the data.
* @param Satellite Vector of satellites; on successful return, satellites that
* were excluded by the algorithm are marked by a negative
* Satellite[i].prn
* @param Pseudorange Vector of raw pseudoranges (parallel to satellite), in meters.
* @param Eph EphemerisStore to be used.
* @param pTropModel Pointer to tropospheric model to be used. By default points to NULL.
* @param pIonoModel Pointer to ionospheric model to be used. By default points to NULL.
* @param extraBiases Vector of extra biases to be added to the model.
*
* @return
* Number of satellites with valid data
*
* @sa TropModel.hpp, IonoModelStore.hpp.
*/
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
*pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
*pIonoModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);
/// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
throw(Exception);
/** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
* @param Tr Measured time of reception of the data.
* @param Satellite ID's of satellite
* @param Pseudorange Pseudorange (parallel to satellite), in meters.
* @param Eph EphemerisStore to be used.
* @param pTropModel Pointer to tropospheric model to be used. By default points to NULL.
* @param pIonoModel Pointer to ionospheric model to be used. By default points to NULL.
* @param extraBiases Extra bias to be added to the model.
*
* @return
* 1 if satellite has valid data
*
* @sa TropModel.hpp, IonoModelStore.hpp.
*/
int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
IonoModelStore *pIonoModel=NULL) throw(Exception);
/// Boolean variable indicating if SV instrumental delays (TGD) will be included in results. It is true by default.
bool useTGD;
/// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
double getMinElev()
{
return minElev;
};
/// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
void setMinElev(double newElevation)
{
minElev = newElevation;
};
/** Method to set the default ionospheric model.
* @param dIonoModel Ionospheric model to be used by default.
*/
void setDefaultIonoModel(IonoModelStore& dIonoModel)
{
pDefaultIonoModel = &dIonoModel;
};
/** Method to set the default tropospheric model.
* @param dTropoModel Tropospheric model to be used by default.
*/
void setDefaultTropoModel(TropModel& dTropoModel)
{
pDefaultTropoModel = &dTropoModel;
};
/** Method to set the default extra biases.
* @param eBiases Vector with the default extra biases
*/
void setDefaultExtraBiases(Vector<double>& eBiases)
{
extraBiases = eBiases;
};
/** Method to set the default observable to be used when fed with GNSS data structures.
* @param type TypeID object to be used by default
*/
virtual void setDefaultObservable(TypeID& type)
{
defaultObservable = type;
};
/// Method to get the default observable being used with GNSS data structures.
virtual TypeID getDefaultObservable()
{
return defaultObservable;
};
/** Method to set the default EphemerisStore to be used with GNSS data structures.
* @param ephem EphemerisStore object to be used by default
*/
virtual void setDefaultEphemeris(EphemerisStore& ephem)
{
pDefaultEphemeris = &ephem;
};
/// Destructor.
virtual ~ModeledReferencePR() throw() {};
protected:
/// Pointer to default ionospheric model.
IonoModelStore *pDefaultIonoModel;
/// Pointer to default tropospheric model.
TropModel *pDefaultTropoModel;
/// Default observable to be used when fed with GNSS data structures.
TypeID defaultObservable;
/// Pointer to default EphemerisStore object when working with GNSS data structures.
EphemerisStore* pDefaultEphemeris;
/// Initialization method
void InitializeValues() throw(Exception) {
setInitialRxPosition();
geometricRho(0);
svClockBiases(0);
svXvt(0);
svTGD(0);
svRelativity(0);
ionoCorrections(0);
tropoCorrections(0);
modeledPseudoranges(0);
prefitResiduals(0);
extraBiases(0);
availableSV(0);
rejectedSV(0);
useTGD = true;
minElev = 10.0; // By default, cut-off elevation is set to 10 degrees
pDefaultIonoModel = NULL;
pDefaultTropoModel = NULL;
defaultObservable = TypeID::C1; // By default, process C1 code
pDefaultEphemeris = NULL;
};
/** Method to set the initial (a priori) position of receiver.
* @return
* 0 if OK
* -1 if problems arose
*/
int setInitialRxPosition(double aRx, double bRx, double cRx,
Position::CoordinateSystem s=Position::Cartesian,
GeoidModel *geoid=NULL) throw(GeometryException)
{
try {
Position rxpos(aRx, bRx, cRx, s, geoid);
setInitialRxPosition(rxpos);
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to set the initial (a priori) position of receiver.
int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
{
try {
rxPos = RxCoordinates;
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to set the initial (a priori) position of receiver.
int setInitialRxPosition() throw(GeometryException)
{
try {
rxPos.setECEF(0.0, 0.0, 0.0);
return 0;
}
catch(GeometryException& e) {
return -1;
}
};
/// Method to get the tropospheric corrections.
double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
{
double tropoCorr = 0.0;
try {
tropoCorr = pTropModel->correction(elevation);
// Check validity
if(!(pTropModel->isValid())) tropoCorr = 0.0;
}
catch(TropModel::InvalidTropModel& e) {
tropoCorr = 0.0;
}
return tropoCorr;
};
/// Method to get the ionospheric corrections.
double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
{
double ionoCorr = 0.0;
try {
ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
}
catch(IonoModelStore::NoIonoModelFound& e) {
ionoCorr = 0.0;
}
return ionoCorr;
};
/// Method to get TGD corrections.
double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
{
double TGDCorr = 0.0;
try {
TGDCorr = (Eph.getTGD(sat, Tr));
}
catch(EphemerisStore::NoTGDFound& e) {
TGDCorr = 0.0;
}
return TGDCorr;
};
}; // class ModeledReferencePR
//@}
} // namespace
#endif
<|endoftext|> |
<commit_before>
#include <Onsang/asio.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/init.hpp>
#include <Onsang/Client/Unit.hpp>
#include <duct/debug.hpp>
#include <duct/Args.hpp>
#include <duct/ScriptParser.hpp>
#include <duct/ScriptWriter.hpp>
#include <Beard/tty/Defs.hpp>
#include <Beard/tty/Ops.hpp>
#include <Beard/tty/Terminal.hpp>
#include <Beard/tty/TerminalInfo.hpp>
#include <Beard/txt/Defs.hpp>
#include <Beard/ui/Defs.hpp>
#include <Beard/ui/Root.hpp>
#include <Beard/ui/Context.hpp>
namespace Onsang {
namespace Client {
// class Unit implementation
void
Unit::add_session(
String name,
String type,
String addr
) {
Log::acquire(Log::debug)
<< "Adding session '"
<< name
<< "': '"
<< type
<< "' @ '"
<< addr
<< "'\n"
;
/*auto const ds_pair = m_driver.placehold_hive(
CacheDatastore::s_type_info,
std::move(address)
);
// TODO: Read protocol from address string
m_sessions.emplace_back(
Hord::System::Context{
Hord::System::Context::Type::client,
m_driver,
ds_pair.hive.get_id()
},
Net::Socket{
m_io_service,
Net::StreamProtocol{asio::tcp::v4()}
}
);*/
}
bool
Unit::init(
signed const argc,
char* argv[]
) {
duct::Var opt;
duct::Args::parse_raw(argc, argv, opt);
// Import requires a node
opt.morph(duct::VarType::node, false);
{
auto log = Log::acquire(Log::debug);
duct::ScriptWriter writer{enum_combine(
duct::ScriptWriter::Flags::defaults,
duct::ScriptWriter::Flags::quote
)};
log << "Arguments:\n";
DUCT_ASSERTE(writer.write(log, opt, true, 1u));
log << "\n";
}
// Leak exceptions to caller
m_args.import(opt);
// Set the log file before validation
auto const& arg_log = m_args.entry("--log");
if (arg_log.assigned()) {
if (arg_log.value.is_null()) {
Log::get_controller().file(false);
} else {
Log::get_controller().set_file_path(
arg_log.value.get_as_str()
);
Log::get_controller().file(true);
}
}
// Check for missing arguments
auto vinfo = m_args.validate();
if (!vinfo.valid) {
Log::acquire(Log::error)
<< "Invalid arguments\n"
;
if (vinfo.has_iter) {
Log::acquire(Log::error)
<< "Missing option: "
<< vinfo.iter->first
<< '\n'
;
}
return false;
}
if (m_args.entry("--no-auto").assigned()) {
m_flags.enable(Flags::no_auto_connect);
}
// Load config
auto const& arg_config = m_args.entry("--config");
auto const cfg_path = arg_config.value.get_as_str();
Log::acquire()
<< "Loading config from '"
<< cfg_path
<< "'\n"
;
duct::Var cfg_root{duct::VarType::node};
std::ifstream stream{cfg_path};
if (stream.is_open()) {
duct::ScriptParser parser{
{duct::Encoding::UTF8, duct::Endian::system}
};
try {
parser.process(cfg_root, stream);
stream.close();
} catch (std::exception& err) {
Log::acquire(Log::error)
<< "Failed to parse config file '"
<< cfg_path
<< "':\n"
<< Log::Pre::current
<< err.what()
<< '\n'
;
return false;
}
} else {
Log::acquire(Log::error)
<< "Failed to open config file '"
<< cfg_path
<< "'\n"
;
return false;
}
// Import and validate config
// Leak import exceptions to caller
m_config.import(cfg_root);
auto const& cfg_sessions = m_config.node("sessions");
auto const& cfg_sessions_builder = cfg_sessions.entry("builder");
vinfo = m_config.validate();
if (!vinfo.valid) {
Log::acquire(Log::error)
<< "Invalid config\n"
;
if (vinfo.has_iter) {
if (&vinfo.iter->second == &cfg_sessions_builder) {
Log::acquire(Log::error)
<< "No sessions supplied\n"
;
} else {
Log::acquire(Log::error)
<< "Missing required value '"
<< vinfo.iter->first
<< "' in node '"
<< vinfo.node
<< "'\n"
;
}
} else {
Log::acquire(Log::error)
<< "Missing required node '"
<< vinfo.node
<< "'\n"
;
}
return false;
}
// Use log path in config file unless --log was provided
if (!arg_log.assigned()) {
auto const& cfg_log_path = m_config.node("log").entry("path");
if (cfg_log_path.assigned()) {
if (cfg_log_path.value.is_null()) {
Log::get_controller().file(false);
} else {
Log::get_controller().set_file_path(
cfg_log_path.value.get_string_ref()
);
Log::get_controller().file(true);
}
}
}
// Load terminfo
auto const& cfg_term_info = m_config.node("term").entry("info");
auto const& terminfo_path = cfg_term_info.value.get_string_ref();
Log::acquire()
<< "Loading terminfo from '"
<< terminfo_path
<< "'\n"
;
stream.open(terminfo_path);
if (stream.is_open()) {
try {
m_ui_ctx.get_terminal().get_info().deserialize(stream);
stream.close();
} catch (Beard::Error& err) {
Log::acquire(Log::error)
<< "Failed to parse terminfo file '"
<< terminfo_path
<< "':\n"
;
report_error(err);
return false;
}
} else {
Log::acquire(Log::error)
<< "Failed to open terminfo file '"
<< terminfo_path
<< "'\n"
;
return false;
}
// Update terminal cap cache
m_ui_ctx.get_terminal().update_cache();
// Initialize driver
driver_init(m_driver);
// Add sessions
Log::acquire()
<< "Creating sessions\n"
;
for (auto const& spair : cfg_sessions.node_proxy()) {
auto const session = spair.second;
if (!session.built()) {
continue;
}
add_session(
spair.first,
session.entry("type").value.get_string_ref(),
session.entry("addr").value.get_string_ref()
);
}
return true;
}
void
Unit::start() try {
Log::acquire()
<< "Opening UI context\n"
;
m_ui_ctx.open(Beard::tty::this_path(), true);
auto root = Beard::ui::Root::make(m_ui_ctx, Beard::Axis::horizontal);
m_ui_ctx.set_root(root);
// The terminal will get all screwy if we don't disable stdout
Log::acquire()
<< "Disabling stdout\n"
;
Log::get_controller().stdout(false);
// Event loop
m_ui_ctx.render(true);
while (!m_ui_ctx.update(10u)) {
// TODO: process data from sessions, handle global hotkeys
}
m_ui_ctx.close();
Log::get_controller().stdout(true);
Log::acquire()
<< "Re-enabled stdout\n"
;
} catch (...) {
Log::get_controller().stdout(true);
Log::acquire()
<< "Re-enabled stdout\n"
;
throw;
}
} // namespace Client
} // namespace Onsang
<commit_msg>Client::Unit: only re-enable stdout if it's not already enabled.¹<commit_after>
#include <Onsang/asio.hpp>
#include <Onsang/Log.hpp>
#include <Onsang/init.hpp>
#include <Onsang/Client/Unit.hpp>
#include <duct/debug.hpp>
#include <duct/Args.hpp>
#include <duct/ScriptParser.hpp>
#include <duct/ScriptWriter.hpp>
#include <Beard/tty/Defs.hpp>
#include <Beard/tty/Ops.hpp>
#include <Beard/tty/Terminal.hpp>
#include <Beard/tty/TerminalInfo.hpp>
#include <Beard/txt/Defs.hpp>
#include <Beard/ui/Defs.hpp>
#include <Beard/ui/Root.hpp>
#include <Beard/ui/Context.hpp>
namespace Onsang {
namespace Client {
// class Unit implementation
void
Unit::add_session(
String name,
String type,
String addr
) {
Log::acquire(Log::debug)
<< "Adding session '"
<< name
<< "': '"
<< type
<< "' @ '"
<< addr
<< "'\n"
;
/*auto const ds_pair = m_driver.placehold_hive(
CacheDatastore::s_type_info,
std::move(address)
);
// TODO: Read protocol from address string
m_sessions.emplace_back(
Hord::System::Context{
Hord::System::Context::Type::client,
m_driver,
ds_pair.hive.get_id()
},
Net::Socket{
m_io_service,
Net::StreamProtocol{asio::tcp::v4()}
}
);*/
}
bool
Unit::init(
signed const argc,
char* argv[]
) {
duct::Var opt;
duct::Args::parse_raw(argc, argv, opt);
// Import requires a node
opt.morph(duct::VarType::node, false);
{
auto log = Log::acquire(Log::debug);
duct::ScriptWriter writer{enum_combine(
duct::ScriptWriter::Flags::defaults,
duct::ScriptWriter::Flags::quote
)};
log << "Arguments:\n";
DUCT_ASSERTE(writer.write(log, opt, true, 1u));
log << "\n";
}
// Leak exceptions to caller
m_args.import(opt);
// Set the log file before validation
auto const& arg_log = m_args.entry("--log");
if (arg_log.assigned()) {
if (arg_log.value.is_null()) {
Log::get_controller().file(false);
} else {
Log::get_controller().set_file_path(
arg_log.value.get_as_str()
);
Log::get_controller().file(true);
}
}
// Check for missing arguments
auto vinfo = m_args.validate();
if (!vinfo.valid) {
Log::acquire(Log::error)
<< "Invalid arguments\n"
;
if (vinfo.has_iter) {
Log::acquire(Log::error)
<< "Missing option: "
<< vinfo.iter->first
<< '\n'
;
}
return false;
}
if (m_args.entry("--no-auto").assigned()) {
m_flags.enable(Flags::no_auto_connect);
}
// Load config
auto const& arg_config = m_args.entry("--config");
auto const cfg_path = arg_config.value.get_as_str();
Log::acquire()
<< "Loading config from '"
<< cfg_path
<< "'\n"
;
duct::Var cfg_root{duct::VarType::node};
std::ifstream stream{cfg_path};
if (stream.is_open()) {
duct::ScriptParser parser{
{duct::Encoding::UTF8, duct::Endian::system}
};
try {
parser.process(cfg_root, stream);
stream.close();
} catch (std::exception& err) {
Log::acquire(Log::error)
<< "Failed to parse config file '"
<< cfg_path
<< "':\n"
<< Log::Pre::current
<< err.what()
<< '\n'
;
return false;
}
} else {
Log::acquire(Log::error)
<< "Failed to open config file '"
<< cfg_path
<< "'\n"
;
return false;
}
// Import and validate config
// Leak import exceptions to caller
m_config.import(cfg_root);
auto const& cfg_sessions = m_config.node("sessions");
auto const& cfg_sessions_builder = cfg_sessions.entry("builder");
vinfo = m_config.validate();
if (!vinfo.valid) {
Log::acquire(Log::error)
<< "Invalid config\n"
;
if (vinfo.has_iter) {
if (&vinfo.iter->second == &cfg_sessions_builder) {
Log::acquire(Log::error)
<< "No sessions supplied\n"
;
} else {
Log::acquire(Log::error)
<< "Missing required value '"
<< vinfo.iter->first
<< "' in node '"
<< vinfo.node
<< "'\n"
;
}
} else {
Log::acquire(Log::error)
<< "Missing required node '"
<< vinfo.node
<< "'\n"
;
}
return false;
}
// Use log path in config file unless --log was provided
if (!arg_log.assigned()) {
auto const& cfg_log_path = m_config.node("log").entry("path");
if (cfg_log_path.assigned()) {
if (cfg_log_path.value.is_null()) {
Log::get_controller().file(false);
} else {
Log::get_controller().set_file_path(
cfg_log_path.value.get_string_ref()
);
Log::get_controller().file(true);
}
}
}
// Load terminfo
auto const& cfg_term_info = m_config.node("term").entry("info");
auto const& terminfo_path = cfg_term_info.value.get_string_ref();
Log::acquire()
<< "Loading terminfo from '"
<< terminfo_path
<< "'\n"
;
stream.open(terminfo_path);
if (stream.is_open()) {
try {
m_ui_ctx.get_terminal().get_info().deserialize(stream);
stream.close();
} catch (Beard::Error& err) {
Log::acquire(Log::error)
<< "Failed to parse terminfo file '"
<< terminfo_path
<< "':\n"
;
report_error(err);
return false;
}
} else {
Log::acquire(Log::error)
<< "Failed to open terminfo file '"
<< terminfo_path
<< "'\n"
;
return false;
}
// Update terminal cap cache
m_ui_ctx.get_terminal().update_cache();
// Initialize driver
driver_init(m_driver);
// Add sessions
Log::acquire()
<< "Creating sessions\n"
;
for (auto const& spair : cfg_sessions.node_proxy()) {
auto const session = spair.second;
if (!session.built()) {
continue;
}
add_session(
spair.first,
session.entry("type").value.get_string_ref(),
session.entry("addr").value.get_string_ref()
);
}
return true;
}
void
Unit::start() try {
Log::acquire()
<< "Opening UI context\n"
;
m_ui_ctx.open(Beard::tty::this_path(), true);
auto root = Beard::ui::Root::make(m_ui_ctx, Beard::Axis::horizontal);
m_ui_ctx.set_root(root);
// The terminal will get all screwy if we don't disable stdout
Log::acquire()
<< "Disabling stdout\n"
;
Log::get_controller().stdout(false);
// Event loop
m_ui_ctx.render(true);
while (!m_ui_ctx.update(10u)) {
// TODO: process data from sessions, handle global hotkeys
}
m_ui_ctx.close();
Log::get_controller().stdout(true);
Log::acquire()
<< "Re-enabled stdout\n"
;
} catch (...) {
// TODO: Terminate UI?
if (!Log::get_controller().stdout_enabled()) {
Log::get_controller().stdout(true);
Log::acquire()
<< "Re-enabled stdout\n"
;
}
throw;
}
} // namespace Client
} // namespace Onsang
<|endoftext|> |
<commit_before>#include "OverworldGameState.h"
#include "irrlicht.h"
#include "ChunkNode.h"
#include "Chunk.h"
#include <iostream>
using namespace irr;
OverworldGameState::OverworldGameState(irr::IrrlichtDevice *irrlicht)
: GameState::GameState(irrlicht) {
device = irrlicht;
driver = irrlicht->getVideoDriver();
smgr = irrlicht->getSceneManager();
systemMgr = entityWorld.getSystemManager();
entityMgr = entityWorld.getEntityManager();
}
void OverworldGameState::init() {
physSys = (PhysicsSystem*) systemMgr->setSystem(new PhysicsSystem());
systemMgr->initializeAll();
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
smgr->addSkyBoxSceneNode(
driver->getTexture("example_media/irrlicht2_up.jpg"),
driver->getTexture("example_media/irrlicht2_dn.jpg"),
driver->getTexture("example_media/irrlicht2_lf.jpg"),
driver->getTexture("example_media/irrlicht2_rt.jpg"),
driver->getTexture("example_media/irrlicht2_ft.jpg"),
driver->getTexture("example_media/irrlicht2_bk.jpg"));
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true);
// Add the camera
cam = smgr->addCameraSceneNode();
cam->setPosition(core::vector3df(0, 2, -4));
cam->setTarget(core::vector3df(0, 0, 0));
// Make the test chunk
ChunkMap* test = new ChunkMap(5, 5);
chunkNode = new ChunkNode(test->getChunk(0, 0), smgr->getRootSceneNode(), smgr, 1337);
scene::IMesh* cube = smgr->getMesh("assets/unit_cube.dae");
scene::IMeshSceneNode* node = smgr->addMeshSceneNode(cube);
node->setMaterialFlag(video::EMF_LIGHTING, false);
artemis::Entity* foo = &(entityMgr->create());
player = new Player(foo, node);
}
void OverworldGameState::cleanup() {
chunkNode->drop();
chunkNode = 0;
}
void OverworldGameState::pause()
{
}
void OverworldGameState::resume()
{
}
void OverworldGameState::update(irr::f32 tpf) {
entityWorld.loopStart();
entityWorld.setDelta(tpf);
physSys->process();
std::cout << player->physics->x << std::endl;
}
void OverworldGameState::render() {
smgr->drawAll();
}
<commit_msg>A-okay<commit_after>#include "OverworldGameState.h"
#include "irrlicht.h"
#include "ChunkNode.h"
#include "Chunk.h"
#include <iostream>
using namespace irr;
OverworldGameState::OverworldGameState(irr::IrrlichtDevice *irrlicht)
: GameState::GameState(irrlicht) {
device = irrlicht;
driver = irrlicht->getVideoDriver();
smgr = irrlicht->getSceneManager();
systemMgr = entityWorld.getSystemManager();
entityMgr = entityWorld.getEntityManager();
}
void OverworldGameState::init() {
physSys = (PhysicsSystem*) systemMgr->setSystem(new PhysicsSystem());
systemMgr->initializeAll();
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
smgr->addSkyBoxSceneNode(
driver->getTexture("example_media/irrlicht2_up.jpg"),
driver->getTexture("example_media/irrlicht2_dn.jpg"),
driver->getTexture("example_media/irrlicht2_lf.jpg"),
driver->getTexture("example_media/irrlicht2_rt.jpg"),
driver->getTexture("example_media/irrlicht2_ft.jpg"),
driver->getTexture("example_media/irrlicht2_bk.jpg"));
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true);
// Add the camera
cam = smgr->addCameraSceneNode();
cam->setPosition(core::vector3df(0, 2, -4));
cam->setTarget(core::vector3df(0, 0, 0));
// Make the test chunk
ChunkMap* test = new ChunkMap(5, 5);
chunkNode = new ChunkNode(test->getChunk(0, 0), smgr->getRootSceneNode(), smgr, 1337);
scene::IMesh* cube = smgr->getMesh("assets/unit_cube.dae");
scene::IMeshSceneNode* node = smgr->addMeshSceneNode(cube);
node->setMaterialFlag(video::EMF_LIGHTING, false);
artemis::Entity* foo = &(entityMgr->create());
player = new Player(foo, node);
}
void OverworldGameState::cleanup() {
chunkNode->drop();
chunkNode = 0;
}
void OverworldGameState::pause()
{
}
void OverworldGameState::resume()
{
}
void OverworldGameState::update(irr::f32 tpf) {
entityWorld.loopStart();
entityWorld.setDelta(tpf);
physSys->process();
cam->setPosition(core::vector3df(player->physics->x, 2, player->physics->z -4));
cam->setTarget(core::vector3df(player->physics->x, 0, player->physics->z));
}
void OverworldGameState::render() {
smgr->drawAll();
}
<|endoftext|> |
<commit_before>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Exceptions/Checkmate_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
int Genetic_AI::next_id = 0;
Genetic_AI::Genetic_AI() :
genome(),
id(next_id++)
{
}
// Sexual reproduction
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
genome(A.genome, B.genome),
id(next_id++)
{
}
Genetic_AI::~Genetic_AI()
{
}
Genetic_AI::Genetic_AI(const std::string& file_name)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw std::runtime_error("Could not read: " + file_name);
}
read_from(ifs);
}
Genetic_AI::Genetic_AI(std::istream& is)
{
read_from(is);
}
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)
{
if(id >= next_id)
{
next_id = id + 1;
}
std::ifstream ifs(file_name);
if( ! ifs)
{
throw std::runtime_error("Could not read: " + file_name);
}
std::string line;
while(std::getline(ifs, line))
{
if( ! String::starts_with(line, "ID:"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(id_in == std::stoi(param_value[1]))
{
genome.read_from(ifs);
return;
}
}
throw std::runtime_error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}
void Genetic_AI::read_from(std::istream& is)
{
std::string line;
id = -1;
while(std::getline(is, line))
{
if(line.empty())
{
continue;
}
if(String::starts_with(line, "ID:"))
{
id = std::stoi(String::split(line)[1]);
break;
}
else
{
throw std::runtime_error("Invalid Genetic_AI line: " + line);
}
}
if( ! is)
{
throw std::runtime_error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id));
}
if(id >= next_id)
{
next_id = id + 1;
}
genome.read_from(is);
}
const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const
{
const auto& legal_moves = board.all_legal_moves();
if(legal_moves.size() == 1)
{
return legal_moves.front(); // If there's only one legal move, take it.
}
auto time_to_use = genome.time_to_examine(board, clock);
Game_Tree_Node_Result alpha_start = {Complete_Move(),
Math::lose_score,
board.whose_turn(),
0,
""};
Game_Tree_Node_Result beta_start = {Complete_Move(),
Math::win_score,
board.whose_turn(),
0,
""};
auto result = search_game_tree(board,
time_to_use,
clock,
0,
alpha_start,
beta_start);
if(result.depth > 0)
{
board.add_commentary_to_next_move(result.commentary);
principal_variation = String::split(result.commentary);
for(auto& move : principal_variation)
{
// remove non-move notation
move = String::strip_comments(move, '+');
move = String::strip_comments(move, '#');
}
}
else
{
principal_variation.clear();
}
return result.move;
}
bool better_than(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b, Color perspective)
{
auto scoreA = a.corrected_score(perspective);
auto scoreB = b.corrected_score(perspective);
if(scoreA > scoreB)
{
return true;
}
if(scoreA < scoreB)
{
return false;
}
// scoreA == scoreB
// Shorter path to winning is better
if(scoreA == Math::win_score)
{
return a.depth < b.depth;
}
// Longer path to losing is better
if(scoreA == Math::lose_score)
{
return a.depth > b.depth;
}
return false;
}
bool operator==(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b)
{
auto scoreA = a.corrected_score(WHITE);
auto scoreB = b.corrected_score(WHITE);
if(scoreA != scoreB)
{
return false;
}
// scoreA == scoreB
if(std::abs(scoreA) == Math::win_score)
{
return a.depth == b.depth;
}
return true;
}
Game_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,
const double time_to_examine,
const Clock& clock,
const size_t depth,
Game_Tree_Node_Result alpha,
Game_Tree_Node_Result beta) const
{
auto perspective = board.whose_turn();
auto time_start = clock.time_left(clock.running_for());
int moves_examined = 0;
Game_Tree_Node_Result best_result = {board.all_legal_moves().front(),
Math::lose_score,
perspective,
depth,
""};
auto all_legal_moves = board.all_legal_moves();
const auto current_legal_moves_count = all_legal_moves.size();
// The first item in the principal variation is the last move that
// this player made. Since then, the opponent has also made a move,
// so the first item in the principal variation corresponds to the
// game record item at game_record.size() - 2. The depth of the game
// tree search increments both the game_record index and the principal
// variation index in step.
bool still_on_principal_variation = false;
if(principal_variation.size() > depth + 2)
{
auto principal_variation_start_index = board.get_game_record().size() - depth - 2;
still_on_principal_variation = std::equal(board.get_game_record().begin() + principal_variation_start_index,
board.get_game_record().end(),
principal_variation.begin());
if(still_on_principal_variation)
{
auto next_principal_variation_move = principal_variation[depth + 2];
auto move_iter = std::find_if(all_legal_moves.begin(),
all_legal_moves.end(),
[&next_principal_variation_move, &board](const auto& cm)
{
return cm.game_record_item(board) == next_principal_variation_move;
});
// Put principal variation move at start of list to allow
// the most pruning later.
std::iter_swap(all_legal_moves.begin(), move_iter);
}
}
for(const auto& move : all_legal_moves)
{
auto next_board = board;
try
{
next_board.submit_move(move);
}
catch(const Checkmate_Exception&)
{
// Mate in one (try to pick the shortest path to checkmate)
auto score = genome.evaluate(next_board, perspective);
auto comment = next_board.get_game_record().back();
return {move,
score,
perspective,
depth,
comment};
}
catch(const Game_Ending_Exception&)
{
// Draws get scored like any other board position
}
Game_Tree_Node_Result result;
int moves_left = current_legal_moves_count - moves_examined;
double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));
double time_alloted_for_this_move = time_left/moves_left;
bool recurse;
if(next_board.game_has_ended())
{
recurse = false;
}
else if(next_board.all_legal_moves().size() == 1)
{
recurse = true;
}
else if(still_on_principal_variation)
{
recurse = true;
}
else if(time_alloted_for_this_move < genome.minimum_time_to_recurse(next_board))
{
recurse = false;
}
else
{
recurse = genome.good_enough_to_examine(board, next_board, perspective);
}
if(recurse)
{
result = search_game_tree(next_board,
time_alloted_for_this_move,
clock,
depth + 1,
beta,
alpha);
// Update last result with this game tree node's data
result.move = move;
result.commentary = next_board.get_game_record().back()
+ " "
+ result.commentary;
}
else
{
// Record immediate result without looking ahead further
result = {move,
genome.evaluate(next_board, perspective),
perspective,
depth,
next_board.get_game_record().back()};
}
if(better_than(result, best_result, perspective))
{
best_result = result;
if(better_than(best_result, alpha, perspective))
{
alpha = best_result;
if(better_than(alpha, beta, perspective) || alpha == beta)
{
break;
}
}
}
++moves_examined;
still_on_principal_variation = false; // only the first move is part of the principal variation
}
return best_result;
}
void Genetic_AI::mutate()
{
genome.mutate();
}
void Genetic_AI::print_genome(const std::string& file_name) const
{
if(file_name.empty())
{
print_genome(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print_genome(dest);
}
}
void Genetic_AI::print_genome(std::ostream& os) const
{
os << "ID: " << get_id() << std::endl;
genome.print(os);
os << "END" << std::endl << std::endl;
}
std::string Genetic_AI::name() const
{
return "Genetic AI " + std::to_string(get_id());
}
std::string Genetic_AI::author() const
{
return "Mark Harrison";
}
int Genetic_AI::get_id() const
{
return id;
}
bool Genetic_AI::operator<(const Genetic_AI& other) const
{
return get_id() < other.get_id();
}
bool Genetic_AI::operator==(const Genetic_AI& other) const
{
return get_id() == other.get_id();
}
<commit_msg>Prevent reading past end of principal variation after forced move<commit_after>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Exceptions/Checkmate_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
int Genetic_AI::next_id = 0;
Genetic_AI::Genetic_AI() :
genome(),
id(next_id++)
{
}
// Sexual reproduction
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
genome(A.genome, B.genome),
id(next_id++)
{
}
Genetic_AI::~Genetic_AI()
{
}
Genetic_AI::Genetic_AI(const std::string& file_name)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw std::runtime_error("Could not read: " + file_name);
}
read_from(ifs);
}
Genetic_AI::Genetic_AI(std::istream& is)
{
read_from(is);
}
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)
{
if(id >= next_id)
{
next_id = id + 1;
}
std::ifstream ifs(file_name);
if( ! ifs)
{
throw std::runtime_error("Could not read: " + file_name);
}
std::string line;
while(std::getline(ifs, line))
{
if( ! String::starts_with(line, "ID:"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(id_in == std::stoi(param_value[1]))
{
genome.read_from(ifs);
return;
}
}
throw std::runtime_error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}
void Genetic_AI::read_from(std::istream& is)
{
std::string line;
id = -1;
while(std::getline(is, line))
{
if(line.empty())
{
continue;
}
if(String::starts_with(line, "ID:"))
{
id = std::stoi(String::split(line)[1]);
break;
}
else
{
throw std::runtime_error("Invalid Genetic_AI line: " + line);
}
}
if( ! is)
{
throw std::runtime_error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id));
}
if(id >= next_id)
{
next_id = id + 1;
}
genome.read_from(is);
}
const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const
{
const auto& legal_moves = board.all_legal_moves();
if(legal_moves.size() == 1)
{
principal_variation.clear();
return legal_moves.front(); // If there's only one legal move, take it.
}
auto time_to_use = genome.time_to_examine(board, clock);
Game_Tree_Node_Result alpha_start = {Complete_Move(),
Math::lose_score,
board.whose_turn(),
0,
""};
Game_Tree_Node_Result beta_start = {Complete_Move(),
Math::win_score,
board.whose_turn(),
0,
""};
auto result = search_game_tree(board,
time_to_use,
clock,
0,
alpha_start,
beta_start);
if(result.depth > 0)
{
board.add_commentary_to_next_move(result.commentary);
principal_variation = String::split(result.commentary);
for(auto& move : principal_variation)
{
// remove non-move notation
move = String::strip_comments(move, '+');
move = String::strip_comments(move, '#');
}
}
else
{
principal_variation.clear();
}
return result.move;
}
bool better_than(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b, Color perspective)
{
auto scoreA = a.corrected_score(perspective);
auto scoreB = b.corrected_score(perspective);
if(scoreA > scoreB)
{
return true;
}
if(scoreA < scoreB)
{
return false;
}
// scoreA == scoreB
// Shorter path to winning is better
if(scoreA == Math::win_score)
{
return a.depth < b.depth;
}
// Longer path to losing is better
if(scoreA == Math::lose_score)
{
return a.depth > b.depth;
}
return false;
}
bool operator==(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b)
{
auto scoreA = a.corrected_score(WHITE);
auto scoreB = b.corrected_score(WHITE);
if(scoreA != scoreB)
{
return false;
}
// scoreA == scoreB
if(std::abs(scoreA) == Math::win_score)
{
return a.depth == b.depth;
}
return true;
}
Game_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,
const double time_to_examine,
const Clock& clock,
const size_t depth,
Game_Tree_Node_Result alpha,
Game_Tree_Node_Result beta) const
{
auto perspective = board.whose_turn();
auto time_start = clock.time_left(clock.running_for());
int moves_examined = 0;
Game_Tree_Node_Result best_result = {board.all_legal_moves().front(),
Math::lose_score,
perspective,
depth,
""};
auto all_legal_moves = board.all_legal_moves();
const auto current_legal_moves_count = all_legal_moves.size();
// The first item in the principal variation is the last move that
// this player made. Since then, the opponent has also made a move,
// so the first item in the principal variation corresponds to the
// game record item at game_record.size() - 2. The depth of the game
// tree search increments both the game_record index and the principal
// variation index in step.
bool still_on_principal_variation = false;
if(principal_variation.size() > depth + 2)
{
auto principal_variation_start_index = board.get_game_record().size() - depth - 2;
still_on_principal_variation = std::equal(board.get_game_record().begin() + principal_variation_start_index,
board.get_game_record().end(),
principal_variation.begin());
if(still_on_principal_variation)
{
auto next_principal_variation_move = principal_variation[depth + 2];
auto move_iter = std::find_if(all_legal_moves.begin(),
all_legal_moves.end(),
[&next_principal_variation_move, &board](const auto& cm)
{
return cm.game_record_item(board) == next_principal_variation_move;
});
// Put principal variation move at start of list to allow
// the most pruning later.
std::iter_swap(all_legal_moves.begin(), move_iter);
}
}
for(const auto& move : all_legal_moves)
{
auto next_board = board;
try
{
next_board.submit_move(move);
}
catch(const Checkmate_Exception&)
{
// Mate in one (try to pick the shortest path to checkmate)
auto score = genome.evaluate(next_board, perspective);
auto comment = next_board.get_game_record().back();
return {move,
score,
perspective,
depth,
comment};
}
catch(const Game_Ending_Exception&)
{
// Draws get scored like any other board position
}
Game_Tree_Node_Result result;
int moves_left = current_legal_moves_count - moves_examined;
double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));
double time_alloted_for_this_move = time_left/moves_left;
bool recurse;
if(next_board.game_has_ended())
{
recurse = false;
}
else if(next_board.all_legal_moves().size() == 1)
{
recurse = true;
}
else if(still_on_principal_variation)
{
recurse = true;
}
else if(time_alloted_for_this_move < genome.minimum_time_to_recurse(next_board))
{
recurse = false;
}
else
{
recurse = genome.good_enough_to_examine(board, next_board, perspective);
}
if(recurse)
{
result = search_game_tree(next_board,
time_alloted_for_this_move,
clock,
depth + 1,
beta,
alpha);
// Update last result with this game tree node's data
result.move = move;
result.commentary = next_board.get_game_record().back()
+ " "
+ result.commentary;
}
else
{
// Record immediate result without looking ahead further
result = {move,
genome.evaluate(next_board, perspective),
perspective,
depth,
next_board.get_game_record().back()};
}
if(better_than(result, best_result, perspective))
{
best_result = result;
if(better_than(best_result, alpha, perspective))
{
alpha = best_result;
if(better_than(alpha, beta, perspective) || alpha == beta)
{
break;
}
}
}
++moves_examined;
still_on_principal_variation = false; // only the first move is part of the principal variation
}
return best_result;
}
void Genetic_AI::mutate()
{
genome.mutate();
}
void Genetic_AI::print_genome(const std::string& file_name) const
{
if(file_name.empty())
{
print_genome(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print_genome(dest);
}
}
void Genetic_AI::print_genome(std::ostream& os) const
{
os << "ID: " << get_id() << std::endl;
genome.print(os);
os << "END" << std::endl << std::endl;
}
std::string Genetic_AI::name() const
{
return "Genetic AI " + std::to_string(get_id());
}
std::string Genetic_AI::author() const
{
return "Mark Harrison";
}
int Genetic_AI::get_id() const
{
return id;
}
bool Genetic_AI::operator<(const Genetic_AI& other) const
{
return get_id() < other.get_id();
}
bool Genetic_AI::operator==(const Genetic_AI& other) const
{
return get_id() == other.get_id();
}
<|endoftext|> |
<commit_before>#include "Players/Minimax_AI.h"
#include <iostream>
#include "Players/Game_Tree_Node_Result.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Utility.h"
const Move& Minimax_AI::choose_move(const Board& board, const Clock& clock) const
{
// Erase data from previous board when starting new game
if(board.get_game_record().size() <= 1)
{
principal_variation.clear();
commentary.clear();
}
nodes_searched = 0;
clock_start_time = clock.time_left(clock.running_for());
maximum_depth = 0;
nodes_evaluated = 0;
total_evaluation_time = 0.0;
const auto& legal_moves = board.legal_moves();
if(legal_moves.size() == 1)
{
if(principal_variation.size() > 2 && principal_variation[1] == board.get_game_record().back())
{
// search_game_tree() assumes the principal variation starts
// with the previous move of this player. If a move was forced,
// then the principal variation needs to be updated to start with
// the next move of this side after checking that the immediately
// preceding move was the expected one.
principal_variation.erase(principal_variation.begin(),
principal_variation.begin() + 2);
}
else
{
principal_variation.clear();
}
commentary.push_back(principal_variation);
return *legal_moves.front(); // If there's only one legal move, take it.
}
auto time_to_use = time_to_examine(board, clock);
// alpha = highest score found that opponent will allow
Game_Tree_Node_Result alpha_start = {Math::lose_score,
board.whose_turn(),
{nullptr}};
// beta = score that will cause opponent to choose a different prior move
Game_Tree_Node_Result beta_start = {Math::win_score,
board.whose_turn(),
{nullptr}};
auto result = search_game_tree(board,
time_to_use,
clock,
0,
alpha_start,
beta_start,
! principal_variation.empty());
if(board.get_thinking_mode() == CECP)
{
output_thinking_cecp(result, clock, board.whose_turn());
std::cout << std::flush;
}
if(result.depth() > 0)
{
commentary.push_back(result.variation);
}
else
{
commentary.push_back({});
}
if(result.depth() > 1)
{
principal_variation = result.variation;
}
else
{
principal_variation.clear();
}
if(nodes_evaluated > 0)
{
evaluation_speed = nodes_evaluated / total_evaluation_time;
}
return *result.variation.front();
}
Game_Tree_Node_Result Minimax_AI::search_game_tree(const Board& board,
const double time_to_examine,
const Clock& clock,
const size_t depth,
Game_Tree_Node_Result alpha,
const Game_Tree_Node_Result& beta,
bool still_on_principal_variation) const
{
auto time_start = clock.time_left(clock.running_for());
maximum_depth = std::max(maximum_depth, depth);
auto all_legal_moves = board.legal_moves();
// The first item in the principal variation is the last move that
// this player made. Since then, the opponent has also made a move,
// so the first item in the principal variation corresponds to the
// game record item at game_record.size() - 2. The depth of the game
// tree search increments both the game_record index and the principal
// variation index in step.
if(still_on_principal_variation && principal_variation.size() > depth + 2)
{
auto next_principal_variation_move = principal_variation[depth + 2];
auto move_iter = std::find(all_legal_moves.begin(),
all_legal_moves.end(),
next_principal_variation_move);
if(move_iter != all_legal_moves.end())
{
// Put principal variation move at start of list to allow
// the most pruning later.
std::iter_swap(all_legal_moves.begin(), move_iter);
}
}
else
{
still_on_principal_variation = false;
}
// Consider capturing moves first after principal variation move
auto partition_start = std::next(all_legal_moves.begin(), still_on_principal_variation ? 1 : 0);
std::partition(partition_start, all_legal_moves.end(),
[&board](auto move){ return board.move_captures(*move); });
auto perspective = board.whose_turn();
auto moves_left = all_legal_moves.size();
Game_Tree_Node_Result best_result = {Math::lose_score,
perspective,
{all_legal_moves.front()}};
for(const auto& move : all_legal_moves)
{
auto evaluate_start_time = clock.time_left(clock.running_for());
++nodes_searched;
auto next_board = board;
auto move_result = next_board.submit_move(*move);
if(move_result.get_winner() != NONE)
{
// This move results in checkmate, no other move can be better.
return create_result(next_board, perspective, move_result, depth);
}
if(alpha.depth() <= depth + 2 && alpha.corrected_score(perspective) == Math::win_score)
{
// This move will take a longer path to victory
// than one already found. Use "depth + 2" since,
// if this move isn't winning (and it isn't, since
// we're here), then the earliest move that can
// win is the next one, which is two away (after
// opponent's move).
continue;
}
double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));
if(time_left < 0.0)
{
break;
}
double time_allotted_for_this_move = (time_left / moves_left)*speculation_time_factor(next_board);
time_allotted_for_this_move = std::min(time_allotted_for_this_move, clock.time_left(clock.running_for()));
bool recurse;
if(move_result.game_has_ended())
{
recurse = false;
}
else if(still_on_principal_variation)
{
recurse = true;
}
else if(depth > 500)
{
recurse = false;
}
else
{
auto minimum_time_to_recurse = next_board.legal_moves().size() / evaluation_speed;
recurse = (time_allotted_for_this_move > minimum_time_to_recurse);
}
Game_Tree_Node_Result result;
if(recurse)
{
result = search_game_tree(next_board,
time_allotted_for_this_move,
clock,
depth + 1,
beta,
alpha,
still_on_principal_variation);
}
else
{
// Record immediate result without looking ahead further
result = create_result(next_board, perspective, move_result, depth);
}
if(better_than(result, best_result, perspective))
{
best_result = result;
if(better_than(best_result, alpha, perspective))
{
alpha = best_result;
if(better_than(alpha, beta, perspective) || alpha == beta)
{
break;
}
else if(board.get_thinking_mode() == CECP && recurse)
{
output_thinking_cecp(alpha, clock,
depth % 2 == 0 ? perspective : opposite(perspective));
}
}
}
--moves_left;
still_on_principal_variation = false; // only the first move is part of the principal variation
if(clock.time_left(clock.running_for()) < 0)
{
break;
}
if(!recurse) // This move was scored by genome.evaluate().
{
++nodes_evaluated;
total_evaluation_time += evaluate_start_time - clock.time_left(clock.running_for());
}
}
return best_result;
}
void Minimax_AI::output_thinking_cecp(const Game_Tree_Node_Result& thought,
const Clock& clock,
Color perspective) const
{
auto score = thought.corrected_score(perspective) / centipawn_value();
// Indicate "mate in N moves" where N == thought.depth
if(score == Math::win_score)
{
score = 10000.0 - thought.depth();
}
else if(score == Math::lose_score)
{
score = -(10000.0 - thought.depth());
}
auto time_so_far = clock_start_time - clock.time_left(clock.running_for());
std::cout << thought.depth() // ply
<< " "
<< int(score) // score in what should be centipawns
<< " "
<< int(time_so_far * 100) // search time in centiseconds
<< " "
<< nodes_searched
<< " "
<< maximum_depth
<< " "
<< int(nodes_searched / time_so_far)
<< '\t';
// Principal variation
for(const auto& move : thought.variation)
{
std::cout << move->coordinate_move() << ' ';
}
std::cout << '\n';
}
Game_Tree_Node_Result Minimax_AI::create_result(const Board& board,
Color perspective,
Game_Result move_result,
size_t depth) const
{
return {evaluate(board, move_result, perspective),
perspective,
{board.get_game_record().end() - (depth + 1),
board.get_game_record().end()}};
}
void Minimax_AI::calibrate_thinking_speed() const
{
evaluation_speed = 100; // very conservative initial guess
auto calibration_time = 1.0; // seconds
Board board;
Clock clock(calibration_time, 1, 0.0);
clock.start();
choose_move(board, clock);
// choose_move() keeps track of the time it takes and the number of positions
// it sees, so this practice move will update the positions_per_second to a
// more reasonable value.
}
double Minimax_AI::evaluate(const Board & board, Game_Result move_result, Color perspective) const
{
if(move_result.game_has_ended())
{
if(move_result.get_winner() == NONE) // stalemate
{
return 0;
}
else if(move_result.get_winner() == perspective) // checkmate win
{
return Math::win_score;
}
else // checkmate loss
{
return Math::lose_score;
}
}
return internal_evaluate(board, perspective);
}
double Minimax_AI::centipawn_value() const
{
return value_of_centipawn;
}
void Minimax_AI::calculate_centipawn_value()
{
auto board_with_pawns = Board("4k3/pppppppp/8/8/8/8/PPPPPPPP/4K3 w - - 0 1");
auto board_with_no_white_pawns = Board("4k3/pppppppp/8/8/8/8/8/4K3 w - - 0 1");
value_of_centipawn = std::abs(evaluate(board_with_pawns, {}, WHITE) - evaluate(board_with_no_white_pawns, {}, WHITE)) / 800;
}
std::string Minimax_AI::get_commentary_for_move(size_t move_number) const
{
std::string result;
if(move_number < commentary.size() && !commentary.at(move_number).empty())
{
result = commentary.at(move_number).front()->coordinate_move();
for(size_t i = 1; i < commentary.at(move_number).size(); ++i)
{
result += " " + commentary.at(move_number).at(i)->coordinate_move();
}
}
return result;
}
<commit_msg>Don't cut off analysis early<commit_after>#include "Players/Minimax_AI.h"
#include <iostream>
#include "Players/Game_Tree_Node_Result.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Utility.h"
const Move& Minimax_AI::choose_move(const Board& board, const Clock& clock) const
{
// Erase data from previous board when starting new game
if(board.get_game_record().size() <= 1)
{
principal_variation.clear();
commentary.clear();
}
nodes_searched = 0;
clock_start_time = clock.time_left(clock.running_for());
maximum_depth = 0;
nodes_evaluated = 0;
total_evaluation_time = 0.0;
const auto& legal_moves = board.legal_moves();
if(legal_moves.size() == 1)
{
if(principal_variation.size() > 2 && principal_variation[1] == board.get_game_record().back())
{
// search_game_tree() assumes the principal variation starts
// with the previous move of this player. If a move was forced,
// then the principal variation needs to be updated to start with
// the next move of this side after checking that the immediately
// preceding move was the expected one.
principal_variation.erase(principal_variation.begin(),
principal_variation.begin() + 2);
}
else
{
principal_variation.clear();
}
commentary.push_back(principal_variation);
return *legal_moves.front(); // If there's only one legal move, take it.
}
auto time_to_use = time_to_examine(board, clock);
// alpha = highest score found that opponent will allow
Game_Tree_Node_Result alpha_start = {Math::lose_score,
board.whose_turn(),
{nullptr}};
// beta = score that will cause opponent to choose a different prior move
Game_Tree_Node_Result beta_start = {Math::win_score,
board.whose_turn(),
{nullptr}};
auto result = search_game_tree(board,
time_to_use,
clock,
0,
alpha_start,
beta_start,
! principal_variation.empty());
if(board.get_thinking_mode() == CECP)
{
output_thinking_cecp(result, clock, board.whose_turn());
std::cout << std::flush;
}
if(result.depth() > 0)
{
commentary.push_back(result.variation);
}
else
{
commentary.push_back({});
}
if(result.depth() > 1)
{
principal_variation = result.variation;
}
else
{
principal_variation.clear();
}
if(nodes_evaluated > 0)
{
evaluation_speed = nodes_evaluated / total_evaluation_time;
}
return *result.variation.front();
}
Game_Tree_Node_Result Minimax_AI::search_game_tree(const Board& board,
const double time_to_examine,
const Clock& clock,
const size_t depth,
Game_Tree_Node_Result alpha,
const Game_Tree_Node_Result& beta,
bool still_on_principal_variation) const
{
auto time_start = clock.time_left(clock.running_for());
maximum_depth = std::max(maximum_depth, depth);
auto all_legal_moves = board.legal_moves();
// The first item in the principal variation is the last move that
// this player made. Since then, the opponent has also made a move,
// so the first item in the principal variation corresponds to the
// game record item at game_record.size() - 2. The depth of the game
// tree search increments both the game_record index and the principal
// variation index in step.
if(still_on_principal_variation && principal_variation.size() > depth + 2)
{
auto next_principal_variation_move = principal_variation[depth + 2];
auto move_iter = std::find(all_legal_moves.begin(),
all_legal_moves.end(),
next_principal_variation_move);
if(move_iter != all_legal_moves.end())
{
// Put principal variation move at start of list to allow
// the most pruning later.
std::iter_swap(all_legal_moves.begin(), move_iter);
}
}
else
{
still_on_principal_variation = false;
}
// Consider capturing moves first after principal variation move
auto partition_start = std::next(all_legal_moves.begin(), still_on_principal_variation ? 1 : 0);
std::partition(partition_start, all_legal_moves.end(),
[&board](auto move){ return board.move_captures(*move); });
auto perspective = board.whose_turn();
auto moves_left = all_legal_moves.size();
Game_Tree_Node_Result best_result = {Math::lose_score,
perspective,
{all_legal_moves.front()}};
for(const auto& move : all_legal_moves)
{
auto evaluate_start_time = clock.time_left(clock.running_for());
++nodes_searched;
auto next_board = board;
auto move_result = next_board.submit_move(*move);
if(move_result.get_winner() != NONE)
{
// This move results in checkmate, no other move can be better.
return create_result(next_board, perspective, move_result, depth);
}
if(alpha.depth() <= depth + 2 && alpha.corrected_score(perspective) == Math::win_score)
{
// This move will take a longer path to victory
// than one already found. Use "depth + 2" since,
// if this move isn't winning (and it isn't, since
// we're here), then the earliest move that can
// win is the next one, which is two away (after
// opponent's move).
continue;
}
double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));
double time_allotted_for_this_move = (time_left / moves_left)*speculation_time_factor(next_board);
time_allotted_for_this_move = std::min(time_allotted_for_this_move, clock.time_left(clock.running_for()));
bool recurse;
if(move_result.game_has_ended())
{
recurse = false;
}
else if(still_on_principal_variation)
{
recurse = true;
}
else if(depth > 500)
{
recurse = false;
}
else
{
auto minimum_time_to_recurse = next_board.legal_moves().size() / evaluation_speed;
recurse = (time_allotted_for_this_move > minimum_time_to_recurse);
}
Game_Tree_Node_Result result;
if(recurse)
{
result = search_game_tree(next_board,
time_allotted_for_this_move,
clock,
depth + 1,
beta,
alpha,
still_on_principal_variation);
}
else
{
// Record immediate result without looking ahead further
result = create_result(next_board, perspective, move_result, depth);
}
if(better_than(result, best_result, perspective))
{
best_result = result;
if(better_than(best_result, alpha, perspective))
{
alpha = best_result;
if(better_than(alpha, beta, perspective) || alpha == beta)
{
break;
}
else if(board.get_thinking_mode() == CECP && recurse)
{
output_thinking_cecp(alpha, clock,
depth % 2 == 0 ? perspective : opposite(perspective));
}
}
}
--moves_left;
still_on_principal_variation = false; // only the first move is part of the principal variation
if(clock.time_left(clock.running_for()) < 0)
{
break;
}
if(!recurse) // This move was scored by genome.evaluate().
{
++nodes_evaluated;
total_evaluation_time += evaluate_start_time - clock.time_left(clock.running_for());
}
}
return best_result;
}
void Minimax_AI::output_thinking_cecp(const Game_Tree_Node_Result& thought,
const Clock& clock,
Color perspective) const
{
auto score = thought.corrected_score(perspective) / centipawn_value();
// Indicate "mate in N moves" where N == thought.depth
if(score == Math::win_score)
{
score = 10000.0 - thought.depth();
}
else if(score == Math::lose_score)
{
score = -(10000.0 - thought.depth());
}
auto time_so_far = clock_start_time - clock.time_left(clock.running_for());
std::cout << thought.depth() // ply
<< " "
<< int(score) // score in what should be centipawns
<< " "
<< int(time_so_far * 100) // search time in centiseconds
<< " "
<< nodes_searched
<< " "
<< maximum_depth
<< " "
<< int(nodes_searched / time_so_far)
<< '\t';
// Principal variation
for(const auto& move : thought.variation)
{
std::cout << move->coordinate_move() << ' ';
}
std::cout << '\n';
}
Game_Tree_Node_Result Minimax_AI::create_result(const Board& board,
Color perspective,
Game_Result move_result,
size_t depth) const
{
return {evaluate(board, move_result, perspective),
perspective,
{board.get_game_record().end() - (depth + 1),
board.get_game_record().end()}};
}
void Minimax_AI::calibrate_thinking_speed() const
{
evaluation_speed = 100; // very conservative initial guess
auto calibration_time = 1.0; // seconds
Board board;
Clock clock(calibration_time, 1, 0.0);
clock.start();
choose_move(board, clock);
// choose_move() keeps track of the time it takes and the number of positions
// it sees, so this practice move will update the positions_per_second to a
// more reasonable value.
}
double Minimax_AI::evaluate(const Board & board, Game_Result move_result, Color perspective) const
{
if(move_result.game_has_ended())
{
if(move_result.get_winner() == NONE) // stalemate
{
return 0;
}
else if(move_result.get_winner() == perspective) // checkmate win
{
return Math::win_score;
}
else // checkmate loss
{
return Math::lose_score;
}
}
return internal_evaluate(board, perspective);
}
double Minimax_AI::centipawn_value() const
{
return value_of_centipawn;
}
void Minimax_AI::calculate_centipawn_value()
{
auto board_with_pawns = Board("4k3/pppppppp/8/8/8/8/PPPPPPPP/4K3 w - - 0 1");
auto board_with_no_white_pawns = Board("4k3/pppppppp/8/8/8/8/8/4K3 w - - 0 1");
value_of_centipawn = std::abs(evaluate(board_with_pawns, {}, WHITE) - evaluate(board_with_no_white_pawns, {}, WHITE)) / 800;
}
std::string Minimax_AI::get_commentary_for_move(size_t move_number) const
{
std::string result;
if(move_number < commentary.size() && !commentary.at(move_number).empty())
{
result = commentary.at(move_number).front()->coordinate_move();
for(size_t i = 1; i < commentary.at(move_number).size(); ++i)
{
result += " " + commentary.at(move_number).at(i)->coordinate_move();
}
}
return result;
}
<|endoftext|> |
<commit_before>/*
* MIT License
*
* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
*
* 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 <fcntl.h>
#include <string.h>
#include <list>
#include "SelectWrap.h"
#include "EventPoller.h"
#include "Util/util.h"
#include "Util/logger.h"
#include "Util/uv_errno.h"
#include "Util/TimeTicker.h"
#include "Util/onceToken.h"
#include "Thread/ThreadPool.h"
#include "Network/sockutil.h"
#if defined(HAS_EPOLL)
#include <sys/epoll.h>
#if !defined(EPOLLEXCLUSIVE)
#define EPOLLEXCLUSIVE 0
#endif
#define EPOLL_SIZE 1024
#define toEpoll(event) (((event) & Event_Read) ? EPOLLIN : 0) \
| (((event) & Event_Write) ? EPOLLOUT : 0) \
| (((event) & Event_Error) ? (EPOLLHUP | EPOLLERR) : 0) \
| (((event) & Event_LT) ? 0 : EPOLLET)
#define toPoller(epoll_event) (((epoll_event) & EPOLLIN) ? Event_Read : 0) \
| (((epoll_event) & EPOLLOUT) ? Event_Write : 0) \
| (((epoll_event) & EPOLLHUP) ? Event_Error : 0) \
| (((epoll_event) & EPOLLERR) ? Event_Error : 0)
#endif //HAS_EPOLL
namespace toolkit {
EventPoller &EventPoller::Instance() {
return *(EventPollerPool::Instance().getFirstPoller());
}
EventPoller::EventPoller(ThreadPool::Priority priority ) {
_priority = priority;
SockUtil::setNoBlocked(_pipe.readFD());
SockUtil::setNoBlocked(_pipe.writeFD());
#if defined(HAS_EPOLL)
_epoll_fd = epoll_create(EPOLL_SIZE);
if (_epoll_fd == -1) {
throw runtime_error(StrPrinter << "创建epoll文件描述符失败:" << get_uv_errmsg());
}
#endif //HAS_EPOLL
_logger = Logger::Instance().shared_from_this();
_loopThreadId = this_thread::get_id();
//添加内部管道事件
if (addEvent(_pipe.readFD(), Event_Read, [this](int event) {onPipeEvent();}) == -1) {
throw std::runtime_error("epoll添加管道失败");
}
}
void EventPoller::shutdown() {
async_l([](){
throw ExitException();
},false, true);
if (_loopThread) {
_loopThread->join();
delete _loopThread;
_loopThread = nullptr;
}
}
EventPoller::~EventPoller() {
shutdown();
wait();
#if defined(HAS_EPOLL)
if (_epoll_fd != -1) {
close(_epoll_fd);
_epoll_fd = -1;
}
#endif //defined(HAS_EPOLL)
//退出前清理管道中的数据
_loopThreadId = this_thread::get_id();
onPipeEvent();
InfoL << this;
}
int EventPoller::addEvent(int fd, int event, PollEventCB &&cb) {
TimeTicker();
if (!cb) {
WarnL << "PollEventCB 为空!";
return -1;
}
if (isCurrentThread()) {
#if defined(HAS_EPOLL)
struct epoll_event ev = {0};
ev.events = (toEpoll(event)) | EPOLLEXCLUSIVE;
ev.data.fd = fd;
int ret = epoll_ctl(_epoll_fd, EPOLL_CTL_ADD, fd, &ev);
if (ret == 0) {
_event_map.emplace(fd, std::make_shared<PollEventCB>(std::move(cb)));
}
return ret;
#else
Poll_Record::Ptr record(new Poll_Record);
record->event = event;
record->callBack = std::move(cb);
_event_map.emplace(fd, record);
return 0;
#endif //HAS_EPOLL
}
async([this, fd, event, cb]() {
addEvent(fd, event, std::move(const_cast<PollEventCB &>(cb)));
});
return 0;
}
int EventPoller::delEvent(int fd, PollDelCB &&cb) {
TimeTicker();
if (!cb) {
cb = [](bool success) {};
}
if (isCurrentThread()) {
#if defined(HAS_EPOLL)
bool success = epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, fd, NULL) == 0 && _event_map.erase(fd) > 0;
cb(success);
return success ? 0 : -1;
#else
cb(_event_map.erase(fd));
return 0;
#endif //HAS_EPOLL
}
//跨线程操作
async([this, fd, cb]() {
delEvent(fd, std::move(const_cast<PollDelCB &>(cb)));
});
return 0;
}
int EventPoller::modifyEvent(int fd, int event) {
TimeTicker();
//TraceL<<fd<<" "<<event;
#if defined(HAS_EPOLL)
struct epoll_event ev = {0};
ev.events = toEpoll(event);
ev.data.fd = fd;
return epoll_ctl(_epoll_fd, EPOLL_CTL_MOD, fd, &ev);
#else
if (isCurrentThread()) {
auto it = _event_map.find(fd);
if (it != _event_map.end()) {
it->second->event = event;
}
return 0;
}
async([this, fd, event]() {
modifyEvent(fd, event);
});
return 0;
#endif //HAS_EPOLL
}
Task::Ptr EventPoller::async(TaskIn &&task, bool may_sync) {
return async_l(std::move(task),may_sync, false);
}
Task::Ptr EventPoller::async_first(TaskIn &&task, bool may_sync) {
return async_l(std::move(task),may_sync, true);
}
Task::Ptr EventPoller::async_l(TaskIn &&task,bool may_sync, bool first) {
TimeTicker();
if (may_sync && isCurrentThread()) {
task();
return nullptr;
}
auto ret = std::make_shared<Task>(std::move(task));
{
lock_guard<mutex> lck(_mtx_task);
if(first){
_list_task.emplace_front(ret);
}else{
_list_task.emplace_back(ret);
}
}
//写数据到管道,唤醒主线程
_pipe.write("",1);
return ret;
}
bool EventPoller::isCurrentThread() {
return _loopThreadId == this_thread::get_id();
}
inline void EventPoller::onPipeEvent() {
TimeTicker();
char buf[1024];
int err = 0;
do {
if (_pipe.read(buf, sizeof(buf)) > 0) {
continue;
}
err = get_uv_error(true);
} while (err != UV_EAGAIN);
decltype(_list_task) _list_swap;
{
lock_guard<mutex> lck(_mtx_task);
_list_swap.swap(_list_task);
}
_list_swap.for_each([&](const Task::Ptr &task){
try {
(*task)();
}catch (ExitException &ex){
_exit_flag = true;
}catch (std::exception &ex){
ErrorL << "EventPoller执行异步任务捕获到异常:" << ex.what();
}
});
}
void EventPoller::wait() {
lock_guard<mutex> lck(_mtx_runing);
}
static map<thread::id,weak_ptr<EventPoller> > s_allThreads;
static mutex s_allThreadsMtx;
//static
EventPoller::Ptr EventPoller::getCurrentPoller(){
lock_guard<mutex> lck(s_allThreadsMtx);
auto it = s_allThreads.find(this_thread::get_id());
if(it == s_allThreads.end()){
return nullptr;
}
return it->second.lock();
}
void EventPoller::runLoop(bool blocked) {
if (blocked) {
ThreadPool::setPriority(_priority);
lock_guard<mutex> lck(_mtx_runing);
_loopThreadId = this_thread::get_id();
{
lock_guard<mutex> lck(s_allThreadsMtx);
s_allThreads[_loopThreadId] = shared_from_this();
}
_sem_run_started.post();
_exit_flag = false;
uint64_t minDelay;
#if defined(HAS_EPOLL)
struct epoll_event events[EPOLL_SIZE];
while (!_exit_flag) {
minDelay = getMinDelay();
startSleep();//用于统计当前线程负载情况
int ret = epoll_wait(_epoll_fd, events, EPOLL_SIZE, minDelay ? minDelay : -1);
sleepWakeUp();//用于统计当前线程负载情况
if(ret <= 0){
//超时或被打断
continue;
}
for (int i = 0; i < ret; ++i) {
struct epoll_event &ev = events[i];
int fd = ev.data.fd;
auto it = _event_map.find(fd);
if (it == _event_map.end()) {
epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, fd, NULL);
continue;
}
auto cb = it->second;
try{
(*cb)(toPoller(ev.events));
}catch (std::exception &ex){
ErrorL << "EventPoller执行事件回调捕获到异常:" << ex.what();
}
}
}
#else
int ret, max_fd;
FdSet set_read, set_write, set_err;
List<Poll_Record::Ptr> callback_list;
struct timeval tv;
while (!_exit_flag) {
//定时器事件中可能操作_event_map
minDelay = getMinDelay();
tv.tv_sec = minDelay / 1000;
tv.tv_usec = 1000 * (minDelay % 1000);
set_read.fdZero();
set_write.fdZero();
set_err.fdZero();
max_fd = 0;
for (auto &pr : _event_map) {
if (pr.first > max_fd) {
max_fd = pr.first;
}
if (pr.second->event & Event_Read) {
set_read.fdSet(pr.first);//监听管道可读事件
}
if (pr.second->event & Event_Write) {
set_write.fdSet(pr.first);//监听管道可写事件
}
if (pr.second->event & Event_Error) {
set_err.fdSet(pr.first);//监听管道错误事件
}
}
startSleep();//用于统计当前线程负载情况
ret = zl_select(max_fd + 1, &set_read, &set_write, &set_err, minDelay ? &tv: NULL);
sleepWakeUp();//用于统计当前线程负载情况
if(ret <= 0) {
//超时或被打断
continue;
}
//收集select事件类型
for (auto &pr : _event_map) {
int event = 0;
if (set_read.isSet(pr.first)) {
event |= Event_Read;
}
if (set_write.isSet(pr.first)) {
event |= Event_Write;
}
if (set_err.isSet(pr.first)) {
event |= Event_Error;
}
if (event != 0) {
pr.second->attach = event;
callback_list.emplace_back(pr.second);
}
}
callback_list.for_each([](Poll_Record::Ptr &record){
try{
record->callBack(record->attach);
}catch (std::exception &ex){
ErrorL << "EventPoller执行事件回调捕获到异常:" << ex.what();
}
});
callback_list.clear();
}
#endif //HAS_EPOLL
}else{
_loopThread = new thread(&EventPoller::runLoop, this, true);
_sem_run_started.wait();
}
}
uint64_t EventPoller::flushDelayTask(uint64_t now_time) {
decltype(_delayTask) taskUpdated;
for(auto it = _delayTask.begin() ; it != _delayTask.end() && it->first <= now_time ; it = _delayTask.erase(it)){
//已到期的任务
try {
auto next_delay = (*(it->second))();
if(next_delay){
//可重复任务,更新时间截止线
taskUpdated.emplace(next_delay + now_time,std::move(it->second));
}
}catch (std::exception &ex){
ErrorL << "EventPoller执行延时任务捕获到异常:" << ex.what();
}
}
_delayTask.insert(taskUpdated.begin(),taskUpdated.end());
auto it = _delayTask.begin();
if(it == _delayTask.end()){
//没有剩余的定时器了
return 0;
}
//最近一个定时器的执行延时
return it->first - now_time;
}
uint64_t EventPoller::getMinDelay() {
auto it = _delayTask.begin();
if(it == _delayTask.end()){
//没有剩余的定时器了
return 0;
}
auto now = getCurrentMillisecond();
if(it->first > now){
//所有任务尚未到期
return it->first - now;
}
//执行已到期的任务并刷新休眠延时
return flushDelayTask(now);
}
DelayTask::Ptr EventPoller::doDelayTask(uint64_t delayMS, function<uint64_t()> &&task) {
DelayTask::Ptr ret = std::make_shared<DelayTask>(std::move(task));
auto time_line = getCurrentMillisecond() + delayMS;
async_first([time_line,ret,this](){
//异步执行的目的是刷新select或epoll的休眠时间
_delayTask.emplace(time_line,ret);
});
return ret;
}
///////////////////////////////////////////////
int EventPollerPool::s_pool_size = 0;
INSTANCE_IMP(EventPollerPool);
EventPoller::Ptr EventPollerPool::getFirstPoller(){
return dynamic_pointer_cast<EventPoller>(_threads.front());
}
EventPoller::Ptr EventPollerPool::getPoller(){
auto poller = EventPoller::getCurrentPoller();
if(_preferCurrentThread && poller){
return poller;
}
return dynamic_pointer_cast<EventPoller>(getExecutor());
}
void EventPollerPool::preferCurrentThread(bool flag){
_preferCurrentThread = flag;
}
EventPollerPool::EventPollerPool(){
auto size = s_pool_size ? s_pool_size : thread::hardware_concurrency();
createThreads([](){
EventPoller::Ptr ret(new EventPoller);
ret->runLoop(false);
return ret;
},size);
InfoL << "创建EventPoller个数:" << size;
}
void EventPollerPool::setPoolSize(int size) {
s_pool_size = size;
}
} // namespace toolkit
<commit_msg>修复可能存在的bug<commit_after>/*
* MIT License
*
* Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
*
* 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 <fcntl.h>
#include <string.h>
#include <list>
#include "SelectWrap.h"
#include "EventPoller.h"
#include "Util/util.h"
#include "Util/logger.h"
#include "Util/uv_errno.h"
#include "Util/TimeTicker.h"
#include "Util/onceToken.h"
#include "Thread/ThreadPool.h"
#include "Network/sockutil.h"
#if defined(HAS_EPOLL)
#include <sys/epoll.h>
#if !defined(EPOLLEXCLUSIVE)
#define EPOLLEXCLUSIVE 0
#endif
#define EPOLL_SIZE 1024
#define toEpoll(event) (((event) & Event_Read) ? EPOLLIN : 0) \
| (((event) & Event_Write) ? EPOLLOUT : 0) \
| (((event) & Event_Error) ? (EPOLLHUP | EPOLLERR) : 0) \
| (((event) & Event_LT) ? 0 : EPOLLET)
#define toPoller(epoll_event) (((epoll_event) & EPOLLIN) ? Event_Read : 0) \
| (((epoll_event) & EPOLLOUT) ? Event_Write : 0) \
| (((epoll_event) & EPOLLHUP) ? Event_Error : 0) \
| (((epoll_event) & EPOLLERR) ? Event_Error : 0)
#endif //HAS_EPOLL
namespace toolkit {
EventPoller &EventPoller::Instance() {
return *(EventPollerPool::Instance().getFirstPoller());
}
EventPoller::EventPoller(ThreadPool::Priority priority ) {
_priority = priority;
SockUtil::setNoBlocked(_pipe.readFD());
SockUtil::setNoBlocked(_pipe.writeFD());
#if defined(HAS_EPOLL)
_epoll_fd = epoll_create(EPOLL_SIZE);
if (_epoll_fd == -1) {
throw runtime_error(StrPrinter << "创建epoll文件描述符失败:" << get_uv_errmsg());
}
#endif //HAS_EPOLL
_logger = Logger::Instance().shared_from_this();
_loopThreadId = this_thread::get_id();
//添加内部管道事件
if (addEvent(_pipe.readFD(), Event_Read, [this](int event) {onPipeEvent();}) == -1) {
throw std::runtime_error("epoll添加管道失败");
}
}
void EventPoller::shutdown() {
async_l([](){
throw ExitException();
},false, true);
if (_loopThread) {
_loopThread->join();
delete _loopThread;
_loopThread = nullptr;
}
}
EventPoller::~EventPoller() {
shutdown();
wait();
#if defined(HAS_EPOLL)
if (_epoll_fd != -1) {
close(_epoll_fd);
_epoll_fd = -1;
}
#endif //defined(HAS_EPOLL)
//退出前清理管道中的数据
_loopThreadId = this_thread::get_id();
onPipeEvent();
InfoL << this;
}
int EventPoller::addEvent(int fd, int event, PollEventCB &&cb) {
TimeTicker();
if (!cb) {
WarnL << "PollEventCB 为空!";
return -1;
}
if (isCurrentThread()) {
#if defined(HAS_EPOLL)
struct epoll_event ev = {0};
ev.events = (toEpoll(event)) | EPOLLEXCLUSIVE;
ev.data.fd = fd;
int ret = epoll_ctl(_epoll_fd, EPOLL_CTL_ADD, fd, &ev);
if (ret == 0) {
_event_map.emplace(fd, std::make_shared<PollEventCB>(std::move(cb)));
}
return ret;
#else
Poll_Record::Ptr record(new Poll_Record);
record->event = event;
record->callBack = std::move(cb);
_event_map.emplace(fd, record);
return 0;
#endif //HAS_EPOLL
}
async([this, fd, event, cb]() {
addEvent(fd, event, std::move(const_cast<PollEventCB &>(cb)));
});
return 0;
}
int EventPoller::delEvent(int fd, PollDelCB &&cb) {
TimeTicker();
if (!cb) {
cb = [](bool success) {};
}
if (isCurrentThread()) {
#if defined(HAS_EPOLL)
bool success = epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, fd, NULL) == 0 && _event_map.erase(fd) > 0;
cb(success);
return success ? 0 : -1;
#else
cb(_event_map.erase(fd));
return 0;
#endif //HAS_EPOLL
}
//跨线程操作
async([this, fd, cb]() {
delEvent(fd, std::move(const_cast<PollDelCB &>(cb)));
});
return 0;
}
int EventPoller::modifyEvent(int fd, int event) {
TimeTicker();
//TraceL<<fd<<" "<<event;
#if defined(HAS_EPOLL)
struct epoll_event ev = {0};
ev.events = toEpoll(event);
ev.data.fd = fd;
return epoll_ctl(_epoll_fd, EPOLL_CTL_MOD, fd, &ev);
#else
if (isCurrentThread()) {
auto it = _event_map.find(fd);
if (it != _event_map.end()) {
it->second->event = event;
}
return 0;
}
async([this, fd, event]() {
modifyEvent(fd, event);
});
return 0;
#endif //HAS_EPOLL
}
Task::Ptr EventPoller::async(TaskIn &&task, bool may_sync) {
return async_l(std::move(task),may_sync, false);
}
Task::Ptr EventPoller::async_first(TaskIn &&task, bool may_sync) {
return async_l(std::move(task),may_sync, true);
}
Task::Ptr EventPoller::async_l(TaskIn &&task,bool may_sync, bool first) {
TimeTicker();
if (may_sync && isCurrentThread()) {
task();
return nullptr;
}
auto ret = std::make_shared<Task>(std::move(task));
{
lock_guard<mutex> lck(_mtx_task);
if(first){
_list_task.emplace_front(ret);
}else{
_list_task.emplace_back(ret);
}
}
//写数据到管道,唤醒主线程
_pipe.write("",1);
return ret;
}
bool EventPoller::isCurrentThread() {
return _loopThreadId == this_thread::get_id();
}
inline void EventPoller::onPipeEvent() {
TimeTicker();
char buf[1024];
int err = 0;
do {
if (_pipe.read(buf, sizeof(buf)) > 0) {
continue;
}
err = get_uv_error(true);
} while (err != UV_EAGAIN);
decltype(_list_task) _list_swap;
{
lock_guard<mutex> lck(_mtx_task);
_list_swap.swap(_list_task);
}
_list_swap.for_each([&](const Task::Ptr &task){
try {
(*task)();
}catch (ExitException &ex){
_exit_flag = true;
}catch (std::exception &ex){
ErrorL << "EventPoller执行异步任务捕获到异常:" << ex.what();
}
});
}
void EventPoller::wait() {
lock_guard<mutex> lck(_mtx_runing);
}
static map<thread::id,weak_ptr<EventPoller> > s_allThreads;
static mutex s_allThreadsMtx;
//static
EventPoller::Ptr EventPoller::getCurrentPoller(){
lock_guard<mutex> lck(s_allThreadsMtx);
auto it = s_allThreads.find(this_thread::get_id());
if(it == s_allThreads.end()){
return nullptr;
}
return it->second.lock();
}
void EventPoller::runLoop(bool blocked) {
if (blocked) {
ThreadPool::setPriority(_priority);
lock_guard<mutex> lck(_mtx_runing);
_loopThreadId = this_thread::get_id();
{
lock_guard<mutex> lck(s_allThreadsMtx);
s_allThreads[_loopThreadId] = shared_from_this();
}
_sem_run_started.post();
_exit_flag = false;
uint64_t minDelay;
#if defined(HAS_EPOLL)
struct epoll_event events[EPOLL_SIZE];
while (!_exit_flag) {
minDelay = getMinDelay();
startSleep();//用于统计当前线程负载情况
int ret = epoll_wait(_epoll_fd, events, EPOLL_SIZE, minDelay ? minDelay : -1);
sleepWakeUp();//用于统计当前线程负载情况
if(ret <= 0){
//超时或被打断
continue;
}
for (int i = 0; i < ret; ++i) {
struct epoll_event &ev = events[i];
int fd = ev.data.fd;
auto it = _event_map.find(fd);
if (it == _event_map.end()) {
epoll_ctl(_epoll_fd, EPOLL_CTL_DEL, fd, NULL);
continue;
}
auto cb = it->second;
try{
(*cb)(toPoller(ev.events));
}catch (std::exception &ex){
ErrorL << "EventPoller执行事件回调捕获到异常:" << ex.what();
}
}
}
#else
int ret, max_fd;
FdSet set_read, set_write, set_err;
List<Poll_Record::Ptr> callback_list;
struct timeval tv;
while (!_exit_flag) {
//定时器事件中可能操作_event_map
minDelay = getMinDelay();
tv.tv_sec = minDelay / 1000;
tv.tv_usec = 1000 * (minDelay % 1000);
set_read.fdZero();
set_write.fdZero();
set_err.fdZero();
max_fd = 0;
for (auto &pr : _event_map) {
if (pr.first > max_fd) {
max_fd = pr.first;
}
if (pr.second->event & Event_Read) {
set_read.fdSet(pr.first);//监听管道可读事件
}
if (pr.second->event & Event_Write) {
set_write.fdSet(pr.first);//监听管道可写事件
}
if (pr.second->event & Event_Error) {
set_err.fdSet(pr.first);//监听管道错误事件
}
}
startSleep();//用于统计当前线程负载情况
ret = zl_select(max_fd + 1, &set_read, &set_write, &set_err, minDelay ? &tv: NULL);
sleepWakeUp();//用于统计当前线程负载情况
if(ret <= 0) {
//超时或被打断
continue;
}
//收集select事件类型
for (auto &pr : _event_map) {
int event = 0;
if (set_read.isSet(pr.first)) {
event |= Event_Read;
}
if (set_write.isSet(pr.first)) {
event |= Event_Write;
}
if (set_err.isSet(pr.first)) {
event |= Event_Error;
}
if (event != 0) {
pr.second->attach = event;
callback_list.emplace_back(pr.second);
}
}
callback_list.for_each([](Poll_Record::Ptr &record){
try{
record->callBack(record->attach);
}catch (std::exception &ex){
ErrorL << "EventPoller执行事件回调捕获到异常:" << ex.what();
}
});
callback_list.clear();
}
#endif //HAS_EPOLL
}else{
_loopThread = new thread(&EventPoller::runLoop, this, true);
_sem_run_started.wait();
}
}
uint64_t EventPoller::flushDelayTask(uint64_t now_time) {
decltype(_delayTask) taskCopy;
taskCopy.swap(_delayTask);
for(auto it = taskCopy.begin() ; it != taskCopy.end() && it->first <= now_time ; it = taskCopy.erase(it)){
//已到期的任务
try {
auto next_delay = (*(it->second))();
if(next_delay){
//可重复任务,更新时间截止线
_delayTask.emplace(next_delay + now_time,std::move(it->second));
}
}catch (std::exception &ex){
ErrorL << "EventPoller执行延时任务捕获到异常:" << ex.what();
}
}
taskCopy.insert(_delayTask.begin(),_delayTask.end());
taskCopy.swap(_delayTask);
auto it = _delayTask.begin();
if(it == _delayTask.end()){
//没有剩余的定时器了
return 0;
}
//最近一个定时器的执行延时
return it->first - now_time;
}
uint64_t EventPoller::getMinDelay() {
auto it = _delayTask.begin();
if(it == _delayTask.end()){
//没有剩余的定时器了
return 0;
}
auto now = getCurrentMillisecond();
if(it->first > now){
//所有任务尚未到期
return it->first - now;
}
//执行已到期的任务并刷新休眠延时
return flushDelayTask(now);
}
DelayTask::Ptr EventPoller::doDelayTask(uint64_t delayMS, function<uint64_t()> &&task) {
DelayTask::Ptr ret = std::make_shared<DelayTask>(std::move(task));
auto time_line = getCurrentMillisecond() + delayMS;
async_first([time_line,ret,this](){
//异步执行的目的是刷新select或epoll的休眠时间
_delayTask.emplace(time_line,ret);
});
return ret;
}
///////////////////////////////////////////////
int EventPollerPool::s_pool_size = 0;
INSTANCE_IMP(EventPollerPool);
EventPoller::Ptr EventPollerPool::getFirstPoller(){
return dynamic_pointer_cast<EventPoller>(_threads.front());
}
EventPoller::Ptr EventPollerPool::getPoller(){
auto poller = EventPoller::getCurrentPoller();
if(_preferCurrentThread && poller){
return poller;
}
return dynamic_pointer_cast<EventPoller>(getExecutor());
}
void EventPollerPool::preferCurrentThread(bool flag){
_preferCurrentThread = flag;
}
EventPollerPool::EventPollerPool(){
auto size = s_pool_size ? s_pool_size : thread::hardware_concurrency();
createThreads([](){
EventPoller::Ptr ret(new EventPoller);
ret->runLoop(false);
return ret;
},size);
InfoL << "创建EventPoller个数:" << size;
}
void EventPollerPool::setPoolSize(int size) {
s_pool_size = size;
}
} // namespace toolkit
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "unzip.h"
#include "Resource.h"
#include "UpdateRunner.h"
#include <vector>
void CUpdateRunner::DisplayErrorMessage(CString& errorMessage, wchar_t* logFile)
{
CTaskDialog dlg;
TASKDIALOG_BUTTON buttons[] = {
{ 1, L"Open Setup Log", },
{ 2, L"Close", },
};
// TODO: Something about contacting support?
if (logFile == NULL) {
dlg.SetButtons(&buttons[1], 1, 1);
} else {
dlg.SetButtons(buttons, 2, 1);
}
dlg.SetMainInstructionText(L"Installation has failed");
dlg.SetContentText(errorMessage);
dlg.SetMainIcon(TD_ERROR_ICON);
int nButton;
if (FAILED(dlg.DoModal(::GetActiveWindow(), &nButton))) {
return;
}
if (nButton == 1 && logFile != NULL) {
ShellExecute(NULL, NULL, logFile, NULL, NULL, SW_SHOW);
}
}
HRESULT CUpdateRunner::AreWeUACElevated()
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken = 0;
HRESULT hr;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
TOKEN_ELEVATION_TYPE elevType;
DWORD dontcare;
if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(TOKEN_ELEVATION_TYPE), &dontcare)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
hr = (elevType == TokenElevationTypeFull ? S_OK : S_FALSE);
out:
if (hToken) {
CloseHandle(hToken);
}
return hr;
}
HRESULT FindDesktopFolderView(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellWindows> spShellWindows;
spShellWindows.CoCreateInstance(CLSID_ShellWindows);
CComVariant vtLoc(CSIDL_DESKTOP);
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
hr = spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty,
SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp);
if (FAILED(hr)) return hr;
CComPtr<IShellBrowser> spBrowser;
hr = CComQIPtr<IServiceProvider>(spdisp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser));
if (FAILED(hr)) return hr;
CComPtr<IShellView> spView;
hr = spBrowser->QueryActiveShellView(&spView);
if (FAILED(hr)) return hr;
hr = spView->QueryInterface(riid, ppv);
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT GetDesktopAutomationObject(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellView> spsv;
hr = FindDesktopFolderView(IID_PPV_ARGS(&spsv));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispView;
hr = spsv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spdispView));
if (FAILED(hr)) return hr;
return spdispView->QueryInterface(riid, ppv);
}
HRESULT CUpdateRunner::ShellExecuteFromExplorer(LPWSTR pszFile, LPWSTR pszParameters)
{
HRESULT hr;
CComPtr<IShellFolderViewDual> spFolderView;
hr = GetDesktopAutomationObject(IID_PPV_ARGS(&spFolderView));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispShell;
hr = spFolderView->get_Application(&spdispShell);
if (FAILED(hr)) return hr;
return CComQIPtr<IShellDispatch2>(spdispShell)->ShellExecute(
CComBSTR(pszFile),
CComVariant(pszParameters ? pszParameters : L""),
CComVariant(L""),
CComVariant(L""),
CComVariant(SW_SHOWDEFAULT));
}
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir)
{
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
CResource zipResource;
wchar_t targetDir[MAX_PATH];
wchar_t logFile[MAX_PATH];
std::vector<CString> to_delete;
if (wcsstr(lpCommandLine, L"--allUsers"))
{
// Bloom addition: install directly in program files(x86). Note that this automatically reverts to simply Program Files on a Win32 machine.
SHGetFolderPath(NULL, CSIDL_PROGRAM_FILESX86, NULL, SHGFP_TYPE_CURRENT, targetDir); // if need be try CSIDL_COMMON_APPDATA
}
else if (!useFallbackDir) {
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir);
} else {
wchar_t username[512];
wchar_t appDataDir[MAX_PATH];
ULONG unameSize = _countof(username);
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir);
GetUserName(username, &unameSize);
DWORD lastError = GetLastError();
_swprintf_c(targetDir, _countof(targetDir), L"%s\\%s", appDataDir, username);
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
DisplayErrorMessage(CString(err), NULL);
return -1;
}
}
wcscat_s(targetDir, _countof(targetDir), L"\\SquirrelTemp");
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
if (useFallbackDir) {
DisplayErrorMessage(CString(err), NULL);
}
goto failedExtract;
}
swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);
if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
goto failedExtract;
}
DWORD dwSize = zipResource.GetSize();
if (dwSize < 0x100) {
goto failedExtract;
}
BYTE* pData = (BYTE*)zipResource.Lock();
HZIP zipFile = OpenZip(pData, dwSize, NULL);
SetUnzipBaseDir(zipFile, targetDir);
// NB: This library is kind of a disaster
ZRESULT zr;
int index = 0;
do {
ZIPENTRY zentry;
wchar_t targetFile[MAX_PATH];
zr = GetZipItem(zipFile, index, &zentry);
if (zr != ZR_OK && zr != ZR_MORE) {
break;
}
// NB: UnzipItem won't overwrite data, we need to do it ourselves
swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
DeleteFile(targetFile);
if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
to_delete.push_back(CString(targetFile));
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
// nfi if the zip extract actually worked, check for Update.exe
wchar_t updateExePath[MAX_PATH];
swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");
if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
goto failedExtract;
}
// Run Update.exe
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW;
if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
lpCommandLine = L"";
}
wchar_t cmd[MAX_PATH];
swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine);
if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
goto failedExtract;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD dwExitCode;
if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
dwExitCode = (DWORD)-1;
}
if (dwExitCode != 0) {
DisplayErrorMessage(CString(
L"There was an error while installing the application. "
L"Check the setup log for more information and contact the author."), logFile);
}
for (unsigned int i = 0; i < to_delete.size(); i++) {
DeleteFile(to_delete[i]);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return (int) dwExitCode;
failedExtract:
if (!useFallbackDir) {
// Take another pass at it, using C:\ProgramData instead
return ExtractUpdaterAndRun(lpCommandLine, true);
}
DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
return (int) dwExitCode;
}<commit_msg>Display message when install complete<commit_after>#include "stdafx.h"
#include "unzip.h"
#include "Resource.h"
#include "UpdateRunner.h"
#include <vector>
void CUpdateRunner::DisplayErrorMessage(CString& errorMessage, wchar_t* logFile)
{
CTaskDialog dlg;
TASKDIALOG_BUTTON buttons[] = {
{ 1, L"Open Setup Log", },
{ 2, L"Close", },
};
// TODO: Something about contacting support?
if (logFile == NULL) {
dlg.SetButtons(&buttons[1], 1, 1);
} else {
dlg.SetButtons(buttons, 2, 1);
}
dlg.SetMainInstructionText(L"Installation has failed");
dlg.SetContentText(errorMessage);
dlg.SetMainIcon(TD_ERROR_ICON);
int nButton;
if (FAILED(dlg.DoModal(::GetActiveWindow(), &nButton))) {
return;
}
if (nButton == 1 && logFile != NULL) {
ShellExecute(NULL, NULL, logFile, NULL, NULL, SW_SHOW);
}
}
HRESULT CUpdateRunner::AreWeUACElevated()
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken = 0;
HRESULT hr;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
TOKEN_ELEVATION_TYPE elevType;
DWORD dontcare;
if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(TOKEN_ELEVATION_TYPE), &dontcare)) {
hr = HRESULT_FROM_WIN32(GetLastError());
goto out;
}
hr = (elevType == TokenElevationTypeFull ? S_OK : S_FALSE);
out:
if (hToken) {
CloseHandle(hToken);
}
return hr;
}
HRESULT FindDesktopFolderView(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellWindows> spShellWindows;
spShellWindows.CoCreateInstance(CLSID_ShellWindows);
CComVariant vtLoc(CSIDL_DESKTOP);
CComVariant vtEmpty;
long lhwnd;
CComPtr<IDispatch> spdisp;
hr = spShellWindows->FindWindowSW(
&vtLoc, &vtEmpty,
SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp);
if (FAILED(hr)) return hr;
CComPtr<IShellBrowser> spBrowser;
hr = CComQIPtr<IServiceProvider>(spdisp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser));
if (FAILED(hr)) return hr;
CComPtr<IShellView> spView;
hr = spBrowser->QueryActiveShellView(&spView);
if (FAILED(hr)) return hr;
hr = spView->QueryInterface(riid, ppv);
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT GetDesktopAutomationObject(REFIID riid, void **ppv)
{
HRESULT hr;
CComPtr<IShellView> spsv;
hr = FindDesktopFolderView(IID_PPV_ARGS(&spsv));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispView;
hr = spsv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spdispView));
if (FAILED(hr)) return hr;
return spdispView->QueryInterface(riid, ppv);
}
HRESULT CUpdateRunner::ShellExecuteFromExplorer(LPWSTR pszFile, LPWSTR pszParameters)
{
HRESULT hr;
CComPtr<IShellFolderViewDual> spFolderView;
hr = GetDesktopAutomationObject(IID_PPV_ARGS(&spFolderView));
if (FAILED(hr)) return hr;
CComPtr<IDispatch> spdispShell;
hr = spFolderView->get_Application(&spdispShell);
if (FAILED(hr)) return hr;
return CComQIPtr<IShellDispatch2>(spdispShell)->ShellExecute(
CComBSTR(pszFile),
CComVariant(pszParameters ? pszParameters : L""),
CComVariant(L""),
CComVariant(L""),
CComVariant(SW_SHOWDEFAULT));
}
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir)
{
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
CResource zipResource;
wchar_t targetDir[MAX_PATH];
wchar_t logFile[MAX_PATH];
std::vector<CString> to_delete;
if (wcsstr(lpCommandLine, L"--allUsers"))
{
// Bloom addition: install directly in program files(x86). Note that this automatically reverts to simply Program Files on a Win32 machine.
SHGetFolderPath(NULL, CSIDL_PROGRAM_FILESX86, NULL, SHGFP_TYPE_CURRENT, targetDir); // if need be try CSIDL_COMMON_APPDATA
}
else if (!useFallbackDir) {
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir);
} else {
wchar_t username[512];
wchar_t appDataDir[MAX_PATH];
ULONG unameSize = _countof(username);
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir);
GetUserName(username, &unameSize);
DWORD lastError = GetLastError();
_swprintf_c(targetDir, _countof(targetDir), L"%s\\%s", appDataDir, username);
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
DisplayErrorMessage(CString(err), NULL);
return -1;
}
}
wcscat_s(targetDir, _countof(targetDir), L"\\SquirrelTemp");
if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
wchar_t err[4096];
_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
if (useFallbackDir) {
DisplayErrorMessage(CString(err), NULL);
}
goto failedExtract;
}
swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);
if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
goto failedExtract;
}
DWORD dwSize = zipResource.GetSize();
if (dwSize < 0x100) {
goto failedExtract;
}
BYTE* pData = (BYTE*)zipResource.Lock();
HZIP zipFile = OpenZip(pData, dwSize, NULL);
SetUnzipBaseDir(zipFile, targetDir);
// NB: This library is kind of a disaster
ZRESULT zr;
int index = 0;
do {
ZIPENTRY zentry;
wchar_t targetFile[MAX_PATH];
zr = GetZipItem(zipFile, index, &zentry);
if (zr != ZR_OK && zr != ZR_MORE) {
break;
}
// NB: UnzipItem won't overwrite data, we need to do it ourselves
swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
DeleteFile(targetFile);
if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
to_delete.push_back(CString(targetFile));
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
// nfi if the zip extract actually worked, check for Update.exe
wchar_t updateExePath[MAX_PATH];
swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");
if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
goto failedExtract;
}
// Run Update.exe
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW;
if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
lpCommandLine = L"";
}
wchar_t cmd[MAX_PATH];
swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine);
if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
goto failedExtract;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD dwExitCode;
if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
dwExitCode = (DWORD)-1;
}
if (dwExitCode != 0) {
DisplayErrorMessage(CString(
L"There was an error while installing the application. "
L"Check the setup log for more information and contact the author."), logFile);
}
for (unsigned int i = 0; i < to_delete.size(); i++) {
DeleteFile(to_delete[i]);
}
if (!wcsstr(lpCommandLine, L"-s")) // also covers --silent
{
MessageBox(0L, L"Installation of Bloom succeeded", L"Finished", 0);
//std::cout << L"Installation succeeded\n"; // doesn't work, command seems to be finished in DOS box before we get here
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return (int) dwExitCode;
failedExtract:
if (!useFallbackDir) {
// Take another pass at it, using C:\ProgramData instead
return ExtractUpdaterAndRun(lpCommandLine, true);
}
DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
return (int) dwExitCode;
}<|endoftext|> |
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* Project */
#include "../include/stateval/StateMachineThread.h"
#include "../include/stateval/StateMachine.h"
/* STD */
#include <iostream>
#include <string>
#include <map>
#include <cassert>
using namespace std;
StateMachineThread::StateMachineThread (StateMachine &sm)
: Thread()
, mEventMutex()
, mEventsInQueue()
, mSM(&sm)
, mSignalList()
, mSignalBroadcast()
{
}
StateMachineThread::~StateMachineThread ()
{
cout << "~StateMachineThread" << endl;
cancel ();
join ();
}
void StateMachineThread::start ()
{
cout << "+StateMachineThread::start ()" << endl;
Thread::start();
cout << "-StateMachineThread::start ()" << endl;
}
void StateMachineThread::signal_cancel() // from thread
{
mEventsInQueue.signal ();
}
void StateMachineThread::run ()
{
cout << "StateMachineThread::running" << endl;
while (isRunning())
{
cout << "StateMachineThread::running while" << endl;
mEventMutex.lock ();
if (mSM->eventQueue.empty())
{
mEventsInQueue.wait (mEventMutex);
}
else
{
int event = mSM->eventQueue.front();
mEventMutex.unlock ();
cout << "EventQueue size: " << mSM->eventQueue.size () << endl;
mSM->evaluateState (event);
// pop element after working
cout << "EventQueue size: " << mSM->eventQueue.size () << endl;
cout << "pop element" << endl;
cout << endl;
// emit event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// emit also multible signals...
for ( ; findResult != lastElement; ++findResult)
{
cout << "call event '" << event << "' to app" << endl;
SignalSignal *signal = (*findResult).second;
signal->emit (event);
}
}
// emit the signal broadcast
// this is e.g. usefull to dispatch signals to another thread
mSignalBroadcast.emit (event);
mEventMutex.lock ();
mSM->popEvent ();
}
mEventMutex.unlock ();
cout << "StateMachineThread running in the background..." << endl;
}
}
void StateMachineThread::pushEvent (int event)
{
mEventMutex.lock ();
mSM->pushEvent (event);
mEventMutex.unlock ();
mEventsInQueue.signal ();
}
void StateMachineThread::pushEvent (const std::string &event)
{
pushEvent (mSM->findMapingEvent (event));
}
void StateMachineThread::connect (int event, const SignalSlot& slot)
{
SignalSignal* signal = new SignalSignal();
mSignalList.insert (pair <int, SignalSignal*> (event, signal));
signal->connect (slot);
}
void StateMachineThread::connect (const SignalSlot& slot)
{
mSignalBroadcast.connect (slot);
}
void StateMachineThread::disconnect (int event)
{
// delete event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// delete all connected handlers
for ( ; findResult != lastElement; ++findResult)
{
SignalSignal *signal = (*findResult).second;
delete signal;
}
}
}
void StateMachineThread::disconnectAll ()
{
for (std::multimap <int, SignalSignal*>::iterator s_it = mSignalList.begin ();
s_it != mSignalList.end ();
++s_it)
{
int event = (*s_it).first;
SignalSignal *signal = (*s_it).second;
delete signal;
}
}
<commit_msg>changed: Added TODO comment and possible error in dtor.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* Project */
#include "../include/stateval/StateMachineThread.h"
#include "../include/stateval/StateMachine.h"
/* STD */
#include <iostream>
#include <string>
#include <map>
#include <cassert>
using namespace std;
StateMachineThread::StateMachineThread (StateMachine &sm)
: Thread()
, mEventMutex()
, mEventsInQueue()
, mSM(&sm)
, mSignalList()
, mSignalBroadcast()
{
}
StateMachineThread::~StateMachineThread ()
{
cout << "~StateMachineThread" << endl;
cancel ();
}
void StateMachineThread::start ()
{
cout << "+StateMachineThread::start ()" << endl;
Thread::start();
cout << "-StateMachineThread::start ()" << endl;
}
void StateMachineThread::signal_cancel() // from thread
{
mEventsInQueue.signal ();
}
void StateMachineThread::run ()
{
cout << "StateMachineThread::running" << endl;
while (isRunning())
{
cout << "StateMachineThread::running while" << endl;
mEventMutex.lock ();
if (mSM->eventQueue.empty())
{
mEventsInQueue.wait (mEventMutex);
}
else
{
int event = mSM->eventQueue.front();
mEventMutex.unlock ();
cout << "EventQueue size: " << mSM->eventQueue.size () << endl;
mSM->evaluateState (event);
// pop element after working
cout << "EventQueue size: " << mSM->eventQueue.size () << endl;
cout << "pop element" << endl;
cout << endl;
// emit event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// emit also multible signals...
for ( ; findResult != lastElement; ++findResult)
{
cout << "call event '" << event << "' to app" << endl;
SignalSignal *signal = (*findResult).second;
signal->emit (event);
}
}
// emit the signal broadcast
// this is e.g. usefull to dispatch signals to another thread
mSignalBroadcast.emit (event);
mEventMutex.lock ();
mSM->popEvent ();
}
mEventMutex.unlock ();
cout << "StateMachineThread running in the background..." << endl;
}
}
void StateMachineThread::pushEvent (int event)
{
mEventMutex.lock ();
mSM->pushEvent (event);
mEventMutex.unlock ();
mEventsInQueue.signal ();
}
void StateMachineThread::pushEvent (const std::string &event)
{
pushEvent (mSM->findMapingEvent (event));
}
void StateMachineThread::connect (int event, const SignalSlot& slot)
{
SignalSignal* signal = new SignalSignal();
mSignalList.insert (pair <int, SignalSignal*> (event, signal));
signal->connect (slot);
}
void StateMachineThread::connect (const SignalSlot& slot)
{
mSignalBroadcast.connect (slot);
}
void StateMachineThread::disconnect (int event)
{
// delete event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// delete all connected handlers
for ( ; findResult != lastElement; ++findResult)
{
SignalSignal *signal = (*findResult).second;
delete signal;
// TODO from hdusel: Forget to remove the element from the multimap?
// Discuss this with Andreas.
}
}
}
void StateMachineThread::disconnectAll ()
{
for (std::multimap <int, SignalSignal*>::iterator s_it = mSignalList.begin ();
s_it != mSignalList.end ();
++s_it)
{
int event = (*s_it).first;
SignalSignal *signal = (*s_it).second;
delete signal;
}
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// appleseed.cli headers.
#include "commandline.h"
#include "superlogger.h"
// appleseed.shared headers.
#include "application/application.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/rendering.h"
#include "renderer/api/utility.h"
// appleseed.foundation headers.
#include "foundation/platform/path.h"
#include "foundation/platform/timer.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/benchmark.h"
#include "foundation/utility/filter.h"
#include "foundation/utility/log.h"
#include "foundation/utility/settings.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
#include "foundation/utility/test.h"
// boost headers.
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
// Standard headers.
#include <cstddef>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
using namespace appleseed::cli;
using namespace appleseed::shared;
using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;
namespace
{
CommandLine g_cl;
ParamArray g_settings;
void load_settings(Logger& logger)
{
const filesystem::path root_path(Application::get_root_path());
const filesystem::path settings_file_path = root_path / "settings/appleseed.cli.xml";
const filesystem::path schema_file_path = root_path / "schemas/settings.xsd";
SettingsFileReader reader(logger);
reader.read(
settings_file_path.file_string().c_str(),
schema_file_path.file_string().c_str(),
g_settings);
}
template <typename Result>
void print_suite_case_result(Logger& logger, const Result& result)
{
const size_t suite_exec = result.get_suite_execution_count();
const size_t suite_fail = result.get_suite_failure_count();
const size_t case_exec = result.get_case_execution_count();
const size_t case_fail = result.get_case_failure_count();
LOG_INFO(
logger,
" suites : %s executed, %s failed (%s)\n"
" cases : %s executed, %s failed (%s)\n",
pretty_uint(suite_exec).c_str(),
pretty_uint(suite_fail).c_str(),
pretty_percent(suite_fail, suite_exec).c_str(),
pretty_uint(case_exec).c_str(),
pretty_uint(case_fail).c_str(),
pretty_percent(case_fail, case_exec).c_str());
}
void print_unit_test_result(Logger& logger, const TestResult& result)
{
LOG_INFO(logger, "unit testing summary:\n");
print_suite_case_result(logger, result);
const size_t assert_exec = result.get_assertion_execution_count();
const size_t assert_fail = result.get_assertion_failure_count();
LOG_INFO(
logger,
" assertions : %s executed, %s failed (%s)\n",
pretty_uint(assert_exec).c_str(),
pretty_uint(assert_fail).c_str(),
pretty_percent(assert_fail, assert_exec).c_str());
}
void print_unit_benchmark_result(Logger& logger, const BenchmarkResult& result)
{
LOG_INFO(logger, "unit benchmarking summary:\n");
print_suite_case_result(logger, result);
}
// Run unit tests.
void run_unit_tests(Logger& logger)
{
// Create a test listener that outputs to the logger.
auto_release_ptr<ITestListener> listener(
create_logger_test_listener(
logger,
g_cl.m_verbose_unit_tests.found()));
TestResult result;
const filesystem::path old_current_path =
Application::change_current_directory_to_tests_root_path();
// Run test suites.
if (g_cl.m_run_unit_tests.values().empty())
TestSuiteRepository::instance().run(listener.ref(), result);
else
{
const char* regex = g_cl.m_run_unit_tests.values().front().c_str();
const RegExFilter filter(regex, RegExFilter::CaseInsensitive);
if (filter.is_valid())
TestSuiteRepository::instance().run(filter, listener.ref(), result);
else
{
LOG_ERROR(
logger,
"malformed regular expression '%s', disabling test filtering",
regex);
TestSuiteRepository::instance().run(listener.ref(), result);
}
}
// Restore the current directory.
filesystem::current_path(old_current_path);
print_unit_test_result(logger, result);
}
// Run unit benchmarks.
void run_unit_benchmarks(Logger& logger)
{
BenchmarkResult result;
// Add a benchmark listener that outputs to the logger.
auto_release_ptr<IBenchmarkListener>
logger_listener(create_logger_benchmark_listener(logger));
result.add_listener(logger_listener.get());
// Try to add a benchmark listener that outputs to a XML file.
auto_release_ptr<XMLFileBenchmarkListener> xmlfile_listener(
create_xmlfile_benchmark_listener());
const string xmlfile_name = "benchmark." + get_time_stamp_string() + ".xml";
const filesystem::path xmlfile_path =
filesystem::path(Application::get_tests_root_path())
/ "benchmarks/"
/ xmlfile_name;
if (xmlfile_listener->open(xmlfile_path.string().c_str()))
result.add_listener(xmlfile_listener.get());
else
{
RENDERER_LOG_WARNING(
"automatic benchmark results archiving to %s failed: i/o error",
xmlfile_path.string().c_str());
}
const filesystem::path old_current_path =
Application::change_current_directory_to_tests_root_path();
// Run benchmark suites.
if (g_cl.m_run_unit_benchmarks.values().empty())
BenchmarkSuiteRepository::instance().run(result);
else
{
const char* regex = g_cl.m_run_unit_benchmarks.values().front().c_str();
const RegExFilter filter(regex, RegExFilter::CaseInsensitive);
if (filter.is_valid())
BenchmarkSuiteRepository::instance().run(filter, result);
else
{
LOG_ERROR(
logger,
"malformed regular expression '%s', disabling benchmark filtering",
regex);
BenchmarkSuiteRepository::instance().run(result);
}
}
// Restore the current directory.
filesystem::current_path(old_current_path);
// Print results.
print_unit_benchmark_result(logger, result);
}
// Apply command line options to a given project.
void apply_command_line_options(ParamArray& params)
{
// Apply rendering threads option.
if (g_cl.m_rendering_threads.found())
{
params.insert(
"generic_frame_renderer.rendering_threads",
g_cl.m_rendering_threads.string_values()[0].c_str());
}
// Apply window option.
if (g_cl.m_window.found())
{
const string window =
g_cl.m_window.string_values()[0] + ' ' +
g_cl.m_window.string_values()[1] + ' ' +
g_cl.m_window.string_values()[2] + ' ' +
g_cl.m_window.string_values()[3];
params.insert("generic_tile_renderer.crop_window", window);
}
// Apply samples option.
if (g_cl.m_samples.found())
{
params.insert(
"generic_tile_renderer.min_samples",
g_cl.m_samples.string_values()[0].c_str());
params.insert(
"generic_tile_renderer.max_samples",
g_cl.m_samples.string_values()[1].c_str());
}
// Apply shading override option.
if (g_cl.m_override_shading.found())
{
params.insert(
"shading_engine.override_shading.mode",
g_cl.m_override_shading.string_values()[0].c_str());
}
// Apply custom parameters.
for (size_t i = 0; i < g_cl.m_params.values().size(); ++i)
{
// Retrieve the assignment string (of the form name=value).
const string& s = g_cl.m_params.values()[i];
// Retrieve the name and the value of the parameter.
const string::size_type equal_pos = s.find_first_of('=');
const string path = s.substr(0, equal_pos);
const string value = s.substr(equal_pos + 1);
// Insert the parameter.
params.insert_path(path, value);
}
}
void apply_resolution_command_line_option(Project* project)
{
const Frame* frame = project->get_frame();
assert(frame);
const string frame_name = frame->get_name();
ParamArray frame_params = frame->get_parameters();
if (g_cl.m_resolution.found())
{
const string resolution =
g_cl.m_resolution.string_values()[0] + ' ' +
g_cl.m_resolution.string_values()[1];
frame_params.insert("resolution", resolution);
}
auto_ptr<Frame> new_frame(
new Frame(frame_name.c_str(), frame_params));
project->set_frame(new_frame);
}
#if defined __APPLE__ || defined _WIN32
// Invoke a system command to open an image file.
void display_frame(const string& path)
{
const string quoted_path = "\"" + path + "\"";
#if defined __APPLE__
const string command = "open " + quoted_path;
#elif defined _WIN32
const string command = quoted_path;
#else
#error Unsupported platform.
#endif
RENDERER_LOG_DEBUG("executing '%s'", command.c_str());
std::system(command.c_str()); // needs std:: qualifier
}
#endif
// Render one frame of a given project.
void render_frame(
Project& project,
const ParamArray& params)
{
RENDERER_LOG_INFO("rendering frame...");
// Create the master renderer.
DefaultRendererController renderer_controller;
MasterRenderer renderer(
project,
params,
&renderer_controller);
// Render the frame.
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
renderer.render();
stopwatch.measure();
// Print rendering time.
const double seconds = stopwatch.get_seconds();
RENDERER_LOG_INFO(
"rendering finished in %s",
pretty_time(seconds, 3).c_str());
// Construct the path to the archive directory.
const filesystem::path autosave_path =
filesystem::path(Application::get_root_path())
/ "images/autosave/";
// Archive the frame to disk.
RENDERER_LOG_INFO("archiving frame to disk...");
char* archive_path;
project.get_frame()->archive(
autosave_path.directory_string().c_str(),
&archive_path);
// Write the frame to disk.
if (g_cl.m_output.found())
{
RENDERER_LOG_INFO("writing frame to disk...");
project.get_frame()->write(g_cl.m_output.values()[0].c_str());
}
#if defined __APPLE__ || defined _WIN32
// Display the output image.
if (g_cl.m_display_output.found())
display_frame(archive_path);
#endif
// Deallocate the memory used by the path to the archived image.
free_string(archive_path);
}
// Render a given project.
void render_project(const string& project_filename)
{
auto_release_ptr<Project> project;
const string builtin_prefix = "builtin:";
if (project_filename.substr(0, builtin_prefix.size()) == builtin_prefix)
{
// Load the built-in project.
ProjectFileReader reader;
const string name = project_filename.substr(builtin_prefix.size());
project = reader.load_builtin(name.c_str());
}
else
{
// Construct the schema filename.
const filesystem::path schema_path =
filesystem::path(Application::get_root_path())
/ "schemas/project.xsd";
// Load the project from disk.
ProjectFileReader reader;
project =
reader.read(
project_filename.c_str(),
schema_path.file_string().c_str());
}
// Skip this project if loading failed.
if (project.get() == 0)
return;
// Retrieve the name of the configuration to use.
const string config_name = g_cl.m_configuration.found()
? g_cl.m_configuration.values()[0]
: "final";
// Retrieve the configuration.
const Configuration* configuration =
project->configurations().get(config_name.c_str());
if (configuration == 0)
{
RENDERER_LOG_ERROR(
"the configuration \"%s\" does not exist",
config_name.c_str());
return;
}
// Retrieve the parameters from the configuration.
ParamArray params;
if (configuration->get_base())
params = configuration->get_base()->get_parameters();
params.merge(g_settings);
params.merge(configuration->get_parameters());
// Apply command line options.
apply_command_line_options(params);
apply_resolution_command_line_option(project.get());
// Render one frame of the project.
render_frame(*project, params);
}
}
//
// Entry point of appleseed.cli.
//
int main(int argc, const char* argv[])
{
SuperLogger logger;
logger.get_log_target().set_formatting_flags(LogMessage::DisplayMessage);
// Make sure the application is properly installed, bail out if not.
Application::check_installation(logger);
// Parse the command line.
g_cl.parse(argc, argv, logger);
// Read the application's settings from disk.
load_settings(logger);
if (g_settings.get_optional<bool>("message_coloring", false))
logger.enable_message_coloring();
// Run unit tests.
if (g_cl.m_run_unit_tests.found())
run_unit_tests(logger);
// Run unit benchmarks.
if (g_cl.m_run_unit_benchmarks.found())
run_unit_benchmarks(logger);
logger.get_log_target().reset_formatting_flags();
global_logger().add_target(&logger.get_log_target());
// Render the specified project.
if (!g_cl.m_filenames.values().empty())
render_project(g_cl.m_filenames.values().front());
return 0;
}
<commit_msg>don't recreate the frame if there's no need to.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// 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.
//
// appleseed.cli headers.
#include "commandline.h"
#include "superlogger.h"
// appleseed.shared headers.
#include "application/application.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/rendering.h"
#include "renderer/api/utility.h"
// appleseed.foundation headers.
#include "foundation/platform/path.h"
#include "foundation/platform/timer.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/benchmark.h"
#include "foundation/utility/filter.h"
#include "foundation/utility/log.h"
#include "foundation/utility/settings.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
#include "foundation/utility/test.h"
// boost headers.
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
// Standard headers.
#include <cstddef>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
using namespace appleseed::cli;
using namespace appleseed::shared;
using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;
namespace
{
CommandLine g_cl;
ParamArray g_settings;
void load_settings(Logger& logger)
{
const filesystem::path root_path(Application::get_root_path());
const filesystem::path settings_file_path = root_path / "settings/appleseed.cli.xml";
const filesystem::path schema_file_path = root_path / "schemas/settings.xsd";
SettingsFileReader reader(logger);
reader.read(
settings_file_path.file_string().c_str(),
schema_file_path.file_string().c_str(),
g_settings);
}
template <typename Result>
void print_suite_case_result(Logger& logger, const Result& result)
{
const size_t suite_exec = result.get_suite_execution_count();
const size_t suite_fail = result.get_suite_failure_count();
const size_t case_exec = result.get_case_execution_count();
const size_t case_fail = result.get_case_failure_count();
LOG_INFO(
logger,
" suites : %s executed, %s failed (%s)\n"
" cases : %s executed, %s failed (%s)\n",
pretty_uint(suite_exec).c_str(),
pretty_uint(suite_fail).c_str(),
pretty_percent(suite_fail, suite_exec).c_str(),
pretty_uint(case_exec).c_str(),
pretty_uint(case_fail).c_str(),
pretty_percent(case_fail, case_exec).c_str());
}
void print_unit_test_result(Logger& logger, const TestResult& result)
{
LOG_INFO(logger, "unit testing summary:\n");
print_suite_case_result(logger, result);
const size_t assert_exec = result.get_assertion_execution_count();
const size_t assert_fail = result.get_assertion_failure_count();
LOG_INFO(
logger,
" assertions : %s executed, %s failed (%s)\n",
pretty_uint(assert_exec).c_str(),
pretty_uint(assert_fail).c_str(),
pretty_percent(assert_fail, assert_exec).c_str());
}
void print_unit_benchmark_result(Logger& logger, const BenchmarkResult& result)
{
LOG_INFO(logger, "unit benchmarking summary:\n");
print_suite_case_result(logger, result);
}
// Run unit tests.
void run_unit_tests(Logger& logger)
{
// Create a test listener that outputs to the logger.
auto_release_ptr<ITestListener> listener(
create_logger_test_listener(
logger,
g_cl.m_verbose_unit_tests.found()));
TestResult result;
const filesystem::path old_current_path =
Application::change_current_directory_to_tests_root_path();
// Run test suites.
if (g_cl.m_run_unit_tests.values().empty())
TestSuiteRepository::instance().run(listener.ref(), result);
else
{
const char* regex = g_cl.m_run_unit_tests.values().front().c_str();
const RegExFilter filter(regex, RegExFilter::CaseInsensitive);
if (filter.is_valid())
TestSuiteRepository::instance().run(filter, listener.ref(), result);
else
{
LOG_ERROR(
logger,
"malformed regular expression '%s', disabling test filtering",
regex);
TestSuiteRepository::instance().run(listener.ref(), result);
}
}
// Restore the current directory.
filesystem::current_path(old_current_path);
print_unit_test_result(logger, result);
}
// Run unit benchmarks.
void run_unit_benchmarks(Logger& logger)
{
BenchmarkResult result;
// Add a benchmark listener that outputs to the logger.
auto_release_ptr<IBenchmarkListener>
logger_listener(create_logger_benchmark_listener(logger));
result.add_listener(logger_listener.get());
// Try to add a benchmark listener that outputs to a XML file.
auto_release_ptr<XMLFileBenchmarkListener> xmlfile_listener(
create_xmlfile_benchmark_listener());
const string xmlfile_name = "benchmark." + get_time_stamp_string() + ".xml";
const filesystem::path xmlfile_path =
filesystem::path(Application::get_tests_root_path())
/ "benchmarks/"
/ xmlfile_name;
if (xmlfile_listener->open(xmlfile_path.string().c_str()))
result.add_listener(xmlfile_listener.get());
else
{
RENDERER_LOG_WARNING(
"automatic benchmark results archiving to %s failed: i/o error",
xmlfile_path.string().c_str());
}
const filesystem::path old_current_path =
Application::change_current_directory_to_tests_root_path();
// Run benchmark suites.
if (g_cl.m_run_unit_benchmarks.values().empty())
BenchmarkSuiteRepository::instance().run(result);
else
{
const char* regex = g_cl.m_run_unit_benchmarks.values().front().c_str();
const RegExFilter filter(regex, RegExFilter::CaseInsensitive);
if (filter.is_valid())
BenchmarkSuiteRepository::instance().run(filter, result);
else
{
LOG_ERROR(
logger,
"malformed regular expression '%s', disabling benchmark filtering",
regex);
BenchmarkSuiteRepository::instance().run(result);
}
}
// Restore the current directory.
filesystem::current_path(old_current_path);
// Print results.
print_unit_benchmark_result(logger, result);
}
// Apply command line options to a given project.
void apply_command_line_options(ParamArray& params)
{
// Apply rendering threads option.
if (g_cl.m_rendering_threads.found())
{
params.insert(
"generic_frame_renderer.rendering_threads",
g_cl.m_rendering_threads.string_values()[0].c_str());
}
// Apply window option.
if (g_cl.m_window.found())
{
const string window =
g_cl.m_window.string_values()[0] + ' ' +
g_cl.m_window.string_values()[1] + ' ' +
g_cl.m_window.string_values()[2] + ' ' +
g_cl.m_window.string_values()[3];
params.insert("generic_tile_renderer.crop_window", window);
}
// Apply samples option.
if (g_cl.m_samples.found())
{
params.insert(
"generic_tile_renderer.min_samples",
g_cl.m_samples.string_values()[0].c_str());
params.insert(
"generic_tile_renderer.max_samples",
g_cl.m_samples.string_values()[1].c_str());
}
// Apply shading override option.
if (g_cl.m_override_shading.found())
{
params.insert(
"shading_engine.override_shading.mode",
g_cl.m_override_shading.string_values()[0].c_str());
}
// Apply custom parameters.
for (size_t i = 0; i < g_cl.m_params.values().size(); ++i)
{
// Retrieve the assignment string (of the form name=value).
const string& s = g_cl.m_params.values()[i];
// Retrieve the name and the value of the parameter.
const string::size_type equal_pos = s.find_first_of('=');
const string path = s.substr(0, equal_pos);
const string value = s.substr(equal_pos + 1);
// Insert the parameter.
params.insert_path(path, value);
}
}
void apply_resolution_command_line_option(Project* project)
{
if (g_cl.m_resolution.found())
{
const string resolution =
g_cl.m_resolution.string_values()[0] + ' ' +
g_cl.m_resolution.string_values()[1];
const Frame* frame = project->get_frame();
assert(frame);
ParamArray new_frame_params = frame->get_parameters();
new_frame_params.insert("resolution", resolution);
auto_ptr<Frame> new_frame(new Frame(frame->get_name(), new_frame_params));
project->set_frame(new_frame);
}
}
#if defined __APPLE__ || defined _WIN32
// Invoke a system command to open an image file.
void display_frame(const string& path)
{
const string quoted_path = "\"" + path + "\"";
#if defined __APPLE__
const string command = "open " + quoted_path;
#elif defined _WIN32
const string command = quoted_path;
#else
#error Unsupported platform.
#endif
RENDERER_LOG_DEBUG("executing '%s'", command.c_str());
std::system(command.c_str()); // needs std:: qualifier
}
#endif
// Render one frame of a given project.
void render_frame(
Project& project,
const ParamArray& params)
{
RENDERER_LOG_INFO("rendering frame...");
// Create the master renderer.
DefaultRendererController renderer_controller;
MasterRenderer renderer(
project,
params,
&renderer_controller);
// Render the frame.
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
renderer.render();
stopwatch.measure();
// Print rendering time.
const double seconds = stopwatch.get_seconds();
RENDERER_LOG_INFO(
"rendering finished in %s",
pretty_time(seconds, 3).c_str());
// Construct the path to the archive directory.
const filesystem::path autosave_path =
filesystem::path(Application::get_root_path())
/ "images/autosave/";
// Archive the frame to disk.
RENDERER_LOG_INFO("archiving frame to disk...");
char* archive_path;
project.get_frame()->archive(
autosave_path.directory_string().c_str(),
&archive_path);
// Write the frame to disk.
if (g_cl.m_output.found())
{
RENDERER_LOG_INFO("writing frame to disk...");
project.get_frame()->write(g_cl.m_output.values()[0].c_str());
}
#if defined __APPLE__ || defined _WIN32
// Display the output image.
if (g_cl.m_display_output.found())
display_frame(archive_path);
#endif
// Deallocate the memory used by the path to the archived image.
free_string(archive_path);
}
// Render a given project.
void render_project(const string& project_filename)
{
auto_release_ptr<Project> project;
const string builtin_prefix = "builtin:";
if (project_filename.substr(0, builtin_prefix.size()) == builtin_prefix)
{
// Load the built-in project.
ProjectFileReader reader;
const string name = project_filename.substr(builtin_prefix.size());
project = reader.load_builtin(name.c_str());
}
else
{
// Construct the schema filename.
const filesystem::path schema_path =
filesystem::path(Application::get_root_path())
/ "schemas/project.xsd";
// Load the project from disk.
ProjectFileReader reader;
project =
reader.read(
project_filename.c_str(),
schema_path.file_string().c_str());
}
// Skip this project if loading failed.
if (project.get() == 0)
return;
// Retrieve the name of the configuration to use.
const string config_name = g_cl.m_configuration.found()
? g_cl.m_configuration.values()[0]
: "final";
// Retrieve the configuration.
const Configuration* configuration =
project->configurations().get(config_name.c_str());
if (configuration == 0)
{
RENDERER_LOG_ERROR(
"the configuration \"%s\" does not exist",
config_name.c_str());
return;
}
// Retrieve the parameters from the configuration.
ParamArray params;
if (configuration->get_base())
params = configuration->get_base()->get_parameters();
params.merge(g_settings);
params.merge(configuration->get_parameters());
// Apply command line options.
apply_command_line_options(params);
apply_resolution_command_line_option(project.get());
// Render one frame of the project.
render_frame(*project, params);
}
}
//
// Entry point of appleseed.cli.
//
int main(int argc, const char* argv[])
{
SuperLogger logger;
logger.get_log_target().set_formatting_flags(LogMessage::DisplayMessage);
// Make sure the application is properly installed, bail out if not.
Application::check_installation(logger);
// Parse the command line.
g_cl.parse(argc, argv, logger);
// Read the application's settings from disk.
load_settings(logger);
if (g_settings.get_optional<bool>("message_coloring", false))
logger.enable_message_coloring();
// Run unit tests.
if (g_cl.m_run_unit_tests.found())
run_unit_tests(logger);
// Run unit benchmarks.
if (g_cl.m_run_unit_benchmarks.found())
run_unit_benchmarks(logger);
logger.get_log_target().reset_formatting_flags();
global_logger().add_target(&logger.get_log_target());
// Render the specified project.
if (!g_cl.m_filenames.values().empty())
render_project(g_cl.m_filenames.values().front());
return 0;
}
<|endoftext|> |
<commit_before>/********************************************************************** <BR>
This file is part of Crack dot Com's free source code release of
Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for
information about compiling & licensing issues visit this URL</a>
<PRE> If that doesn't help, contact Jonathan Clark at
golgotha_source@usa.net (Subject should have "GOLG" in it)
***********************************************************************/
#include "pch.h"
#include "area/rectlist.h"
#include "error/error.h"
#include "memory/malloc.h"
#include "error/error.h"
#include "init/init.h"
//#include <stdlib.h>
#ifndef max
#define max(x,y) (((x)>(y)) ? (x) : (y))
#define min(x,y) (((x)>(y)) ? (y) : (x))
#endif
i4_rect_list_class::area::area_allocator *i4_rect_list_class::area::area_alloc=0;
// this class is used to ensure area_alloc is created after the memory manager is installed
class area_allocator_initter : public i4_init_class
{
public :
virtual void init()
{
i4_rect_list_class::area::area_alloc=
new i4_linear_allocator(sizeof(i4_rect_list_class::area),0,300,"areas");
}
virtual void uninit()
{
delete i4_rect_list_class::area::area_alloc;
}
} ;
static area_allocator_initter instance;
void i4_rect_list_class::swap(i4_rect_list_class *other)
{
other->list.swap(list);
}
void i4_rect_list_class::remove_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2)
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end(),del;
for (;a!=list.end();)
{
if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2))
{
if (x2>=a->x2 && x1<=a->x1) // does it take a x slice off? (across)
{
if (y2>=a->y2 && y1<=a->y1)
{
del=a;
++a;
if (last!=list.end())
list.erase_after(last);
else
list.erase();
delete_area(&*del);
}
else if (y2>=a->y2)
{
a->y2=y1-1;
last=a;
++a;
}
else if (y1<=a->y1)
{
a->y1=y2+1;
last=a;
++a;
}
else
{
list.insert(*(new_area(a->x1,a->y1,a->x2,y1-1)));
a->y1=y2+1;
last=a;
++a;
}
}
else if (y2>=a->y2 && y1<=a->y1) // does it take a y slice off (down)
{
if (x2>=a->x2)
{
a->x2=x1-1;
last=a;
++a;
}
else if (x1<=a->x1)
{
a->x1=x2+1;
last=a;
++a;
}
else
{
list.insert(*(new_area(a->x1,a->y1,x1-1,a->y2)));
a->x1=x2+1;
last=a;
++a;
}
}
else // otherwise it just takes a little chunk off
{
i4_coord ax1,ay1,ax2,ay2;
del=a;
++a;
if (last!=list.end())
list.erase_after(last);
else
list.erase();
if (x2>=del->x2) { ax1=del->x1; ax2=x1-1; }
else if (x1<=del->x1) { ax1=x2+1; ax2=del->x2; }
else { ax1=del->x1; ax2=x1-1; }
if (y2>=del->y2) { ay1=y1; ay2=del->y2; }
else if (y1<=del->y1) { ay1=del->y1; ay2=y2; }
else { ay1=y1; ay2=y2; }
{
list.insert(*(new_area(ax1,ay1,ax2,ay2)));
if (a==list.end())
a=list.begin();
else if (last==list.end())
last=list.begin();
}
if (x2>=del->x2 || x1<=del->x1) { ax1=del->x1; ax2=del->x2; }
else { ax1=x2+1; ax2=del->x2; }
if (y2>=del->y2)
{ if (ax1==del->x1) { ay1=del->y1; ay2=y1-1; }
else { ay1=y1; ay2=del->y2; } }
else if (y1<=del->y1) { if (ax1==del->x1) { ay1=y2+1; ay2=del->y2; }
else { ay1=del->y1; ay2=y2; } }
else { if (ax1==del->x1) { ay1=del->y1; ay2=y1-1; }
else { ay1=y1; ay2=y2; } }
list.insert(*(new_area(ax1,ay1,ax2,ay2)));
if (a==list.end())
a=list.begin();
else if (last==list.end())
last=list.begin();
if (x1>del->x1 && x2<del->x2)
{
if (y1>del->y1 && y2<del->y2)
{
list.insert(*(new_area(del->x1,del->y1,del->x2,y1-1)));
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
} else if (y1<=del->y1)
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
else
list.insert(*(new_area(del->x1,del->y1,del->x2,y1-1)));
} else if (y1>del->y1 && y2<del->y2)
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
delete_area(&*del);
}
} else
{
last=a;
++a;
}
}
}
void i4_rect_list_class::add_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2,
i4_bool combine)
{
if (x1>x2 || y1>y2)
return ;
if (list.begin()==list.end())
list.insert(*(new_area(x1,y1,x2,y2)));
else
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end();
for (;a!=list.end();)
{
// check to see if this new rectangle completly encloses the check rectangle
if (x1<=a->x1 && y1<=a->y1 && x2>=a->x2 && y2>=a->y2)
{
if (last==list.end())
list.erase();
else list.erase_after(last);
i4_isl_list<area>::iterator q=a;
++a;
delete_area(&*q);
} else if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2)) // intersects another area?
{
if (x1<a->x1)
add_area(x1,(i4_coord) max(y1,a->y1),(sw16)(a->x1-1),(i4_coord) min(y2,a->y2));
if (x2>a->x2)
add_area(a->x2+1,(i4_coord) max(y1,a->y1),x2,(i4_coord) min(y2,a->y2));
if (y1<a->y1)
add_area(x1,y1,x2,a->y1-1);
if (y2>a->y2)
add_area(x1,a->y2+1,x2,y2);
return ;
}
else if (combine && a->x2+1==x1 && a->y1==y1 && a->y2==y2) // combines to the right
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->x2=x2;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->x1-1==x2 && a->y1==y1 && a->y2==y2) // combines to the left
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->x1=x1;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->y1-1==y2 && a->x1==x1 && a->x2==x2) // combines above
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->y1=y1;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->y2+1==y1 && a->x1==x1 && a->x2==x2) // combines below
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->y2=y2;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else
{
last=a;
++a;
}
}
list.insert(*(new_area(x1,y1,x2,y2)));
}
}
void i4_rect_list_class::intersect_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2) // reduces area list to that which intersects this area
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end(),next;
for (;a!=list.end();a=next)
{
next=a;
++next;
if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2))
{
if (x1>a->x1) a->x1=x1;
if (x2<a->x2) a->x2=x2;
if (y1>a->y1) a->y1=y1;
if (y2<a->y2) a->y2=y2;
last=a;
} else
{
if (a==list.begin())
list.erase();
else
list.erase_after(last);
delete_area(&*a);
}
}
}
// return i4_T if area is totally clipped away
// this can be used to skip expensive drawing operations
i4_bool i4_rect_list_class::clipped_away(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2)
{
i4_rect_list_class area_left(x1,y1,x2,y2);
i4_isl_list<area>::iterator a=list.begin();
for (;a!=list.end();++a)
area_left.remove_area(a->x1, a->y1, a->x2, a->y2);
return area_left.empty();
}
i4_rect_list_class::i4_rect_list_class(i4_rect_list_class *copy_from, i4_coord xoff, i4_coord yoff)
{
i4_isl_list<area>::iterator a=copy_from->list.begin(),last,q;
if (a!=copy_from->list.end())
{
last=new_area(a->x1+xoff,a->y1+yoff,a->x2+xoff,a->y2+yoff);
list.insert(*last);
++a;
while (a!=copy_from->list.end())
{
q=new_area(a->x1+xoff,a->y1+yoff,a->x2+xoff,a->y2+yoff);
list.insert_after(last,*q);
last=q;
++a;
}
}
}
void i4_rect_list_class::intersect_list(i4_rect_list_class *other) // reduces area list to that which intersects this area list
{
i4_rect_list_class intersection;
i4_isl_list<area>::iterator a,b;
for (b=other->list.begin();b!=other->list.end();++b)
{
for (a=list.begin();a!=list.end();++a)
{
if (!(b->x2<a->x1 || b->y2<a->y1 || b->x1>a->x2 || b->y1>a->y2))
{
i4_coord x1,y1,x2,y2;
if (b->x1>a->x1) x1=b->x1; else x1=a->x1;
if (b->x2<a->x2) x2=b->x2; else x2=a->x2;
if (b->y1>a->y1) y1=b->y1; else y1=a->y1;
if (b->y2<a->y2) y2=b->y2; else y2=a->y2;
intersection.list.insert(*(new_area(x1,y1,x2,y2)));
}
}
}
intersection.list.swap(list);
}
void i4_rect_list_class::inspect(int print)
{
for (i4_isl_list<area>::iterator a=list.begin(); a!=list.end(); ++a)
{
if (print)
i4_warning("(%d %d %d %d (%d x %d)", a->x1, a->y1, a->x2, a->y2,
a->x2-a->x1+1, a->y2-a->y1+1);
}
}
<commit_msg>- Documentation updates and reformating for easier reading.<commit_after>/********************************************************************** <BR>
This file is part of Crack dot Com's free source code release of
Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for
information about compiling & licensing issues visit this URL</a>
<PRE> If that doesn't help, contact Jonathan Clark at
golgotha_source@usa.net (Subject should have "GOLG" in it)
***********************************************************************/
#include "pch.h"
#include "area/rectlist.h"
#include "error/error.h"
#include "memory/malloc.h"
#include "error/error.h"
#include "init/init.h"
//#include <stdlib.h>
#ifndef max
#define max(x,y) (((x)>(y)) ? (x) : (y))
#define min(x,y) (((x)>(y)) ? (y) : (x))
#endif
i4_rect_list_class::area::area_allocator *i4_rect_list_class::area::area_alloc=0;
//! This class is used to ensure area_alloc is created after the memory manager is installed.
class area_allocator_initter : public i4_init_class
{
public :
virtual void init()
{
i4_rect_list_class::area::area_alloc=
new i4_linear_allocator(sizeof(i4_rect_list_class::area),0,300,"areas");
}
virtual void uninit()
{
delete i4_rect_list_class::area::area_alloc;
}
} ;
static area_allocator_initter instance;
void i4_rect_list_class::swap(i4_rect_list_class *other)
{
other->list.swap(list);
}
void i4_rect_list_class::remove_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2)
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end(),del;
for (;a!=list.end();)
{
if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2))
{
if (x2>=a->x2 && x1<=a->x1) // does it take a x slice off? (across)
{
if (y2>=a->y2 && y1<=a->y1)
{
del=a;
++a;
if (last!=list.end())
list.erase_after(last);
else
list.erase();
delete_area(&*del);
}
else if (y2>=a->y2)
{
a->y2=y1-1;
last=a;
++a;
}
else if (y1<=a->y1)
{
a->y1=y2+1;
last=a;
++a;
}
else
{
list.insert(*(new_area(a->x1,a->y1,a->x2,y1-1)));
a->y1=y2+1;
last=a;
++a;
}
}
else if (y2>=a->y2 && y1<=a->y1) // does it take a y slice off (down)
{
if (x2>=a->x2)
{
a->x2=x1-1;
last=a;
++a;
}
else if (x1<=a->x1)
{
a->x1=x2+1;
last=a;
++a;
}
else
{
list.insert(*(new_area(a->x1,a->y1,x1-1,a->y2)));
a->x1=x2+1;
last=a;
++a;
}
}
else // otherwise it just takes a little chunk off
{
i4_coord ax1,ay1,ax2,ay2;
del=a;
++a;
if (last!=list.end())
{
list.erase_after(last);
}
else
{
list.erase();
}
if (x2>=del->x2)
{
ax1=del->x1;
ax2=x1-1;
}
else if (x1<=del->x1)
{
ax1=x2+1;
ax2=del->x2;
}
else
{
ax1=del->x1;
ax2=x1-1;
}
if (y2>=del->y2)
{
ay1=y1;
ay2=del->y2;
}
else if (y1<=del->y1)
{
ay1=del->y1;
ay2=y2;
}
else
{
ay1=y1;
ay2=y2;
}
{
list.insert(*(new_area(ax1,ay1,ax2,ay2)));
if (a==list.end())
a=list.begin();
else if (last==list.end())
last=list.begin();
}
if (x2>=del->x2 || x1<=del->x1)
{
ax1=del->x1;
ax2=del->x2;
}
else
{
ax1=x2+1;
ax2=del->x2;
}
if (y2>=del->y2)
{
if (ax1==del->x1)
{
ay1=del->y1;
ay2=y1-1;
}
else
{
ay1=y1;
ay2=del->y2;
}
}
else if (y1<=del->y1)
{
if (ax1==del->x1)
{
ay1=y2+1;
ay2=del->y2;
}
else
{
ay1=del->y1;
ay2=y2;
}
}
else
{
if (ax1==del->x1)
{
ay1=del->y1;
ay2=y1-1;
}
else
{
ay1=y1;
ay2=y2;
}
}
list.insert(*(new_area(ax1,ay1,ax2,ay2)));
if (a==list.end())
a=list.begin();
else if (last==list.end())
last=list.begin();
if (x1>del->x1 && x2<del->x2)
{
if (y1>del->y1 && y2<del->y2)
{
list.insert(*(new_area(del->x1,del->y1,del->x2,y1-1)));
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
} else if (y1<=del->y1)
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
else
list.insert(*(new_area(del->x1,del->y1,del->x2,y1-1)));
} else if (y1>del->y1 && y2<del->y2)
list.insert(*(new_area(del->x1,y2+1,del->x2,del->y2)));
delete_area(&*del);
}
} else
{
last=a;
++a;
}
}
}
void i4_rect_list_class::add_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2,
i4_bool combine)
{
if (x1>x2 || y1>y2)
return ;
if (list.begin()==list.end())
list.insert(*(new_area(x1,y1,x2,y2)));
else
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end();
for (;a!=list.end();)
{
// check to see if this new rectangle completly encloses the check rectangle
if (x1<=a->x1 && y1<=a->y1 && x2>=a->x2 && y2>=a->y2)
{
if (last==list.end())
list.erase();
else list.erase_after(last);
i4_isl_list<area>::iterator q=a;
++a;
delete_area(&*q);
} else if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2)) // intersects another area?
{
if (x1<a->x1)
add_area(x1,(i4_coord) max(y1,a->y1),(sw16)(a->x1-1),(i4_coord) min(y2,a->y2));
if (x2>a->x2)
add_area(a->x2+1,(i4_coord) max(y1,a->y1),x2,(i4_coord) min(y2,a->y2));
if (y1<a->y1)
add_area(x1,y1,x2,a->y1-1);
if (y2>a->y2)
add_area(x1,a->y2+1,x2,y2);
return ;
}
else if (combine && a->x2+1==x1 && a->y1==y1 && a->y2==y2) // combines to the right
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->x2=x2;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->x1-1==x2 && a->y1==y1 && a->y2==y2) // combines to the left
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->x1=x1;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->y1-1==y2 && a->x1==x1 && a->x2==x2) // combines above
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->y1=y1;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else if (combine && a->y2+1==y1 && a->x1==x1 && a->x2==x2) // combines below
{
if (last==list.end())
list.erase();
else list.erase_after(last);
a->y2=y2;
add_area(a->x1, a->y1, a->x2, a->y2);
delete_area(&*a);
return;
}
else
{
last=a;
++a;
}
}
list.insert(*(new_area(x1,y1,x2,y2)));
}
}
void i4_rect_list_class::intersect_area(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2) // reduces area list to that which intersects this area
{
i4_isl_list<area>::iterator a=list.begin(),last=list.end(),next;
for (;a!=list.end();a=next)
{
next=a;
++next;
if (!(x2<a->x1 || y2<a->y1 || x1>a->x2 || y1>a->y2))
{
if (x1>a->x1) a->x1=x1;
if (x2<a->x2) a->x2=x2;
if (y1>a->y1) a->y1=y1;
if (y2<a->y2) a->y2=y2;
last=a;
} else
{
if (a==list.begin())
list.erase();
else
list.erase_after(last);
delete_area(&*a);
}
}
}
// return i4_T if area is totally clipped away
// this can be used to skip expensive drawing operations
i4_bool i4_rect_list_class::clipped_away(i4_coord x1, i4_coord y1, i4_coord x2, i4_coord y2)
{
i4_rect_list_class area_left(x1,y1,x2,y2);
i4_isl_list<area>::iterator a=list.begin();
for (;a!=list.end();++a)
area_left.remove_area(a->x1, a->y1, a->x2, a->y2);
return area_left.empty();
}
i4_rect_list_class::i4_rect_list_class(i4_rect_list_class *copy_from, i4_coord xoff, i4_coord yoff)
{
i4_isl_list<area>::iterator a=copy_from->list.begin(),last,q;
if (a!=copy_from->list.end())
{
last=new_area(a->x1+xoff,a->y1+yoff,a->x2+xoff,a->y2+yoff);
list.insert(*last);
++a;
while (a!=copy_from->list.end())
{
q=new_area(a->x1+xoff,a->y1+yoff,a->x2+xoff,a->y2+yoff);
list.insert_after(last,*q);
last=q;
++a;
}
}
}
void i4_rect_list_class::intersect_list(i4_rect_list_class *other) // reduces area list to that which intersects this area list
{
i4_rect_list_class intersection;
i4_isl_list<area>::iterator a,b;
for (b=other->list.begin();b!=other->list.end();++b)
{
for (a=list.begin();a!=list.end();++a)
{
if (!(b->x2<a->x1 || b->y2<a->y1 || b->x1>a->x2 || b->y1>a->y2))
{
i4_coord x1,y1,x2,y2;
if (b->x1>a->x1) x1=b->x1; else x1=a->x1;
if (b->x2<a->x2) x2=b->x2; else x2=a->x2;
if (b->y1>a->y1) y1=b->y1; else y1=a->y1;
if (b->y2<a->y2) y2=b->y2; else y2=a->y2;
intersection.list.insert(*(new_area(x1,y1,x2,y2)));
}
}
}
intersection.list.swap(list);
}
void i4_rect_list_class::inspect(int print)
{
for (i4_isl_list<area>::iterator a=list.begin(); a!=list.end(); ++a)
{
if (print)
i4_warning("(%d %d %d %d (%d x %d)", a->x1, a->y1, a->x2, a->y2,
a->x2-a->x1+1, a->y2-a->y1+1);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 The Brick Authors.
#include "brick/window/accounts_window.h"
#include "include/base/cef_logging.h"
#include "brick/client_handler.h"
#include "brick/window/edit_account_window.h"
extern char _binary_window_accounts_glade_start;
extern char _binary_window_accounts_glade_size;
namespace {
bool
on_delete_event(GtkDialog *dialog, gpointer data, AccountsWindow *self) {
self->Hide();
return true;
}
void
on_edit_finished(GtkWidget *widget, AccountsWindow *self) {
self->ReloadAccounts();
}
void
on_add_button(GtkWidget *widget, AccountsWindow *self) {
self->window_objects_.edit_account_window->Init(CefRefPtr<Account> (new Account));
g_signal_connect(GTK_OBJECT(self->window_objects_.edit_account_window->window_objects_.window), "destroy", G_CALLBACK(on_edit_finished), self);
self->window_objects_.edit_account_window->Show();
}
void
on_edit_button(GtkWidget *widget, AccountsWindow *self) {
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
selection = gtk_tree_view_get_selection(self->window_objects_.accounts_view);
model = gtk_tree_view_get_model(self->window_objects_.accounts_view);
LOG_IF(WARNING, !gtk_tree_model_get_iter_first(model, &iter))
<< "Can't get first list iter";
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
gint ref_id;
gtk_tree_model_get(model, &iter,
AccountsWindow::REF_ID, &ref_id,
-1
);
self->window_objects_.edit_account_window->Init(
self->window_objects_.account_manager->GetById(ref_id)
);
self->window_objects_.edit_account_window->Show();
g_signal_connect(GTK_OBJECT(self->window_objects_.edit_account_window->window_objects_.window), "destroy", G_CALLBACK(on_edit_finished), self);
} else {
LOG(WARNING)
<< "Can't find selected row";
}
}
void
on_delete_button(GtkWidget *widget, AccountsWindow *self) {
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
selection = gtk_tree_view_get_selection(self->window_objects_.accounts_view);
model = gtk_tree_view_get_model(self->window_objects_.accounts_view);
LOG_IF(WARNING, !gtk_tree_model_get_iter_first(model, &iter))
<< "Can't get first list iter";
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
gint ref_id;
gtk_tree_model_get(model, &iter,
AccountsWindow::REF_ID, &ref_id,
-1
);
self->window_objects_.account_manager->DeleteAccount(ref_id);
self->window_objects_.account_manager->Commit();
gtk_list_store_remove(self->window_objects_.accounts_store, &iter);
} else {
LOG(WARNING)
<< "Can't remove row";
}
}
static void
on_close_button(GtkWidget *widget, AccountsWindow *self) {
self->Hide();
}
} // namespace
void
AccountsWindow::Init() {
GtkBuilder *builder = gtk_builder_new ();
GError* error = NULL;
if (!gtk_builder_add_from_string(builder, &_binary_window_accounts_glade_start, (gsize)&_binary_window_accounts_glade_size, &error)) {
LOG(WARNING) << "Failed to build accounts window: " << error->message;
g_error_free (error);
}
window_objects_.account_manager = ClientHandler::GetInstance()->GetAccountManager();
window_objects_.edit_account_window = new EditAccountWindow();
window_handler_ = GTK_WIDGET(gtk_builder_get_object(builder, "accounts_dialog"));
window_objects_.window = window_handler_;
window_objects_.accounts_view = GTK_TREE_VIEW(gtk_builder_get_object(builder, "accounts_view"));
window_objects_.accounts_store = GTK_LIST_STORE(gtk_builder_get_object(builder, "accounts_store"));
g_signal_connect(gtk_builder_get_object(builder, "accounts_dialog"), "delete_event", G_CALLBACK(on_delete_event), this);
g_signal_connect(gtk_builder_get_object(builder, "add_button"), "clicked", G_CALLBACK(on_add_button), this);
g_signal_connect(gtk_builder_get_object(builder, "edit_button"), "clicked", G_CALLBACK(on_edit_button), this);
g_signal_connect(gtk_builder_get_object(builder, "delete_button"), "clicked", G_CALLBACK(on_delete_button), this);
g_signal_connect(gtk_builder_get_object(builder, "close_button"), "clicked", G_CALLBACK(on_close_button), this);
g_object_unref(builder);
ReloadAccounts();
}
void
AccountsWindow::AddToList(int id, std::string label) {
GtkListStore *store;
GtkTreeIter iter;
store = window_objects_.accounts_store;
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter,
REF_ID, id,
LABEL, label.c_str(),
-1
);
}
void
AccountsWindow::Clear() {
gtk_list_store_clear(window_objects_.accounts_store);
}
<commit_msg>Добавил открытие формы редактировании аккаунта по двойному клику<commit_after>// Copyright (c) 2015 The Brick Authors.
#include "brick/window/accounts_window.h"
#include "include/base/cef_logging.h"
#include "brick/client_handler.h"
#include "brick/window/edit_account_window.h"
extern char _binary_window_accounts_glade_start;
extern char _binary_window_accounts_glade_size;
namespace {
bool
on_delete_event(GtkDialog *dialog, gpointer data, AccountsWindow *self) {
self->Hide();
return true;
}
void
on_edit_finished(GtkWidget *widget, AccountsWindow *self) {
self->ReloadAccounts();
}
void
on_add_button(GtkWidget *widget, AccountsWindow *self) {
self->window_objects_.edit_account_window->Init(CefRefPtr<Account> (new Account));
g_signal_connect(GTK_OBJECT(self->window_objects_.edit_account_window->window_objects_.window), "destroy", G_CALLBACK(on_edit_finished), self);
self->window_objects_.edit_account_window->Show();
}
void
on_edit_button(GtkWidget *widget, AccountsWindow *self) {
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
selection = gtk_tree_view_get_selection(self->window_objects_.accounts_view);
model = gtk_tree_view_get_model(self->window_objects_.accounts_view);
LOG_IF(WARNING, !gtk_tree_model_get_iter_first(model, &iter))
<< "Can't get first list iter";
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
gint ref_id;
gtk_tree_model_get(model, &iter,
AccountsWindow::REF_ID, &ref_id,
-1
);
self->window_objects_.edit_account_window->Init(
self->window_objects_.account_manager->GetById(ref_id)
);
self->window_objects_.edit_account_window->Show();
g_signal_connect(GTK_OBJECT(self->window_objects_.edit_account_window->window_objects_.window), "destroy", G_CALLBACK(on_edit_finished), self);
} else {
LOG(WARNING)
<< "Can't find selected row";
}
}
void
on_delete_button(GtkWidget *widget, AccountsWindow *self) {
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter iter;
selection = gtk_tree_view_get_selection(self->window_objects_.accounts_view);
model = gtk_tree_view_get_model(self->window_objects_.accounts_view);
LOG_IF(WARNING, !gtk_tree_model_get_iter_first(model, &iter))
<< "Can't get first list iter";
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
gint ref_id;
gtk_tree_model_get(model, &iter,
AccountsWindow::REF_ID, &ref_id,
-1
);
self->window_objects_.account_manager->DeleteAccount(ref_id);
self->window_objects_.account_manager->Commit();
gtk_list_store_remove(self->window_objects_.accounts_store, &iter);
} else {
LOG(WARNING)
<< "Can't remove row";
}
}
static void
on_close_button(GtkWidget *widget, AccountsWindow *self) {
self->Hide();
}
void
on_accounts_view_row_activated(
GtkTreeView *treeview,
GtkTreePath *path,
GtkTreeViewColumn *col,
AccountsWindow *self) {
on_edit_button(nullptr, self);
}
} // namespace
void
AccountsWindow::Init() {
GtkBuilder *builder = gtk_builder_new ();
GError* error = NULL;
if (!gtk_builder_add_from_string(builder, &_binary_window_accounts_glade_start, (gsize)&_binary_window_accounts_glade_size, &error)) {
LOG(WARNING) << "Failed to build accounts window: " << error->message;
g_error_free (error);
}
window_objects_.account_manager = ClientHandler::GetInstance()->GetAccountManager();
window_objects_.edit_account_window = new EditAccountWindow();
window_handler_ = GTK_WIDGET(gtk_builder_get_object(builder, "accounts_dialog"));
window_objects_.window = window_handler_;
window_objects_.accounts_view = GTK_TREE_VIEW(gtk_builder_get_object(builder, "accounts_view"));
window_objects_.accounts_store = GTK_LIST_STORE(gtk_builder_get_object(builder, "accounts_store"));
g_signal_connect(gtk_builder_get_object(builder, "accounts_dialog"), "delete_event", G_CALLBACK(on_delete_event), this);
g_signal_connect(window_objects_.accounts_view, "row-activated", G_CALLBACK(on_accounts_view_row_activated), this);
g_signal_connect(gtk_builder_get_object(builder, "add_button"), "clicked", G_CALLBACK(on_add_button), this);
g_signal_connect(gtk_builder_get_object(builder, "edit_button"), "clicked", G_CALLBACK(on_edit_button), this);
g_signal_connect(gtk_builder_get_object(builder, "delete_button"), "clicked", G_CALLBACK(on_delete_button), this);
g_signal_connect(gtk_builder_get_object(builder, "close_button"), "clicked", G_CALLBACK(on_close_button), this);
g_object_unref(builder);
ReloadAccounts();
}
void
AccountsWindow::AddToList(int id, std::string label) {
GtkListStore *store;
GtkTreeIter iter;
store = window_objects_.accounts_store;
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter,
REF_ID, id,
LABEL, label.c_str(),
-1
);
}
void
AccountsWindow::Clear() {
gtk_list_store_clear(window_objects_.accounts_store);
}
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
// Modified to implement C code by Dave Benson.
#include <set>
#include <map>
#include <protoc-c/c_enum.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
const string& dllexport_decl)
: descriptor_(descriptor),
dllexport_decl_(dllexport_decl) {
}
EnumGenerator::~EnumGenerator() {}
void EnumGenerator::GenerateDefinition(io::Printer* printer) {
map<string, string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name());
vars["shortname"] = descriptor_->name();
vars["uc_name"] = FullNameToUpper(descriptor_->full_name());
printer->Print(vars, "typedef enum _$classname$ {\n");
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
const EnumValueDescriptor* max_value = descriptor_->value(0);
vars["opt_comma"] = ",";
vars["prefix"] = FullNameToUpper(descriptor_->full_name()) + "__";
for (int i = 0; i < descriptor_->value_count(); i++) {
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
if (i + 1 == descriptor_->value_count())
vars["opt_comma"] = "";
printer->Print(vars, "$prefix$$name$ = $number$$opt_comma$\n");
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
}
if (descriptor_->value(i)->number() > max_value->number()) {
max_value = descriptor_->value(i);
}
}
printer->Print(vars, " _PROTOBUF_C_FORCE_ENUM_TO_BE_INT_SIZE($uc_name$)\n");
printer->Outdent();
printer->Print(vars, "} $classname$;\n");
}
void EnumGenerator::GenerateDescriptorDeclarations(io::Printer* printer) {
map<string, string> vars;
if (dllexport_decl_.empty()) {
vars["dllexport"] = "";
} else {
vars["dllexport"] = dllexport_decl_ + " ";
}
vars["classname"] = FullNameToC(descriptor_->full_name());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name());
printer->Print(vars,
"extern $dllexport$const ProtobufCEnumDescriptor $lcclassname$__descriptor;\n");
}
struct ValueIndex
{
int value;
unsigned index;
unsigned final_index; /* index in uniqified array of values */
const char *name;
};
void EnumGenerator::GenerateValueInitializer(io::Printer *printer, int index)
{
const EnumValueDescriptor *vd = descriptor_->value(index);
map<string, string> vars;
vars["enum_value_name"] = vd->name();
vars["c_enum_value_name"] = FullNameToUpper(descriptor_->full_name()) + "__" + ToUpper(vd->name());
vars["value"] = SimpleItoa(vd->number());
printer->Print(vars,
" { \"$enum_value_name$\", \"$c_enum_value_name$\", $value$ },\n");
}
static int compare_value_indices_by_value_then_index(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
if (vi_a->value < vi_b->value) return -1;
if (vi_a->value > vi_b->value) return +1;
if (vi_a->index < vi_b->index) return -1;
if (vi_a->index > vi_b->index) return +1;
return 0;
}
static int compare_value_indices_by_name(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
return strcmp (vi_a->name, vi_b->name);
}
void EnumGenerator::GenerateEnumDescriptor(io::Printer* printer) {
map<string, string> vars;
vars["fullname"] = descriptor_->full_name();
vars["lcclassname"] = FullNameToLower(descriptor_->full_name());
vars["cname"] = FullNameToC(descriptor_->full_name());
vars["shortname"] = descriptor_->name();
vars["packagename"] = descriptor_->file()->package();
vars["value_count"] = SimpleItoa(descriptor_->value_count());
// Sort by name and value, dropping duplicate values if they appear later.
// TODO: use a c++ paradigm for this!
NameIndex *name_index = new NameIndex[descriptor_->value_count()];
ValueIndex *value_index = new ValueIndex[descriptor_->value_count()];
for (int j = 0; j < descriptor_->value_count(); j++) {
const EnumValueDescriptor *vd = descriptor_->value(j);
name_index[j].index = j;
name_index[j].name = vd->name().c_str();
value_index[j].index = j;
value_index[j].value = vd->number();
value_index[j].name = vd->name().c_str();
}
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_value_then_index);
// only record unique values
int n_unique_values;
if (descriptor_->value_count() == 0) {
n_unique_values = 0; // should never happen
} else {
n_unique_values = 1;
value_index[0].final_index = 0;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value)
value_index[j].final_index = n_unique_values++;
else
value_index[j].final_index = n_unique_values - 1;
}
}
vars["unique_value_count"] = SimpleItoa(n_unique_values);
printer->Print(vars,
"const ProtobufCEnumValue $lcclassname$__enum_values_by_number[$unique_value_count$] =\n"
"{\n");
if (descriptor_->value_count() > 0) {
GenerateValueInitializer(printer, value_index[0].index);
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
GenerateValueInitializer(printer, value_index[j].index);
}
}
}
printer->Print(vars, "};\n");
printer->Print(vars, "static const ProtobufCIntRange $lcclassname$__value_ranges[] = {\n");
unsigned n_ranges = 0;
if (descriptor_->value_count() > 0) {
unsigned range_start = 0;
unsigned range_len = 1;
int range_start_value = value_index[0].value;
int last_value = range_start_value;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
if (last_value + 1 == value_index[j].value) {
range_len++;
} else {
// output range
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start_value = value_index[j].value;
range_start += range_len;
range_len = 1;
n_ranges++;
}
last_value = value_index[j].value;
}
}
{
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start += range_len;
n_ranges++;
}
{
vars["range_start_value"] = SimpleItoa(0);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$}\n};\n");
}
}
vars["n_ranges"] = SimpleItoa(n_ranges);
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_name);
printer->Print(vars,
"const ProtobufCEnumValueIndex $lcclassname$__enum_values_by_name[$value_count$] =\n"
"{\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
vars["index"] = SimpleItoa(value_index[j].final_index);
vars["name"] = value_index[j].name;
printer->Print (vars, " { \"$name$\", $index$ },\n");
}
printer->Print(vars, "};\n");
printer->Print(vars,
"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\n"
"{\n"
" PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,\n"
" \"$fullname$\",\n"
" \"$shortname$\",\n"
" \"$cname$\",\n"
" \"$packagename$\",\n"
" $unique_value_count$,\n"
" $lcclassname$__enum_values_by_number,\n"
" $value_count$,\n"
" $lcclassname$__enum_values_by_name,\n"
" $n_ranges$,\n"
" $lcclassname$__value_ranges,\n"
" NULL,NULL,NULL,NULL /* reserved[1234] */\n"
"};\n");
delete[] name_index;
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
<commit_msg>GenerateEnumDescriptor(): free value_index, Coverity #1153645<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// Copyright (c) 2008-2013, Dave Benson. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
// Modified to implement C code by Dave Benson.
#include <set>
#include <map>
#include <protoc-c/c_enum.h>
#include <protoc-c/c_helpers.h>
#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace c {
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
const string& dllexport_decl)
: descriptor_(descriptor),
dllexport_decl_(dllexport_decl) {
}
EnumGenerator::~EnumGenerator() {}
void EnumGenerator::GenerateDefinition(io::Printer* printer) {
map<string, string> vars;
vars["classname"] = FullNameToC(descriptor_->full_name());
vars["shortname"] = descriptor_->name();
vars["uc_name"] = FullNameToUpper(descriptor_->full_name());
printer->Print(vars, "typedef enum _$classname$ {\n");
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
const EnumValueDescriptor* max_value = descriptor_->value(0);
vars["opt_comma"] = ",";
vars["prefix"] = FullNameToUpper(descriptor_->full_name()) + "__";
for (int i = 0; i < descriptor_->value_count(); i++) {
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
if (i + 1 == descriptor_->value_count())
vars["opt_comma"] = "";
printer->Print(vars, "$prefix$$name$ = $number$$opt_comma$\n");
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
}
if (descriptor_->value(i)->number() > max_value->number()) {
max_value = descriptor_->value(i);
}
}
printer->Print(vars, " _PROTOBUF_C_FORCE_ENUM_TO_BE_INT_SIZE($uc_name$)\n");
printer->Outdent();
printer->Print(vars, "} $classname$;\n");
}
void EnumGenerator::GenerateDescriptorDeclarations(io::Printer* printer) {
map<string, string> vars;
if (dllexport_decl_.empty()) {
vars["dllexport"] = "";
} else {
vars["dllexport"] = dllexport_decl_ + " ";
}
vars["classname"] = FullNameToC(descriptor_->full_name());
vars["lcclassname"] = FullNameToLower(descriptor_->full_name());
printer->Print(vars,
"extern $dllexport$const ProtobufCEnumDescriptor $lcclassname$__descriptor;\n");
}
struct ValueIndex
{
int value;
unsigned index;
unsigned final_index; /* index in uniqified array of values */
const char *name;
};
void EnumGenerator::GenerateValueInitializer(io::Printer *printer, int index)
{
const EnumValueDescriptor *vd = descriptor_->value(index);
map<string, string> vars;
vars["enum_value_name"] = vd->name();
vars["c_enum_value_name"] = FullNameToUpper(descriptor_->full_name()) + "__" + ToUpper(vd->name());
vars["value"] = SimpleItoa(vd->number());
printer->Print(vars,
" { \"$enum_value_name$\", \"$c_enum_value_name$\", $value$ },\n");
}
static int compare_value_indices_by_value_then_index(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
if (vi_a->value < vi_b->value) return -1;
if (vi_a->value > vi_b->value) return +1;
if (vi_a->index < vi_b->index) return -1;
if (vi_a->index > vi_b->index) return +1;
return 0;
}
static int compare_value_indices_by_name(const void *a, const void *b)
{
const ValueIndex *vi_a = (const ValueIndex *) a;
const ValueIndex *vi_b = (const ValueIndex *) b;
return strcmp (vi_a->name, vi_b->name);
}
void EnumGenerator::GenerateEnumDescriptor(io::Printer* printer) {
map<string, string> vars;
vars["fullname"] = descriptor_->full_name();
vars["lcclassname"] = FullNameToLower(descriptor_->full_name());
vars["cname"] = FullNameToC(descriptor_->full_name());
vars["shortname"] = descriptor_->name();
vars["packagename"] = descriptor_->file()->package();
vars["value_count"] = SimpleItoa(descriptor_->value_count());
// Sort by name and value, dropping duplicate values if they appear later.
// TODO: use a c++ paradigm for this!
NameIndex *name_index = new NameIndex[descriptor_->value_count()];
ValueIndex *value_index = new ValueIndex[descriptor_->value_count()];
for (int j = 0; j < descriptor_->value_count(); j++) {
const EnumValueDescriptor *vd = descriptor_->value(j);
name_index[j].index = j;
name_index[j].name = vd->name().c_str();
value_index[j].index = j;
value_index[j].value = vd->number();
value_index[j].name = vd->name().c_str();
}
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_value_then_index);
// only record unique values
int n_unique_values;
if (descriptor_->value_count() == 0) {
n_unique_values = 0; // should never happen
} else {
n_unique_values = 1;
value_index[0].final_index = 0;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value)
value_index[j].final_index = n_unique_values++;
else
value_index[j].final_index = n_unique_values - 1;
}
}
vars["unique_value_count"] = SimpleItoa(n_unique_values);
printer->Print(vars,
"const ProtobufCEnumValue $lcclassname$__enum_values_by_number[$unique_value_count$] =\n"
"{\n");
if (descriptor_->value_count() > 0) {
GenerateValueInitializer(printer, value_index[0].index);
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
GenerateValueInitializer(printer, value_index[j].index);
}
}
}
printer->Print(vars, "};\n");
printer->Print(vars, "static const ProtobufCIntRange $lcclassname$__value_ranges[] = {\n");
unsigned n_ranges = 0;
if (descriptor_->value_count() > 0) {
unsigned range_start = 0;
unsigned range_len = 1;
int range_start_value = value_index[0].value;
int last_value = range_start_value;
for (int j = 1; j < descriptor_->value_count(); j++) {
if (value_index[j-1].value != value_index[j].value) {
if (last_value + 1 == value_index[j].value) {
range_len++;
} else {
// output range
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start_value = value_index[j].value;
range_start += range_len;
range_len = 1;
n_ranges++;
}
last_value = value_index[j].value;
}
}
{
vars["range_start_value"] = SimpleItoa(range_start_value);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$},");
range_start += range_len;
n_ranges++;
}
{
vars["range_start_value"] = SimpleItoa(0);
vars["orig_index"] = SimpleItoa(range_start);
printer->Print (vars, "{$range_start_value$, $orig_index$}\n};\n");
}
}
vars["n_ranges"] = SimpleItoa(n_ranges);
qsort(value_index, descriptor_->value_count(),
sizeof(ValueIndex), compare_value_indices_by_name);
printer->Print(vars,
"const ProtobufCEnumValueIndex $lcclassname$__enum_values_by_name[$value_count$] =\n"
"{\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
vars["index"] = SimpleItoa(value_index[j].final_index);
vars["name"] = value_index[j].name;
printer->Print (vars, " { \"$name$\", $index$ },\n");
}
printer->Print(vars, "};\n");
printer->Print(vars,
"const ProtobufCEnumDescriptor $lcclassname$__descriptor =\n"
"{\n"
" PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC,\n"
" \"$fullname$\",\n"
" \"$shortname$\",\n"
" \"$cname$\",\n"
" \"$packagename$\",\n"
" $unique_value_count$,\n"
" $lcclassname$__enum_values_by_number,\n"
" $value_count$,\n"
" $lcclassname$__enum_values_by_name,\n"
" $n_ranges$,\n"
" $lcclassname$__value_ranges,\n"
" NULL,NULL,NULL,NULL /* reserved[1234] */\n"
"};\n");
delete[] value_index;
delete[] name_index;
}
} // namespace c
} // namespace compiler
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#define EIGEN_NO_STATIC_ASSERT // otherwise we fail at compile time on unused paths
#include "main.h"
template<typename MatrixType> void block(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType;
typedef Matrix<Scalar, Dynamic, Dynamic> DynamicMatrixType;
typedef Matrix<Scalar, Dynamic, 1> DynamicVectorType;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
ones = MatrixType::Ones(rows, cols);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
v3 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar s1 = ei_random<Scalar>();
Index r1 = ei_random<Index>(0,rows-1);
Index r2 = ei_random<Index>(r1,rows-1);
Index c1 = ei_random<Index>(0,cols-1);
Index c2 = ei_random<Index>(c1,cols-1);
//check row() and col()
VERIFY_IS_EQUAL(m1.col(c1).transpose(), m1.transpose().row(c1));
//check operator(), both constant and non-constant, on row() and col()
m1.row(r1) += s1 * m1.row(r2);
m1.col(c1) += s1 * m1.col(c2);
//check block()
Matrix<Scalar,Dynamic,Dynamic> b1(1,1); b1(0,0) = m1(r1,c1);
RowVectorType br1(m1.block(r1,0,1,cols));
VectorType bc1(m1.block(0,c1,rows,1));
VERIFY_IS_EQUAL(b1, m1.block(r1,c1,1,1));
VERIFY_IS_EQUAL(m1.row(r1), br1);
VERIFY_IS_EQUAL(m1.col(c1), bc1);
//check operator(), both constant and non-constant, on block()
m1.block(r1,c1,r2-r1+1,c2-c1+1) = s1 * m2.block(0, 0, r2-r1+1,c2-c1+1);
m1.block(r1,c1,r2-r1+1,c2-c1+1)(r2-r1,c2-c1) = m2.block(0, 0, r2-r1+1,c2-c1+1)(0,0);
enum {
BlockRows = 2,
BlockCols = 5
};
if (rows>=5 && cols>=8)
{
// test fixed block() as lvalue
m1.template block<BlockRows,BlockCols>(1,1) *= s1;
// test operator() on fixed block() both as constant and non-constant
m1.template block<BlockRows,BlockCols>(1,1)(0, 3) = m1.template block<2,5>(1,1)(1,2);
// check that fixed block() and block() agree
Matrix<Scalar,Dynamic,Dynamic> b = m1.template block<BlockRows,BlockCols>(3,3);
VERIFY_IS_EQUAL(b, m1.block(3,3,BlockRows,BlockCols));
}
if (rows>2)
{
// test sub vectors
VERIFY_IS_EQUAL(v1.template head<2>(), v1.block(0,0,2,1));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.head(2));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.segment(0,2));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.template segment<2>(0));
Index i = rows-2;
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.block(i,0,2,1));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.tail(2));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.segment(i,2));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.template segment<2>(i));
i = ei_random<Index>(0,rows-2);
VERIFY_IS_EQUAL(v1.segment(i,2), v1.template segment<2>(i));
}
// stress some basic stuffs with block matrices
VERIFY(ei_real(ones.col(c1).sum()) == RealScalar(rows));
VERIFY(ei_real(ones.row(r1).sum()) == RealScalar(cols));
VERIFY(ei_real(ones.col(c1).dot(ones.col(c2))) == RealScalar(rows));
VERIFY(ei_real(ones.row(r1).dot(ones.row(r2))) == RealScalar(cols));
// now test some block-inside-of-block.
// expressions with direct access
VERIFY_IS_EQUAL( (m1.block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2)) , (m1.block(r2,c2,rows-r2,cols-c2)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).row(0)) , (m1.row(r1).segment(c1,c2-c1+1)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).col(0)) , (m1.col(c1).segment(r1,r2-r1+1)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0)) , (m1.row(r1).segment(c1,c2-c1+1)).transpose() );
VERIFY_IS_EQUAL( (m1.transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0)) , (m1.row(r1).segment(c1,c2-c1+1)).transpose() );
// expressions without direct access
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2)) , ((m1+m2).block(r2,c2,rows-r2,cols-c2)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).row(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).col(0)) , ((m1+m2).col(c1).segment(r1,r2-r1+1)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)).transpose() );
VERIFY_IS_EQUAL( ((m1+m2).transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)).transpose() );
// evaluation into plain matrices from expressions with direct access (stress MapBase)
DynamicMatrixType dm;
DynamicVectorType dv;
dm.setZero();
dm = m1.block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2);
VERIFY_IS_EQUAL(dm, (m1.block(r2,c2,rows-r2,cols-c2)));
dm.setZero();
dv.setZero();
dm = m1.block(r1,c1,r2-r1+1,c2-c1+1).row(0).transpose();
dv = m1.row(r1).segment(c1,c2-c1+1);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.col(c1).segment(r1,r2-r1+1);
dv = m1.block(r1,c1,r2-r1+1,c2-c1+1).col(0);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0);
dv = m1.row(r1).segment(c1,c2-c1+1);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.row(r1).segment(c1,c2-c1+1).transpose();
dv = m1.transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0);
VERIFY_IS_EQUAL(dv, dm);
}
template<typename MatrixType>
void compare_using_data_and_stride(const MatrixType& m)
{
typedef MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index size = m.size();
Index innerStride = m.innerStride();
Index outerStride = m.outerStride();
Index rowStride = m.rowStride();
Index colStride = m.colStride();
const typename MatrixType::Scalar* data = m.data();
for(int j=0;j<cols;++j)
for(int i=0;i<rows;++i)
VERIFY(m.coeff(i,j) == data[i*rowStride + j*colStride]);
if(!MatrixType::IsVectorAtCompileTime)
{
for(int j=0;j<cols;++j)
for(int i=0;i<rows;++i)
VERIFY(m.coeff(i,j) == data[(MatrixType::Flags&RowMajorBit)
? i*outerStride + j*innerStride
: j*outerStride + i*innerStride]);
}
if(MatrixType::IsVectorAtCompileTime)
{
VERIFY(innerStride == int((&m.coeff(1))-(&m.coeff(0))));
for (int i=0;i<size;++i)
VERIFY(m.coeff(i) == data[i*innerStride]);
}
}
template<typename MatrixType>
void data_and_stride(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index r1 = ei_random<Index>(0,rows-1);
Index r2 = ei_random<Index>(r1,rows-1);
Index c1 = ei_random<Index>(0,cols-1);
Index c2 = ei_random<Index>(c1,cols-1);
MatrixType m1 = MatrixType::Random(rows, cols);
compare_using_data_and_stride(m1.block(r1, c1, r2-r1+1, c2-c1+1));
compare_using_data_and_stride(m1.transpose().block(c1, r1, c2-c1+1, r2-r1+1));
compare_using_data_and_stride(m1.row(r1));
compare_using_data_and_stride(m1.col(c1));
compare_using_data_and_stride(m1.row(r1).transpose());
compare_using_data_and_stride(m1.col(c1).transpose());
}
void test_block()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( block(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( block(Matrix4d()) );
CALL_SUBTEST_3( block(MatrixXcf(3, 3)) );
CALL_SUBTEST_4( block(MatrixXi(8, 12)) );
CALL_SUBTEST_5( block(MatrixXcd(20, 20)) );
CALL_SUBTEST_6( block(MatrixXf(20, 20)) );
CALL_SUBTEST_8( block(Matrix<float,Dynamic,4>(3, 4)) );
#ifndef EIGEN_DEFAULT_TO_ROW_MAJOR
CALL_SUBTEST_6( data_and_stride(MatrixXf(ei_random(5,50), ei_random(5,50))) );
CALL_SUBTEST_7( data_and_stride(Matrix<int,Dynamic,Dynamic,RowMajor>(ei_random(5,50), ei_random(5,50))) );
#endif
}
}
<commit_msg>Compilation fix.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#define EIGEN_NO_STATIC_ASSERT // otherwise we fail at compile time on unused paths
#include "main.h"
template<typename MatrixType> void block(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType;
typedef Matrix<Scalar, Dynamic, Dynamic> DynamicMatrixType;
typedef Matrix<Scalar, Dynamic, 1> DynamicVectorType;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
ones = MatrixType::Ones(rows, cols);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
v3 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar s1 = ei_random<Scalar>();
Index r1 = ei_random<Index>(0,rows-1);
Index r2 = ei_random<Index>(r1,rows-1);
Index c1 = ei_random<Index>(0,cols-1);
Index c2 = ei_random<Index>(c1,cols-1);
//check row() and col()
VERIFY_IS_EQUAL(m1.col(c1).transpose(), m1.transpose().row(c1));
//check operator(), both constant and non-constant, on row() and col()
m1.row(r1) += s1 * m1.row(r2);
m1.col(c1) += s1 * m1.col(c2);
//check block()
Matrix<Scalar,Dynamic,Dynamic> b1(1,1); b1(0,0) = m1(r1,c1);
RowVectorType br1(m1.block(r1,0,1,cols));
VectorType bc1(m1.block(0,c1,rows,1));
VERIFY_IS_EQUAL(b1, m1.block(r1,c1,1,1));
VERIFY_IS_EQUAL(m1.row(r1), br1);
VERIFY_IS_EQUAL(m1.col(c1), bc1);
//check operator(), both constant and non-constant, on block()
m1.block(r1,c1,r2-r1+1,c2-c1+1) = s1 * m2.block(0, 0, r2-r1+1,c2-c1+1);
m1.block(r1,c1,r2-r1+1,c2-c1+1)(r2-r1,c2-c1) = m2.block(0, 0, r2-r1+1,c2-c1+1)(0,0);
enum {
BlockRows = 2,
BlockCols = 5
};
if (rows>=5 && cols>=8)
{
// test fixed block() as lvalue
m1.template block<BlockRows,BlockCols>(1,1) *= s1;
// test operator() on fixed block() both as constant and non-constant
m1.template block<BlockRows,BlockCols>(1,1)(0, 3) = m1.template block<2,5>(1,1)(1,2);
// check that fixed block() and block() agree
Matrix<Scalar,Dynamic,Dynamic> b = m1.template block<BlockRows,BlockCols>(3,3);
VERIFY_IS_EQUAL(b, m1.block(3,3,BlockRows,BlockCols));
}
if (rows>2)
{
// test sub vectors
VERIFY_IS_EQUAL(v1.template head<2>(), v1.block(0,0,2,1));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.head(2));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.segment(0,2));
VERIFY_IS_EQUAL(v1.template head<2>(), v1.template segment<2>(0));
Index i = rows-2;
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.block(i,0,2,1));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.tail(2));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.segment(i,2));
VERIFY_IS_EQUAL(v1.template tail<2>(), v1.template segment<2>(i));
i = ei_random<Index>(0,rows-2);
VERIFY_IS_EQUAL(v1.segment(i,2), v1.template segment<2>(i));
}
// stress some basic stuffs with block matrices
VERIFY(ei_real(ones.col(c1).sum()) == RealScalar(rows));
VERIFY(ei_real(ones.row(r1).sum()) == RealScalar(cols));
VERIFY(ei_real(ones.col(c1).dot(ones.col(c2))) == RealScalar(rows));
VERIFY(ei_real(ones.row(r1).dot(ones.row(r2))) == RealScalar(cols));
// now test some block-inside-of-block.
// expressions with direct access
VERIFY_IS_EQUAL( (m1.block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2)) , (m1.block(r2,c2,rows-r2,cols-c2)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).row(0)) , (m1.row(r1).segment(c1,c2-c1+1)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).col(0)) , (m1.col(c1).segment(r1,r2-r1+1)) );
VERIFY_IS_EQUAL( (m1.block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0)) , (m1.row(r1).segment(c1,c2-c1+1)).transpose() );
VERIFY_IS_EQUAL( (m1.transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0)) , (m1.row(r1).segment(c1,c2-c1+1)).transpose() );
// expressions without direct access
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2)) , ((m1+m2).block(r2,c2,rows-r2,cols-c2)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).row(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).col(0)) , ((m1+m2).col(c1).segment(r1,r2-r1+1)) );
VERIFY_IS_EQUAL( ((m1+m2).block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)).transpose() );
VERIFY_IS_EQUAL( ((m1+m2).transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0)) , ((m1+m2).row(r1).segment(c1,c2-c1+1)).transpose() );
// evaluation into plain matrices from expressions with direct access (stress MapBase)
DynamicMatrixType dm;
DynamicVectorType dv;
dm.setZero();
dm = m1.block(r1,c1,rows-r1,cols-c1).block(r2-r1,c2-c1,rows-r2,cols-c2);
VERIFY_IS_EQUAL(dm, (m1.block(r2,c2,rows-r2,cols-c2)));
dm.setZero();
dv.setZero();
dm = m1.block(r1,c1,r2-r1+1,c2-c1+1).row(0).transpose();
dv = m1.row(r1).segment(c1,c2-c1+1);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.col(c1).segment(r1,r2-r1+1);
dv = m1.block(r1,c1,r2-r1+1,c2-c1+1).col(0);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.block(r1,c1,r2-r1+1,c2-c1+1).transpose().col(0);
dv = m1.row(r1).segment(c1,c2-c1+1);
VERIFY_IS_EQUAL(dv, dm);
dm.setZero();
dv.setZero();
dm = m1.row(r1).segment(c1,c2-c1+1).transpose();
dv = m1.transpose().block(c1,r1,c2-c1+1,r2-r1+1).col(0);
VERIFY_IS_EQUAL(dv, dm);
}
template<typename MatrixType>
void compare_using_data_and_stride(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index size = m.size();
Index innerStride = m.innerStride();
Index outerStride = m.outerStride();
Index rowStride = m.rowStride();
Index colStride = m.colStride();
const typename MatrixType::Scalar* data = m.data();
for(int j=0;j<cols;++j)
for(int i=0;i<rows;++i)
VERIFY(m.coeff(i,j) == data[i*rowStride + j*colStride]);
if(!MatrixType::IsVectorAtCompileTime)
{
for(int j=0;j<cols;++j)
for(int i=0;i<rows;++i)
VERIFY(m.coeff(i,j) == data[(MatrixType::Flags&RowMajorBit)
? i*outerStride + j*innerStride
: j*outerStride + i*innerStride]);
}
if(MatrixType::IsVectorAtCompileTime)
{
VERIFY(innerStride == int((&m.coeff(1))-(&m.coeff(0))));
for (int i=0;i<size;++i)
VERIFY(m.coeff(i) == data[i*innerStride]);
}
}
template<typename MatrixType>
void data_and_stride(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
Index r1 = ei_random<Index>(0,rows-1);
Index r2 = ei_random<Index>(r1,rows-1);
Index c1 = ei_random<Index>(0,cols-1);
Index c2 = ei_random<Index>(c1,cols-1);
MatrixType m1 = MatrixType::Random(rows, cols);
compare_using_data_and_stride(m1.block(r1, c1, r2-r1+1, c2-c1+1));
compare_using_data_and_stride(m1.transpose().block(c1, r1, c2-c1+1, r2-r1+1));
compare_using_data_and_stride(m1.row(r1));
compare_using_data_and_stride(m1.col(c1));
compare_using_data_and_stride(m1.row(r1).transpose());
compare_using_data_and_stride(m1.col(c1).transpose());
}
void test_block()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( block(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( block(Matrix4d()) );
CALL_SUBTEST_3( block(MatrixXcf(3, 3)) );
CALL_SUBTEST_4( block(MatrixXi(8, 12)) );
CALL_SUBTEST_5( block(MatrixXcd(20, 20)) );
CALL_SUBTEST_6( block(MatrixXf(20, 20)) );
CALL_SUBTEST_8( block(Matrix<float,Dynamic,4>(3, 4)) );
#ifndef EIGEN_DEFAULT_TO_ROW_MAJOR
CALL_SUBTEST_6( data_and_stride(MatrixXf(ei_random(5,50), ei_random(5,50))) );
CALL_SUBTEST_7( data_and_stride(Matrix<int,Dynamic,Dynamic,RowMajor>(ei_random(5,50), ei_random(5,50))) );
#endif
}
}
<|endoftext|> |
<commit_before>/*
* fits.cpp
*
* Created on: Jun 19, 2012
* Author: mpetkova
*/
#include "MOKAlens.h"
#include <fstream>
#ifdef ENABLE_FITS
#include <CCfits/CCfits>
using namespace CCfits;
#endif
void LensHaloMOKA::getDims(){
#ifdef ENABLE_FITS
try{
std::auto_ptr<FITS> ff(new FITS (MOKA_input_file, Read));
PHDU *h0=&ff->pHDU();
map->nx=h0->axis(0);
map->ny=h0->axis(1);
}
catch(FITS::CantOpen){
std::cout << "can not open " << MOKA_input_file << std::endl;
exit(1);
}
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* \brief reads in the fits file for the MOKA map and saves it in the structure map
*/
void LensHaloMOKA::readImage(){
#ifdef ENABLE_FITS
std:: cout << " reading MOKA file: " << MOKA_input_file << std:: endl;
std::auto_ptr<FITS> ff(new FITS (MOKA_input_file, Read));
PHDU *h0=&ff->pHDU();
h0->read(map->convergence);
h0->readKey ("SIDEL",map->boxlarcsec);
h0->readKey ("SIDEL2",map->boxlMpc);
h0->readKey ("ZLENS",map->zlens);
h0->readKey ("ZSOURCE",map->zsource);
h0->readKey ("OMEGA",map->omegam);
h0->readKey ("LAMBDA",map->omegal);
h0->readKey ("H",map->h);
h0->readKey ("W",map->wq);
h0->readKey ("MSTAR",map->mstar);
h0->readKey ("MVIR",map->m);
h0->readKey ("CONCENTRATION",map->c);
h0->readKey ("DL",map->DL);
h0->readKey ("DLS",map->DLS);
h0->readKey ("DS",map->DS);
ExtHDU &h1=ff->extension(1);
h1.read(map->alpha1);
ExtHDU &h2=ff->extension(2);
h2.read(map->alpha2);
ExtHDU &h3=ff->extension(3);
h3.read(map->gamma1);
ExtHDU &h4=ff->extension(4);
h4.read(map->gamma2);
std::cout << *h0 << h1 << h2 << h3 << h4 << std::endl;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* \brief write the fits file of the new MOKA map from the structure map
*/
void LensHaloMOKA::writeImage(std::string filename){
#ifdef ENABLE_FITS
long naxis=2;
long naxes[2]={map->nx,map->ny};
std::auto_ptr<FITS> fout(0);
try{
fout.reset(new FITS(filename,FLOAT_IMG,naxis,naxes));
}
catch(FITS::CantCreate){
std::cout << "Unable to open fits file " << filename << std::endl;
ERROR_MESSAGE();
exit(1);
}
std::vector<long> naxex(2);
naxex[0]=map->nx;
naxex[1]=map->ny;
PHDU *phout=&fout->pHDU();
phout->write( 1,map->nx*map->ny,map->convergence );
phout->addKey ("SIDEL",map->boxlarcsec,"arcsec");
phout->addKey ("SIDEL2",map->boxlMpc,"Mpc/h");
phout->addKey ("ZLENS",map->zlens,"lens redshift");
phout->addKey ("ZSOURCE",map->zsource, "source redshift");
phout->addKey ("OMEGA",map->omegam,"omega matter");
phout->addKey ("LAMBDA",map->omegal,"omega lamda");
phout->addKey ("H",map->h,"hubble/100");
phout->addKey ("W",map->wq,"dark energy equation of state parameter");
phout->addKey ("MSTAR",map->mstar,"stellar mass of the BCG in Msun/h");
phout->addKey ("MVIR",map->m,"virial mass of the halo in Msun/h");
phout->addKey ("CONCENTRATION",map->c,"NFW concentration");
phout->addKey ("DL",map->DL,"Mpc/h");
phout->addKey ("DLS",map->DLS,"Mpc/h");
phout->addKey ("DS",map->DS,"Mpc/h");
ExtHDU *eh1=fout->addImage("gamma1", FLOAT_IMG, naxex);
eh1->write(1,map->nx*map->ny,map->gamma1);
ExtHDU *eh2=fout->addImage("gamma2", FLOAT_IMG, naxex);
eh2->write(1,map->nx*map->ny,map->gamma2);
ExtHDU *eh3=fout->addImage("gamma3", FLOAT_IMG, naxex);
eh3->write(1,map->nx*map->ny,map->gamma3);
std::cout << *phout << std::endl;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* routine used by fof to link nearby grid cell points
*/
void make_friendship(int ii,int ji,int np,std:: vector<int> &friends, std:: vector<double> &pointdist){
for(int jj=0;jj<np;jj++){
if(friends[ji+np*jj]!=0){
if(friends[ji+np*jj]<0){
friends[ii+np*jj]=-(ii+1);
}
else{
friends[ii+np*jj]=(ii+1);
}
friends[ji+np*jj]=0;
}
}
friends[ii+np*ji]=-(ii+1);
}
/*
* given a a set of grid points xci and yci and an interpixeld distance l return the id of the
* fof group nearest to the centre
*/
int fof(double l,std:: vector<double> xci, std:: vector<double> yci, std:: vector<int> &groupid){
int np = xci.size();
std:: vector<int> friends(np*np);
std:: vector<double> pointdist(np*np);
for(int ii = 0;ii<np; ii++) for(int ji = 0;ji<np; ji++){
pointdist[ii+np*ji] = sqrt( pow(xci[ii] - xci[ji],2) + pow(yci[ii] - yci[ji],2));
groupid[ii] = 0;
friends[ii+np*ji]=0;
}
for(int ii=0;ii<np;ii++) for(int ji = 0;ji<np; ji++){
if(pointdist[ii+np*ji]<=1.5*l) friends[ii+np*ji] = ii+1;
}
for(int ii=0;ii<np;ii++){
int r = 0;
while(r==0){
r=1;
for(int ji=0;ji<np;ji++){
if(friends[ii+np*ji]>0){
if(ii!=ji){
make_friendship(ii,ji,np,friends,pointdist);
r=0;
}
}
}
}
}
for(int ii=0;ii<np;ii++){
int p=0;
for(int ji=0;ji<np;ji++){
if(friends[ji+np*ii]!=0) p++;
if(p==2){
std:: cout << ji << " " << ii << ": " << friends[ji+np*ii] << " " << friends[ii+np*ji] << std:: endl;
exit(1);
}
}
}
// count the particles in each group
int kt = 0;
int ng= 0;
std:: vector<double> distcentre;
std:: vector<int> idgroup;
for(int ii=0;ii<np;ii++){
int k = 0;
double xcm=0;
double ycm=0;
for(int ji=0;ji<np;ji++){
if(friends[ii+np*ji]!=0){
k++;
groupid[ji]=ii+1;
xcm += xci[ji];
ycm += yci[ji];
}
}
if(k>4){
ng++;
xcm/=k;
ycm/=k;
distcentre.push_back(sqrt(xcm*xcm+ycm*ycm));
idgroup.push_back(ii+1);
// std:: cout << " " << ii+1 << " " << k << " " << sqrt(xcm*xcm+ycm*ycm) << std:: endl;
}
kt = kt + k;
}
if(kt != np){
std:: cout << " number of screaned particles : " << kt << std:: endl;
std:: cout << " differes from the number of particles : " << np << std:: endl;
std:: cout << " number of group found : " << ng << std:: endl;
std:: cout << " " << std:: endl;
std:: cout << " I will STOP here!!! " << std:: endl;
exit(1);
}
if(idgroup.size()>0){
std:: vector<double>::iterator it = min_element(distcentre.begin(), distcentre.end());
int minpos = idgroup[distance(distcentre.begin(), it)];
// std:: cout << " nearest to the centre " << minpos << std:: endl;
return minpos;
}
else return 0;
/* Make a histogram of the data */
/*
std::vector< int > histogram(np,0);
std::vector< int >::iterator it = groupid.begin();
while(it != groupid.end()) histogram[*it++]++;
/* Print out the frequencies of the values in v */
// std::copy(histogram.begin(),histogram.end(),std::ostream_iterator< int >(std::cout, " "));
// std::cout << std::endl;
/* Find the mode */
/*
int mode = std::max_element(histogram.begin(),histogram.end()) - histogram.begin();
return mode;
*/
}
<commit_msg>solved conflicts<commit_after>/*
* fits.cpp
*
* Created on: Jun 19, 2012
* Author: mpetkova
*/
#include "MOKAlens.h"
#include <fstream>
#ifdef ENABLE_FITS
#include <CCfits/CCfits>
using namespace CCfits;
#endif
void LensHaloMOKA::getDims(){
#ifdef ENABLE_FITS
try{
std::auto_ptr<FITS> ff(new FITS (MOKA_input_file, Read));
PHDU *h0=&ff->pHDU();
map->nx=h0->axis(0);
map->ny=h0->axis(1);
}
catch(FITS::CantOpen){
std::cout << "can not open " << MOKA_input_file << std::endl;
exit(1);
}
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* \brief reads in the fits file for the MOKA map and saves it in the structure map
*/
void LensHaloMOKA::readImage(){
#ifdef ENABLE_FITS
std:: cout << " reading MOKA file: " << MOKA_input_file << std:: endl;
std::auto_ptr<FITS> ff(new FITS (MOKA_input_file, Read));
PHDU *h0=&ff->pHDU();
h0->read(map->convergence);
h0->readKey ("SIDEL",map->boxlarcsec);
h0->readKey ("SIDEL2",map->boxlMpc);
h0->readKey ("ZLENS",map->zlens);
h0->readKey ("ZSOURCE",map->zsource);
h0->readKey ("OMEGA",map->omegam);
h0->readKey ("LAMBDA",map->omegal);
h0->readKey ("H",map->h);
h0->readKey ("W",map->wq);
h0->readKey ("MSTAR",map->mstar);
h0->readKey ("MVIR",map->m);
h0->readKey ("CONCENTRATION",map->c);
h0->readKey ("DL",map->DL);
h0->readKey ("DLS",map->DLS);
h0->readKey ("DS",map->DS);
std:: cout << map->boxlMpc << " " << map->boxlarcsec << std:: endl;
ExtHDU &h1=ff->extension(1);
h1.read(map->alpha1);
ExtHDU &h2=ff->extension(2);
h2.read(map->alpha2);
ExtHDU &h3=ff->extension(3);
h3.read(map->gamma1);
ExtHDU &h4=ff->extension(4);
h4.read(map->gamma2);
std::cout << *h0 << h1 << h2 << h3 << h4 << std::endl;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* \brief write the fits file of the new MOKA map from the structure map
*/
void LensHaloMOKA::writeImage(std::string filename){
#ifdef ENABLE_FITS
long naxis=2;
long naxes[2]={map->nx,map->ny};
std::auto_ptr<FITS> fout(0);
try{
fout.reset(new FITS(filename,FLOAT_IMG,naxis,naxes));
}
catch(FITS::CantCreate){
std::cout << "Unable to open fits file " << filename << std::endl;
ERROR_MESSAGE();
exit(1);
}
std::vector<long> naxex(2);
naxex[0]=map->nx;
naxex[1]=map->ny;
PHDU *phout=&fout->pHDU();
phout->write( 1,map->nx*map->ny,map->convergence );
phout->addKey ("SIDEL",map->boxlarcsec,"arcsec");
phout->addKey ("SIDEL2",map->boxlMpc,"Mpc/h");
phout->addKey ("ZLENS",map->zlens,"lens redshift");
phout->addKey ("ZSOURCE",map->zsource, "source redshift");
phout->addKey ("OMEGA",map->omegam,"omega matter");
phout->addKey ("LAMBDA",map->omegal,"omega lamda");
phout->addKey ("H",map->h,"hubble/100");
phout->addKey ("W",map->wq,"dark energy equation of state parameter");
phout->addKey ("MSTAR",map->mstar,"stellar mass of the BCG in Msun/h");
phout->addKey ("MVIR",map->m,"virial mass of the halo in Msun/h");
phout->addKey ("CONCENTRATION",map->c,"NFW concentration");
phout->addKey ("DL",map->DL,"Mpc/h");
phout->addKey ("DLS",map->DLS,"Mpc/h");
phout->addKey ("DS",map->DS,"Mpc/h");
ExtHDU *eh1=fout->addImage("gamma1", FLOAT_IMG, naxex);
eh1->write(1,map->nx*map->ny,map->gamma1);
ExtHDU *eh2=fout->addImage("gamma2", FLOAT_IMG, naxex);
eh2->write(1,map->nx*map->ny,map->gamma2);
ExtHDU *eh3=fout->addImage("gamma3", FLOAT_IMG, naxex);
eh3->write(1,map->nx*map->ny,map->gamma3);
std::cout << *phout << std::endl;
#else
std::cout << "Please enable the preprocessor flag ENABLE_FITS !" << std::endl;
exit(1);
#endif
}
/**
* routine used by fof to link nearby grid cell points
*/
void make_friendship(int ii,int ji,int np,std:: vector<int> &friends, std:: vector<double> &pointdist){
for(int jj=0;jj<np;jj++){
if(friends[ji+np*jj]!=0){
if(friends[ji+np*jj]<0){
friends[ii+np*jj]=-(ii+1);
}
else{
friends[ii+np*jj]=(ii+1);
}
friends[ji+np*jj]=0;
}
}
friends[ii+np*ji]=-(ii+1);
}
/*
* given a a set of grid points xci and yci and an interpixeld distance l return the id of the
* fof group nearest to the centre
*/
int fof(double l,std:: vector<double> xci, std:: vector<double> yci, std:: vector<int> &groupid){
int np = xci.size();
std:: vector<int> friends(np*np);
std:: vector<double> pointdist(np*np);
for(int ii = 0;ii<np; ii++) for(int ji = 0;ji<np; ji++){
pointdist[ii+np*ji] = sqrt( pow(xci[ii] - xci[ji],2) + pow(yci[ii] - yci[ji],2));
groupid[ii] = 0;
friends[ii+np*ji]=0;
}
for(int ii=0;ii<np;ii++) for(int ji = 0;ji<np; ji++){
if(pointdist[ii+np*ji]<=1.5*l) friends[ii+np*ji] = ii+1;
}
for(int ii=0;ii<np;ii++){
int r = 0;
while(r==0){
r=1;
for(int ji=0;ji<np;ji++){
if(friends[ii+np*ji]>0){
if(ii!=ji){
make_friendship(ii,ji,np,friends,pointdist);
r=0;
}
}
}
}
}
for(int ii=0;ii<np;ii++){
int p=0;
for(int ji=0;ji<np;ji++){
if(friends[ji+np*ii]!=0) p++;
if(p==2){
std:: cout << ji << " " << ii << ": " << friends[ji+np*ii] << " " << friends[ii+np*ji] << std:: endl;
exit(1);
}
}
}
// count the particles in each group
int kt = 0;
int ng= 0;
std:: vector<double> distcentre;
std:: vector<int> idgroup;
for(int ii=0;ii<np;ii++){
int k = 0;
double xcm=0;
double ycm=0;
for(int ji=0;ji<np;ji++){
if(friends[ii+np*ji]!=0){
k++;
groupid[ji]=ii+1;
xcm += xci[ji];
ycm += yci[ji];
}
}
if(k>4){
ng++;
xcm/=k;
ycm/=k;
distcentre.push_back(sqrt(xcm*xcm+ycm*ycm));
idgroup.push_back(ii+1);
// std:: cout << " " << ii+1 << " " << k << " " << sqrt(xcm*xcm+ycm*ycm) << std:: endl;
}
kt = kt + k;
}
if(kt != np){
std:: cout << " number of screaned particles : " << kt << std:: endl;
std:: cout << " differes from the number of particles : " << np << std:: endl;
std:: cout << " number of group found : " << ng << std:: endl;
std:: cout << " " << std:: endl;
std:: cout << " I will STOP here!!! " << std:: endl;
exit(1);
}
if(idgroup.size()>0){
std:: vector<double>::iterator it = min_element(distcentre.begin(), distcentre.end());
int minpos = idgroup[distance(distcentre.begin(), it)];
// std:: cout << " nearest to the centre " << minpos << std:: endl;
return minpos;
}
else return 0;
/* Make a histogram of the data */
/*
std::vector< int > histogram(np,0);
std::vector< int >::iterator it = groupid.begin();
while(it != groupid.end()) histogram[*it++]++;
/* Print out the frequencies of the values in v */
// std::copy(histogram.begin(),histogram.end(),std::ostream_iterator< int >(std::cout, " "));
// std::cout << std::endl;
/* Find the mode */
/*
int mode = std::max_element(histogram.begin(),histogram.end()) - histogram.begin();
return mode;
*/
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <set>
#include "oddlib/stream.hpp"
#include <jsonxx/jsonxx.h>
#include "logger.hpp"
#include "resourcemapper.hpp"
using namespace ::testing;
class MockFileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
// Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call
return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName));
}
MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));
MOCK_METHOD1(EnumerateFiles, std::vector<std::string>(const char* ));
MOCK_METHOD1(Exists, bool(const char*));
};
TEST(ResourceLocator, ResourceLoaderOpen)
{
MockFileSystem fs;
ResourceLoader loader(fs);
loader.Add("C:\\dataset_location1", 1);
loader.Add("C:\\dataset_location2", 2);
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND")))
.WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.Times(1)
.WillOnce(Return(new Oddlib::Stream(StringToVector("test"))));
auto stream = loader.Open("SLIGZ.BND");
ASSERT_NE(nullptr, stream);
const auto str = stream->LoadAllToString();
ASSERT_EQ(str, "test");
}
TEST(ResourceLocator, Cache)
{
ResourceCache cache;
const size_t resNameHash = StringHash("foo");
ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash));
{
Resource<Animation> res1(resNameHash, cache, nullptr);
std::shared_ptr<Animation> cached = cache.Find<Animation>(resNameHash);
ASSERT_NE(nullptr, cached);
ASSERT_EQ(cached.get(), res1.Ptr());
}
ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash));
}
TEST(ResourceLocator, ParseResourceMap)
{
const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})";
MockFileSystem fs;
EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
ResourceMapper mapper(fs, "resource_maps.json");
const ResourceMapper::AnimMapping* r0 = mapper.Find("I don't exist");
ASSERT_EQ(nullptr, r0);
const ResourceMapper::AnimMapping* r1 = mapper.Find("SLIGZ.BND_417_1");
ASSERT_NE(nullptr, r1);
ASSERT_EQ("SLIGZ.BND", r1->mFile);
ASSERT_EQ(417u, r1->mId);
ASSERT_EQ(1u, r1->mBlendingMode);
const ResourceMapper::AnimMapping* r2 = mapper.Find("SLIGZ.BND_417_2");
ASSERT_NE(nullptr, r2);
ASSERT_EQ("SLIGZ.BND", r2->mFile);
ASSERT_EQ(417u, r2->mId);
ASSERT_EQ(1u, r2->mBlendingMode);
}
TEST(ResourceLocator, ParseGameDefinition)
{
// TODO
MockFileSystem fs;
GameDefinition gd(fs, "test_game_definition.json");
}
TEST(ResourceLocator, GameDefinitionDiscovery)
{
// TODO - enumerating GD's
}
TEST(ResourceLocator, LocateAnimation)
{
GameDefinition aePc;
/*
aePc.mAuthor = "Oddworld Inhabitants";
aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus";
aePc.mName = "Oddworld Abe's Exoddus PC";
aePc.mDataSetName = "AePc";
*/
MockFileSystem fs;
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND")))
.WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.Times(1)
.WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); // For SLIGZ.BND_417_1, 2nd call should be cached
ResourceMapper mapper;
mapper.AddAnimMapping("SLIGZ.BND_417_1", { "SLIGZ.BND", 417, 1 });
mapper.AddAnimMapping("SLIGZ.BND_417_2", { "SLIGZ.BND", 417, 1 });
ResourceLocator locator(fs, aePc, std::move(mapper));
locator.AddDataPath("C:\\dataset_location2", 2);
locator.AddDataPath("C:\\dataset_location1", 1);
Resource<Animation> resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
Resource<Animation> resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped2.Reload();
// Can explicitly set the dataset to obtain it from a known location
Resource<Animation> resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", "AePc");
resDirect.Reload();
}
TEST(ResourceLocator, LocateAnimationMod)
{
// TODO: Like LocateAnimation but with mod override with and without original data
}
TEST(ResourceLocator, LocateFmv)
{
// TODO
}
TEST(ResourceLocator, LocateSound)
{
// TODO
}
TEST(ResourceLocator, LocateMusic)
{
// TODO
}
TEST(ResourceLocator, LocateCamera)
{
// TODO
}
TEST(ResourceLocator, LocatePath)
{
// TODO
}
class DataPathIdentities
{
public:
DataPathIdentities(IFileSystem& fs, const char* dataSetsIdsFileName)
{
auto stream = fs.Open(dataSetsIdsFileName);
Parse(stream->LoadAllToString());
}
void AddIdentity(const std::string& dataSetName, const std::vector<std::string>& idenfyingFiles)
{
mDataPathIds[dataSetName] = idenfyingFiles;
}
std::string Identify(IFileSystem& fs, const std::string& path) const
{
for (const auto& dataPathId : mDataPathIds)
{
bool foundAll = true;
for (const auto& identifyingFile : dataPathId.second)
{
if (!fs.Exists((path + "\\" + identifyingFile).c_str()))
{
foundAll = false;
break;
}
}
if (foundAll)
{
return dataPathId.first;
}
}
return "";
}
private:
std::map<std::string, std::vector<std::string>> mDataPathIds;
void Parse(const std::string& json)
{
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Object>("data_set_ids"))
{
jsonxx::Object dataSetIds = root.get<jsonxx::Object>("data_set_ids");
for (const auto& v : dataSetIds.kv_map())
{
jsonxx::Object dataSetId = dataSetIds.get<jsonxx::Object>(v.first);
jsonxx::Array identifyingFiles = dataSetId.get<jsonxx::Array>("files");
std::vector<std::string> files;
files.reserve(identifyingFiles.size());
for (const auto& f : identifyingFiles.values())
{
files.emplace_back(f->get<jsonxx::String>());
}
mDataPathIds[v.first] = files;
}
}
}
};
class DataPaths
{
public:
DataPaths(IFileSystem& fs, const char* dataSetsIdsFileName, const char* dataPathFileName)
: mIds(fs, dataSetsIdsFileName)
{
auto stream = fs.Open(dataPathFileName);
std::vector<std::string> paths = Parse(stream->LoadAllToString());
for (const auto& path : paths)
{
// TODO: Store the path and its identity
mIds.Identify(fs, path);
}
}
private:
std::vector<std::string> Parse(const std::string& json)
{
std::vector<std::string> paths;
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Array>("paths"))
{
jsonxx::Array pathsArray = root.get<jsonxx::Array>("paths");
for (const auto& path : pathsArray.values())
{
paths.emplace_back(path->get<jsonxx::String>());
}
}
return paths;
}
// To match to what a game def wants (AePcCd1, AoDemoPsx etc)
// we use SLUS codes for PSX or if it contains ABEWIN.EXE etc then its AoPc.
DataPathIdentities mIds;
};
TEST(ResourceLocator, Construct)
{
MockFileSystem fs;
const std::string resourceMapsJson = R"(
{
"data_set_ids" :
{
"AoPc": { "files": [ "AbeWin.exe" ] },
"AePc": { "files": [ "Exoddus.exe" ] }
}
}
)";
EXPECT_CALL(fs, OpenProxy(StrEq("datasetids.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
const std::string dataSetsJson = R"(
{
"paths": [
"F:\\Program Files\\SteamGames\\SteamApps\\common\\Oddworld Abes Exoddus",
"C:\\data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin"
]
}
)";
EXPECT_CALL(fs, OpenProxy(StrEq("datasets.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(dataSetsJson))));
// Data paths are saved user paths to game data
// load the list of data paths (if any) and discover what they are
DataPaths dataPaths(fs, "datasetids.json", "datasets.json");
/*
std::vector<GameDefinition> gds;
// load the enumerated "built-in" game defs
const auto builtInGds = fs.EnumerateFiles("${game_files}\\GameDefinitions");
for (const auto& file : builtInGds)
{
gds.emplace_back(GameDefinition(fs, file.c_str()));
}
// load the enumerated "mod" game defs
const auto modGs = fs.EnumerateFiles("${user_home}\\Alive\\Mods");
for (const auto& file : modGs)
{
gds.emplace_back(GameDefinition(fs, file.c_str()));
}
ResourceMapper mapper;
// Get the user selected game def
GameDefinition& selected = gds[0];
// ask for any missing data sets
//dataPaths.MissingDataSets(selected.RequiredDataSets());
// TODO: Pass in data paths here instead of calling AddDataPath?
// create the resource mapper loading the resource maps from the json db
ResourceLocator resourceLocator(fs, selected, std::move(mapper));
// TODO: Should be a DataPath instance (?)
// locator.AddDataPath(dataPaths[i], i);
// TODO: Allow changing at any point, don't set in ctor?
//resourceLocator.SetGameDefinition(&selected);
// Now we can obtain resources
Resource<Animation> resMapped1 = resourceLocator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
*/
}
<commit_msg>path ids<commit_after>#include <gmock/gmock.h>
#include <set>
#include "oddlib/stream.hpp"
#include <jsonxx/jsonxx.h>
#include "logger.hpp"
#include "resourcemapper.hpp"
using namespace ::testing;
class MockFileSystem : public IFileSystem
{
public:
virtual std::unique_ptr<Oddlib::IStream> Open(const char* fileName) override
{
// Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call
return std::unique_ptr<Oddlib::IStream>(OpenProxy(fileName));
}
MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));
MOCK_METHOD1(EnumerateFiles, std::vector<std::string>(const char* ));
MOCK_METHOD1(Exists, bool(const char*));
};
TEST(ResourceLocator, ResourceLoaderOpen)
{
MockFileSystem fs;
ResourceLoader loader(fs);
loader.Add("C:\\dataset_location1", 1);
loader.Add("C:\\dataset_location2", 2);
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND")))
.WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.Times(1)
.WillOnce(Return(new Oddlib::Stream(StringToVector("test"))));
auto stream = loader.Open("SLIGZ.BND");
ASSERT_NE(nullptr, stream);
const auto str = stream->LoadAllToString();
ASSERT_EQ(str, "test");
}
TEST(ResourceLocator, Cache)
{
ResourceCache cache;
const size_t resNameHash = StringHash("foo");
ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash));
{
Resource<Animation> res1(resNameHash, cache, nullptr);
std::shared_ptr<Animation> cached = cache.Find<Animation>(resNameHash);
ASSERT_NE(nullptr, cached);
ASSERT_EQ(cached.get(), res1.Ptr());
}
ASSERT_EQ(nullptr, cache.Find<Animation>(resNameHash));
}
TEST(ResourceLocator, ParseResourceMap)
{
const std::string resourceMapsJson = R"({"anims":[{"blend_mode":1,"name":"SLIGZ.BND_417_1"},{"blend_mode":1,"name":"SLIGZ.BND_417_2"}],"file":"SLIGZ.BND","id":417})";
MockFileSystem fs;
EXPECT_CALL(fs, OpenProxy(StrEq("resource_maps.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
ResourceMapper mapper(fs, "resource_maps.json");
const ResourceMapper::AnimMapping* r0 = mapper.Find("I don't exist");
ASSERT_EQ(nullptr, r0);
const ResourceMapper::AnimMapping* r1 = mapper.Find("SLIGZ.BND_417_1");
ASSERT_NE(nullptr, r1);
ASSERT_EQ("SLIGZ.BND", r1->mFile);
ASSERT_EQ(417u, r1->mId);
ASSERT_EQ(1u, r1->mBlendingMode);
const ResourceMapper::AnimMapping* r2 = mapper.Find("SLIGZ.BND_417_2");
ASSERT_NE(nullptr, r2);
ASSERT_EQ("SLIGZ.BND", r2->mFile);
ASSERT_EQ(417u, r2->mId);
ASSERT_EQ(1u, r2->mBlendingMode);
}
TEST(ResourceLocator, ParseGameDefinition)
{
// TODO
MockFileSystem fs;
GameDefinition gd(fs, "test_game_definition.json");
}
TEST(ResourceLocator, GameDefinitionDiscovery)
{
// TODO - enumerating GD's
}
TEST(ResourceLocator, LocateAnimation)
{
GameDefinition aePc;
/*
aePc.mAuthor = "Oddworld Inhabitants";
aePc.mDescription = "The original PC version of Oddworld Abe's Exoddus";
aePc.mName = "Oddworld Abe's Exoddus PC";
aePc.mDataSetName = "AePc";
*/
MockFileSystem fs;
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location1\\SLIGZ.BND")))
.WillRepeatedly(Return(nullptr));
EXPECT_CALL(fs, OpenProxy(StrEq("C:\\dataset_location2\\SLIGZ.BND")))
.Times(1)
.WillOnce(Return(new Oddlib::Stream(StringToVector("test")))); // For SLIGZ.BND_417_1, 2nd call should be cached
ResourceMapper mapper;
mapper.AddAnimMapping("SLIGZ.BND_417_1", { "SLIGZ.BND", 417, 1 });
mapper.AddAnimMapping("SLIGZ.BND_417_2", { "SLIGZ.BND", 417, 1 });
ResourceLocator locator(fs, aePc, std::move(mapper));
locator.AddDataPath("C:\\dataset_location2", 2);
locator.AddDataPath("C:\\dataset_location1", 1);
Resource<Animation> resMapped1 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
Resource<Animation> resMapped2 = locator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped2.Reload();
// Can explicitly set the dataset to obtain it from a known location
Resource<Animation> resDirect = locator.Locate<Animation>("SLIGZ.BND_417_1", "AePc");
resDirect.Reload();
}
TEST(ResourceLocator, LocateAnimationMod)
{
// TODO: Like LocateAnimation but with mod override with and without original data
}
TEST(ResourceLocator, LocateFmv)
{
// TODO
}
TEST(ResourceLocator, LocateSound)
{
// TODO
}
TEST(ResourceLocator, LocateMusic)
{
// TODO
}
TEST(ResourceLocator, LocateCamera)
{
// TODO
}
TEST(ResourceLocator, LocatePath)
{
// TODO
}
class DataPathIdentities
{
public:
DataPathIdentities(IFileSystem& fs, const char* dataSetsIdsFileName)
{
auto stream = fs.Open(dataSetsIdsFileName);
Parse(stream->LoadAllToString());
}
void AddIdentity(const std::string& dataSetName, const std::vector<std::string>& idenfyingFiles)
{
mDataPathIds[dataSetName] = idenfyingFiles;
}
std::string Identify(IFileSystem& fs, const std::string& path) const
{
for (const auto& dataPathId : mDataPathIds)
{
bool foundAll = true;
for (const auto& identifyingFile : dataPathId.second)
{
if (!fs.Exists((path + "\\" + identifyingFile).c_str()))
{
foundAll = false;
break;
}
}
if (foundAll)
{
return dataPathId.first;
}
}
return "";
}
private:
std::map<std::string, std::vector<std::string>> mDataPathIds;
void Parse(const std::string& json)
{
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Object>("data_set_ids"))
{
jsonxx::Object dataSetIds = root.get<jsonxx::Object>("data_set_ids");
for (const auto& v : dataSetIds.kv_map())
{
jsonxx::Object dataSetId = dataSetIds.get<jsonxx::Object>(v.first);
jsonxx::Array identifyingFiles = dataSetId.get<jsonxx::Array>("files");
std::vector<std::string> files;
files.reserve(identifyingFiles.size());
for (const auto& f : identifyingFiles.values())
{
files.emplace_back(f->get<jsonxx::String>());
}
mDataPathIds[v.first] = files;
}
}
}
};
class DataPaths
{
public:
DataPaths(IFileSystem& fs, const char* dataSetsIdsFileName, const char* dataPathFileName)
: mIds(fs, dataSetsIdsFileName)
{
auto stream = fs.Open(dataPathFileName);
std::vector<std::string> paths = Parse(stream->LoadAllToString());
for (const auto& path : paths)
{
// TODO: Store the path and its identity
std::string id = mIds.Identify(fs, path);
auto it = mPaths.find(id);
if (it == std::end(mPaths))
{
mPaths[id] = std::vector < std::string > {path};
}
else
{
it->second.push_back(path);
}
}
}
const std::vector<std::string>& PathsFor(const std::string& id)
{
auto it = mPaths.find(id);
if (it == std::end(mPaths))
{
return mNotFoundResult;
}
else
{
return it->second;
}
}
private:
std::map<std::string, std::vector<std::string>> mPaths;
std::vector<std::string> Parse(const std::string& json)
{
std::vector<std::string> paths;
jsonxx::Object root;
root.parse(json);
if (root.has<jsonxx::Array>("paths"))
{
jsonxx::Array pathsArray = root.get<jsonxx::Array>("paths");
for (const auto& path : pathsArray.values())
{
paths.emplace_back(path->get<jsonxx::String>());
}
}
return paths;
}
// To match to what a game def wants (AePcCd1, AoDemoPsx etc)
// we use SLUS codes for PSX or if it contains ABEWIN.EXE etc then its AoPc.
DataPathIdentities mIds;
std::vector<std::string> mNotFoundResult;
};
TEST(ResourceLocator, Construct)
{
MockFileSystem fs;
const std::string resourceMapsJson = R"(
{
"data_set_ids" :
{
"AoPc": { "files": [ "AbeWin.exe" ] },
"AePc": { "files": [ "Exoddus.exe" ] }
}
}
)";
EXPECT_CALL(fs, OpenProxy(StrEq("datasetids.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));
const std::string dataSetsJson = R"(
{
"paths": [
"F:\\Program Files\\SteamGames\\SteamApps\\common\\Oddworld Abes Exoddus",
"C:\\data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin"
]
}
)";
EXPECT_CALL(fs, OpenProxy(StrEq("datasets.json")))
.WillRepeatedly(Return(new Oddlib::Stream(StringToVector(dataSetsJson))));
EXPECT_CALL(fs, Exists(StrEq("F:\\Program Files\\SteamGames\\SteamApps\\common\\Oddworld Abes Exoddus\\Exoddus.exe")))
.WillOnce(Return(true));
EXPECT_CALL(fs, Exists(StrEq("C:\\data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\AbeWin.exe")))
.WillOnce(Return(false));
EXPECT_CALL(fs, Exists(StrEq("C:\\data\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\Exoddus.exe")))
.WillOnce(Return(false));
// Data paths are saved user paths to game data
// load the list of data paths (if any) and discover what they are
DataPaths dataPaths(fs, "datasetids.json", "datasets.json");
auto aoPaths = dataPaths.PathsFor("AoPc");
ASSERT_EQ(aoPaths.size(), 0u);
auto aePaths = dataPaths.PathsFor("AePc");
ASSERT_EQ(aePaths.size(), 1u);
ASSERT_EQ(aePaths[0], "F:\\Program Files\\SteamGames\\SteamApps\\common\\Oddworld Abes Exoddus");
/*
std::vector<GameDefinition> gds;
// load the enumerated "built-in" game defs
const auto builtInGds = fs.EnumerateFiles("${game_files}\\GameDefinitions");
for (const auto& file : builtInGds)
{
gds.emplace_back(GameDefinition(fs, file.c_str()));
}
// load the enumerated "mod" game defs
const auto modGs = fs.EnumerateFiles("${user_home}\\Alive\\Mods");
for (const auto& file : modGs)
{
gds.emplace_back(GameDefinition(fs, file.c_str()));
}
ResourceMapper mapper;
// Get the user selected game def
GameDefinition& selected = gds[0];
// ask for any missing data sets
//dataPaths.MissingDataSets(selected.RequiredDataSets());
// TODO: Pass in data paths here instead of calling AddDataPath?
// create the resource mapper loading the resource maps from the json db
ResourceLocator resourceLocator(fs, selected, std::move(mapper));
// TODO: Should be a DataPath instance (?)
// locator.AddDataPath(dataPaths[i], i);
// TODO: Allow changing at any point, don't set in ctor?
//resourceLocator.SetGameDefinition(&selected);
// Now we can obtain resources
Resource<Animation> resMapped1 = resourceLocator.Locate<Animation>("SLIGZ.BND_417_1");
resMapped1.Reload();
*/
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QtCore>
#include <QtSql>
#include "tableschema.h"
QSettings *dbSettings = 0;
TableSchema::TableSchema(const QString &table, const QString &env)
: tablename(table)
{
if (!dbSettings) {
QString path = QLatin1String("config") + QDir::separator() + "database.ini";
if (!QFile::exists(path)) {
qCritical("not found, %s", qPrintable(path));
}
dbSettings = new QSettings(path, QSettings::IniFormat);
}
if (openDatabase(env)) {
if (!tablename.isEmpty()) {
QSqlTableModel model;
model.setTable(tablename);
tableFields = model.record();
} else {
qCritical("Empty table name");
}
}
}
bool TableSchema::exists() const
{
return (tableFields.count() > 0);
}
QList<QPair<QString, QString> > TableSchema::getFieldList() const
{
QList<QPair<QString, QString> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
fieldList << QPair<QString, QString>(f.name().toLower(), QString(QVariant::typeToName(f.type())));
}
return fieldList;
}
QList<QPair<QString, int> > TableSchema::getFieldTypeList() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
fieldList << QPair<QString, int>(f.name().toLower(), f.type());
}
return fieldList;
}
int TableSchema::primaryKeyIndex() const
{
QSqlTableModel model;
model.setTable(tablename);
QSqlIndex index = model.primaryKey();
if (index.isEmpty()) {
return -1;
}
QSqlField fi = index.field(0);
return model.record().indexOf(fi.name());
}
QString TableSchema::primaryKeyFieldName() const
{
QSqlTableModel model;
model.setTable(tablename);
QSqlIndex index = model.primaryKey();
if (index.isEmpty()) {
return QString();
}
QSqlField fi = index.field(0);
return fi.name().toLower();
}
int TableSchema::autoValueIndex() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.isAutoValue())
return i;
}
return -1;
}
QString TableSchema::autoValueFieldName() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.isAutoValue())
return f.name().toLower();
}
return QString();
}
QPair<QString, QString> TableSchema::getPrimaryKeyField() const
{
QPair<QString, QString> pair;
int index = primaryKeyIndex();
if (index >= 0) {
QSqlField f = tableFields.field(index);
pair = QPair<QString, QString>(f.name().toLower(), QString(QVariant::typeToName(f.type())));
}
return pair;
}
QPair<QString, int> TableSchema::getPrimaryKeyFieldType() const
{
QPair<QString, int> pair;
int index = primaryKeyIndex();
if (index >= 0) {
QSqlField f = tableFields.field(index);
pair = QPair<QString, int>(f.name().toLower(), f.type());
}
return pair;
}
bool TableSchema::hasLockRevisionField() const
{
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.name().toLower() == "lock_revision") {
return true;
}
}
return false;
}
bool TableSchema::openDatabase(const QString &env) const
{
if (isOpen())
return true;
if (!dbSettings->childGroups().contains(env)) {
qCritical("invalid environment: %s", qPrintable(env));
return false;
}
dbSettings->beginGroup(env);
QString driverType = dbSettings->value("DriverType").toString().trimmed();
if (driverType.isEmpty()) {
qWarning("Parameter 'DriverType' is empty");
}
qDebug("DriverType: %s", qPrintable(driverType));
QSqlDatabase db = QSqlDatabase::addDatabase(driverType);
if (!db.isValid()) {
qWarning("Parameter 'DriverType' is invalid");
return false;
}
QString databaseName = dbSettings->value("DatabaseName").toString().trimmed();
qDebug("DatabaseName: %s", qPrintable(databaseName));
if (!databaseName.isEmpty())
db.setDatabaseName(databaseName);
QString hostName = dbSettings->value("HostName").toString().trimmed();
qDebug("HostName: %s", qPrintable(hostName));
if (!hostName.isEmpty())
db.setHostName(hostName);
int port = dbSettings->value("Port").toInt();
if (port > 0)
db.setPort(port);
QString userName = dbSettings->value("UserName").toString().trimmed();
if (!userName.isEmpty())
db.setUserName(userName);
QString password = dbSettings->value("Password").toString().trimmed();
if (!password.isEmpty())
db.setPassword(password);
QString connectOptions = dbSettings->value("ConnectOptions").toString().trimmed();
if (!connectOptions.isEmpty())
db.setConnectOptions(connectOptions);
dbSettings->endGroup();
if (!db.open()) {
qWarning("Database open error");
return false;
}
qDebug("Database opened successfully");
return true;
}
bool TableSchema::isOpen() const
{
return QSqlDatabase::database().isOpen();
}
QStringList TableSchema::databaseDrivers()
{
return QSqlDatabase::drivers();
}
QStringList TableSchema::tables(const QString &env)
{
QSet<QString> ret;
TableSchema dummy("dummy", env); // to open database
if (QSqlDatabase::database().isOpen()) {
for (QStringListIterator i(QSqlDatabase::database().tables(QSql::Tables)); i.hasNext(); ) {
TableSchema t(i.next());
if (t.exists())
ret << t.tableName(); // If value already exists, the set is left unchanged
}
}
return ret.toList();
}
<commit_msg>removed toLower() from field name conversion.<commit_after>/* Copyright (c) 2010-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QtCore>
#include <QtSql>
#include "tableschema.h"
QSettings *dbSettings = 0;
TableSchema::TableSchema(const QString &table, const QString &env)
: tablename(table)
{
if (!dbSettings) {
QString path = QLatin1String("config") + QDir::separator() + "database.ini";
if (!QFile::exists(path)) {
qCritical("not found, %s", qPrintable(path));
}
dbSettings = new QSettings(path, QSettings::IniFormat);
}
if (openDatabase(env)) {
if (!tablename.isEmpty()) {
QSqlTableModel model;
model.setTable(tablename);
tableFields = model.record();
} else {
qCritical("Empty table name");
}
}
}
bool TableSchema::exists() const
{
return (tableFields.count() > 0);
}
QList<QPair<QString, QString> > TableSchema::getFieldList() const
{
QList<QPair<QString, QString> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
fieldList << QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));
}
return fieldList;
}
QList<QPair<QString, int> > TableSchema::getFieldTypeList() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
fieldList << QPair<QString, int>(f.name(), f.type());
}
return fieldList;
}
int TableSchema::primaryKeyIndex() const
{
QSqlTableModel model;
model.setTable(tablename);
QSqlIndex index = model.primaryKey();
if (index.isEmpty()) {
return -1;
}
QSqlField fi = index.field(0);
return model.record().indexOf(fi.name());
}
QString TableSchema::primaryKeyFieldName() const
{
QSqlTableModel model;
model.setTable(tablename);
QSqlIndex index = model.primaryKey();
if (index.isEmpty()) {
return QString();
}
QSqlField fi = index.field(0);
return fi.name();
}
int TableSchema::autoValueIndex() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.isAutoValue())
return i;
}
return -1;
}
QString TableSchema::autoValueFieldName() const
{
QList<QPair<QString, int> > fieldList;
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.isAutoValue())
return f.name();
}
return QString();
}
QPair<QString, QString> TableSchema::getPrimaryKeyField() const
{
QPair<QString, QString> pair;
int index = primaryKeyIndex();
if (index >= 0) {
QSqlField f = tableFields.field(index);
pair = QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));
}
return pair;
}
QPair<QString, int> TableSchema::getPrimaryKeyFieldType() const
{
QPair<QString, int> pair;
int index = primaryKeyIndex();
if (index >= 0) {
QSqlField f = tableFields.field(index);
pair = QPair<QString, int>(f.name(), f.type());
}
return pair;
}
bool TableSchema::hasLockRevisionField() const
{
for (int i = 0; i < tableFields.count(); ++i) {
QSqlField f = tableFields.field(i);
if (f.name().toLower() == "lock_revision") {
return true;
}
}
return false;
}
bool TableSchema::openDatabase(const QString &env) const
{
if (isOpen())
return true;
if (!dbSettings->childGroups().contains(env)) {
qCritical("invalid environment: %s", qPrintable(env));
return false;
}
dbSettings->beginGroup(env);
QString driverType = dbSettings->value("DriverType").toString().trimmed();
if (driverType.isEmpty()) {
qWarning("Parameter 'DriverType' is empty");
}
qDebug("DriverType: %s", qPrintable(driverType));
QSqlDatabase db = QSqlDatabase::addDatabase(driverType);
if (!db.isValid()) {
qWarning("Parameter 'DriverType' is invalid");
return false;
}
QString databaseName = dbSettings->value("DatabaseName").toString().trimmed();
qDebug("DatabaseName: %s", qPrintable(databaseName));
if (!databaseName.isEmpty())
db.setDatabaseName(databaseName);
QString hostName = dbSettings->value("HostName").toString().trimmed();
qDebug("HostName: %s", qPrintable(hostName));
if (!hostName.isEmpty())
db.setHostName(hostName);
int port = dbSettings->value("Port").toInt();
if (port > 0)
db.setPort(port);
QString userName = dbSettings->value("UserName").toString().trimmed();
if (!userName.isEmpty())
db.setUserName(userName);
QString password = dbSettings->value("Password").toString().trimmed();
if (!password.isEmpty())
db.setPassword(password);
QString connectOptions = dbSettings->value("ConnectOptions").toString().trimmed();
if (!connectOptions.isEmpty())
db.setConnectOptions(connectOptions);
dbSettings->endGroup();
if (!db.open()) {
qWarning("Database open error");
return false;
}
qDebug("Database opened successfully");
return true;
}
bool TableSchema::isOpen() const
{
return QSqlDatabase::database().isOpen();
}
QStringList TableSchema::databaseDrivers()
{
return QSqlDatabase::drivers();
}
QStringList TableSchema::tables(const QString &env)
{
QSet<QString> ret;
TableSchema dummy("dummy", env); // to open database
if (QSqlDatabase::database().isOpen()) {
for (QStringListIterator i(QSqlDatabase::database().tables(QSql::Tables)); i.hasNext(); ) {
TableSchema t(i.next());
if (t.exists())
ret << t.tableName(); // If value already exists, the set is left unchanged
}
}
return ret.toList();
}
<|endoftext|> |
<commit_before>#include<stdio.h>
#include<stdlib.h>
typedef struct stu{
long num;
float scr;
} stu;
stu a[100];
void sort(int left,int right){
if(left >= right) return;
int i = left,j = right;
stu t = a[left];
while(i<j){
while((i<j)&&(a[j].scr >= t.scr))j--;
a[i] = a[j];
while((i<j)&&(a[i].scr <= t.scr))i++;
a[j] = a[i];
}
a[i] = t;
sort(left,i-1);
sort(i+1,right);
}
int main(void){
int k,jjfly;
scanf("%d %d",&jjfly,&k);
for(int i = 0; i < jjfly; i++){
scanf("%ld %f",&a[i].num,&a[i].scr);
}
sort(0,jjfly);
printf("%d %.1f",a[jjfly-k+1].num,a[jjfly-k+1].scr);
return 0;
}<commit_msg>Update 01.cpp<commit_after>#include<stdio.h>
#include<stdlib.h>
typedef struct stu{
long num;
float scr;
} stu;
stu a[100];
void sort(int left,int right){
if(left >= right) return;
int i = left,j = right;
stu t = a[left];
while(i<j){
while((i<j)&&(a[j].scr >= t.scr))j--;
a[i] = a[j];
while((i<j)&&(a[i].scr <= t.scr))i++;
a[j] = a[i];
}
a[i] = t;
sort(left,i-1);
sort(i+1,right);
}
int main(void){
int k,jjfly,i;
scanf("%d %d",&jjfly,&k);
for(i = 0; i < jjfly; i++)
scanf("%ld %f",&a[i].num,&a[i].scr);
sort(0,jjfly);
printf("%d %.1f",a[jjfly-k+1].num,a[jjfly-k+1].scr);
return 0;
}
<|endoftext|> |
<commit_before>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package 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.
Infomap software package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
namespace infomap {
const char* INFOMAP_VERSION = "1.0.0-beta.55";
}
<commit_msg>1.0.0-beta.56<commit_after>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package 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.
Infomap software package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
namespace infomap {
const char* INFOMAP_VERSION = "1.0.0-beta.56";
}
<|endoftext|> |
<commit_before>#include <types.h>
#include <isa/vexISA.h>
#include <string.h>
#include <iomanip>
#include <sstream>
#ifndef __NIOS
#include <strings.h>
uint32 assembleIInstruction(uint7 opcode, uint19 imm19, uint6 regA){
ac_int<32, false> result = 0;
result.set_slc(0, opcode);
result.set_slc(7, imm19);
result.set_slc(26, regA);
return result;
}
uint32 assembleRInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint6 regB){
ac_int<32, false> result = 0;
ac_int<1, false> const0 = 0;
result.set_slc(0, opcode);
result.set_slc(7, const0); //Immediate bit is equal to zero
result.set_slc(14, regDest);
result.set_slc(20, regB);
result.set_slc(26, regA);
return result;
}
uint32 assembleRiInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint13 imm13){
ac_int<32, false> result = 0;
result.set_slc(0, opcode);
result.set_slc(7, imm13);
result.set_slc(20, regDest);
result.set_slc(26, regA);
return result;
}
#else
uint32 assembleIInstruction(uint7 opcode, uint19 imm19, uint6 regA){
uint32 result = 0;
result += opcode & 0x7f;
result += (imm19 & 0x7ffff)<<7;
result += (regA & 0x3f) << 26;
return result;
}
uint32 assembleRInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint6 regB){
uint32 result = 0;
result += opcode & 0x7f;
result += (regDest & 0x3f) << 14;
result += (regB & 0x3f) << 20;
result += (regA & 0x3f) << 26;
return result;
}
uint32 assembleRiInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint13 imm13){
uint32 result = 0;
result += opcode & 0x7f;
result += (imm13 & 0x1fff) << 7;
result += (regDest & 0x3f) << 20;
result += (regA & 0x3f) << 26;
return result;
}
#endif
#ifndef __NIOS
const char* opcodeNames[128] = {
"NOP", "MPYLL", "MPYLLU", "MPYLH", "MPYLHU", "MPYHH", "MPYHHU", "MPYL", "DIVW", "MPYW", "MPYHU", "MPYHS", "MPYLO", "MPYHI", "DIVLO", "DIVHI",
"LDD", "LDW", "LDH", "LDHU", "LDB", "LDBU","LDWU", "?", "STB", "STH", "STW", "STD", "?", "?", "?", "?",
"?", "GOTO", "IGOTO", "CALL", "ICALL", "BR", "BRF", "RETURN", "MOVI", "AUIPC", "RECONFFS", "RECONFEXECUNIT", "?", "?", "?", "STOP",
"SLCTF", "?", "?", "?", "?", "?", "?", "?", "SLCT", "?", "?", "?", "?", "?", "?", "?",
"?", "ADD", "NOR", "AND", "ANDC", "CMPLT", "CMPLTU", "CMPNE", "NOT", "OR", "ORC", "SH1ADD", "SH2ADD", "SH3ADD", "SH4ADD", "SLL",
"SRL", "SRA", "SUB", "XOR", "ADDW", "SUBW", "SLLW", "SRLW", "SRAW", "CMPEQ", "CMPGE", "CMPGEU", "CMPGT", "CMPGTU", "CMPLE", "CMPLEU",
"?", "ADDi", "NORi", "ANDi", "ANDCi", "CMPLTi", "CMPLTUi", "CMPNEi", "NOTi", "ORi", "ORCi", "SH1ADDi", "SH2ADDi", "SH3ADDi", "SH4ADDi", "SLLi",
"SRLi", "SRAi", "SUBi", "XORi", "ADDWi", "?", "SLLWi", "SRLWi", "SRAWi", "CMPEQi", "CMPGEi", "CMPGEUi", "CMPGTi", "CMPGTUi", "CMPLEi", "CMPLEUi"};
std::string printDecodedInstr(ac_int<32, false> instruction){
ac_int<6, false> RA = instruction.slc<6>(26);
ac_int<6, false> RB = instruction.slc<6>(20);
ac_int<6, false> RC = instruction.slc<6>(14);
ac_int<19, true> IMM19 = instruction.slc<19>(7);
ac_int<13, false> IMM13 = instruction.slc<13>(7);
ac_int<13, true> IMM13_signed = instruction.slc<13>(7);
ac_int<7, false> OP = instruction.slc<7>(0);
ac_int<3, false> BEXT = instruction.slc<3>(8);
ac_int<9, false> IMM9 = instruction.slc<9>(11);
ac_int<1, false> isIType = (OP.slc<3>(4) == 2);
ac_int<1, false> isImm = OP.slc<3>(4) == 1 || OP.slc<3>(4) == 6 || OP.slc<3>(4) == 7;
std::stringstream stream;
stream << opcodeNames[OP];
if (OP == 0){
}
else if (isIType)
stream << " r" << RA << ", " << IMM19;
else if (isImm){
stream << " r" << RB << " = " << RA << " 0x";
stream << std::hex << IMM13_signed;
}
else
stream << " r" << RC << " = " << RA << " " << RB;
std::string result(stream.str());
for (int addedSpace = result.size(); addedSpace < 20; addedSpace++)
result.append(" ");
return result;
}
#endif
<commit_msg>Support for the new instruction<commit_after>#include <types.h>
#include <isa/vexISA.h>
#include <string.h>
#include <iomanip>
#include <sstream>
#ifndef __NIOS
#include <strings.h>
uint32 assembleIInstruction(uint7 opcode, uint19 imm19, uint6 regA){
ac_int<32, false> result = 0;
result.set_slc(0, opcode);
result.set_slc(7, imm19);
result.set_slc(26, regA);
return result;
}
uint32 assembleRInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint6 regB){
ac_int<32, false> result = 0;
ac_int<1, false> const0 = 0;
result.set_slc(0, opcode);
result.set_slc(7, const0); //Immediate bit is equal to zero
result.set_slc(14, regDest);
result.set_slc(20, regB);
result.set_slc(26, regA);
return result;
}
uint32 assembleRiInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint13 imm13){
ac_int<32, false> result = 0;
result.set_slc(0, opcode);
result.set_slc(7, imm13);
result.set_slc(20, regDest);
result.set_slc(26, regA);
return result;
}
#else
uint32 assembleIInstruction(uint7 opcode, uint19 imm19, uint6 regA){
uint32 result = 0;
result += opcode & 0x7f;
result += (imm19 & 0x7ffff)<<7;
result += (regA & 0x3f) << 26;
return result;
}
uint32 assembleRInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint6 regB){
uint32 result = 0;
result += opcode & 0x7f;
result += (regDest & 0x3f) << 14;
result += (regB & 0x3f) << 20;
result += (regA & 0x3f) << 26;
return result;
}
uint32 assembleRiInstruction(uint7 opcode, uint6 regDest, uint6 regA, uint13 imm13){
uint32 result = 0;
result += opcode & 0x7f;
result += (imm13 & 0x1fff) << 7;
result += (regDest & 0x3f) << 20;
result += (regA & 0x3f) << 26;
return result;
}
#endif
#ifndef __NIOS
const char* opcodeNames[128] = {
"NOP", "MPYLL", "MPYLLU", "MPYLH", "MPYLHU", "MPYHH", "MPYHHU", "MPYL", "DIVW", "MPYW", "MPYHU", "MPYHS", "MPYLO", "MPYHI", "DIVLO", "DIVHI",
"LDD", "LDW", "LDH", "LDHU", "LDB", "LDBU","LDWU", "?", "STB", "STH", "STW", "STD", "?", "?", "?", "?",
"?", "GOTO", "IGOTO", "CALL", "ICALL", "BR", "BRF", "RETURN", "MOVI", "AUIPC", "RECONFFS", "RECONFEXECUNIT", "?", "?", "?", "STOP",
"SETc", "SETFc", "?", "?", "?", "?", "?", "?", "SLCT", "?", "?", "?", "?", "?", "?", "?",
"?", "ADD", "NOR", "AND", "ANDC", "CMPLT", "CMPLTU", "CMPNE", "NOT", "OR", "ORC", "SH1ADD", "SH2ADD", "SH3ADD", "SH4ADD", "SLL",
"SRL", "SRA", "SUB", "XOR", "ADDW", "SUBW", "SLLW", "SRLW", "SRAW", "CMPEQ", "CMPGE", "CMPGEU", "CMPGT", "CMPGTU", "CMPLE", "CMPLEU",
"?", "ADDi", "NORi", "ANDi", "ANDCi", "CMPLTi", "CMPLTUi", "CMPNEi", "NOTi", "ORi", "ORCi", "SH1ADDi", "SH2ADDi", "SH3ADDi", "SH4ADDi", "SLLi",
"SRLi", "SRAi", "SUBi", "XORi", "ADDWi", "?", "SLLWi", "SRLWi", "SRAWi", "CMPEQi", "CMPGEi", "CMPGEUi", "CMPGTi", "CMPGTUi", "CMPLEi", "CMPLEUi"};
std::string printDecodedInstr(ac_int<32, false> instruction){
ac_int<6, false> RA = instruction.slc<6>(26);
ac_int<6, false> RB = instruction.slc<6>(20);
ac_int<6, false> RC = instruction.slc<6>(14);
ac_int<19, true> IMM19 = instruction.slc<19>(7);
ac_int<13, false> IMM13 = instruction.slc<13>(7);
ac_int<13, true> IMM13_signed = instruction.slc<13>(7);
ac_int<7, false> OP = instruction.slc<7>(0);
ac_int<3, false> BEXT = instruction.slc<3>(8);
ac_int<9, false> IMM9 = instruction.slc<9>(11);
ac_int<1, false> isIType = (OP.slc<3>(4) == 2);
ac_int<1, false> isImm = OP.slc<3>(4) == 1 || OP.slc<3>(4) == 6 || OP.slc<3>(4) == 7;
std::stringstream stream;
stream << opcodeNames[OP];
if (OP == 0){
}
else if (isIType)
stream << " r" << RA << ", " << IMM19;
else if (isImm){
stream << " r" << RB << " = " << RA << " 0x";
stream << std::hex << IMM13_signed;
}
else
stream << " r" << RC << " = " << RA << " " << RB;
std::string result(stream.str());
for (int addedSpace = result.size(); addedSpace < 20; addedSpace++)
result.append(" ");
return result;
}
#endif
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2016 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include "kernel/data.h"
namespace vita
{
///
/// New empty data instance.
///
data::data(dataset_t d) : active_dataset_(d)
{
}
///
/// \param[in] d the active dataset.
///
/// Activates the dataset we want to operate on (training / validation /
/// test set).
///
void data::select(dataset_t d)
{
active_dataset_ = d;
}
///
/// \return the type (training, validation, test) of the active dataset.
///
data::dataset_t data::active_dataset() const
{
return active_dataset_;
}
} // namespace vita
<commit_msg>[DOC] Minor changes to doxygen documentation<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2017 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include "kernel/data.h"
namespace vita
{
///
/// New empty data instance.
///
data::data(dataset_t d) : active_dataset_(d)
{
}
///
/// Activates the dataset we want to operate on (training / validation /
/// test set).
///
/// \param[in] d the active dataset
///
void data::select(dataset_t d)
{
active_dataset_ = d;
}
///
/// \return the type (training, validation, test) of the active dataset
///
data::dataset_t data::active_dataset() const
{
return active_dataset_;
}
} // namespace vita
<|endoftext|> |
<commit_before>/* This file is part of nSkinz by namazso, licensed under the MIT license:
*
* MIT License
*
* Copyright (c) namazso 2018
*
* 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 "kit_parser.hpp"
#include "Utilities/platform.hpp"
#include "nSkinz.hpp"
#include <algorithm>
std::vector<paint_kit> k_skins;
std::vector<paint_kit> k_gloves;
std::vector<paint_kit> k_stickers;
class CCStrike15ItemSchema;
class CCStrike15ItemSystem;
template <typename Key, typename Value>
struct Node_t
{
int previous_id; //0x0000
int next_id; //0x0004
void* _unknown_ptr; //0x0008
int _unknown; //0x000C
Key key; //0x0010
Value value; //0x0014
};
template <typename Key, typename Value>
struct Head_t
{
Node_t<Key, Value>* memory; //0x0000
int allocation_count; //0x0004
int grow_size; //0x0008
int start_element; //0x000C
int next_available; //0x0010
int _unknown; //0x0014
int last_element; //0x0018
}; //Size=0x001C
// could use CUtlString but this is just easier and CUtlString isn't needed anywhere else
struct String_t
{
char* buffer; //0x0000
int capacity; //0x0004
int grow_size; //0x0008
int length; //0x000C
}; //Size=0x0010
struct CPaintKit
{
int id; //0x0000
String_t name; //0x0004
String_t description; //0x0014
String_t item_name; //0x0024
String_t material_name; //0x0034
String_t image_inventory; //0x0044
char pad_0x0054[0x8C]; //0x0054
}; //Size=0x00E0
struct CStickerKit
{
int id;
int item_rarity;
String_t name;
String_t description;
String_t item_name;
String_t material_name;
String_t image_inventory;
int tournament_event_id;
int tournament_team_id;
int tournament_player_id;
bool is_custom_sticker_material;
float rotate_end;
float rotate_start;
float scale_min;
float scale_max;
float wear_min;
float wear_max;
String_t image_inventory2;
String_t image_inventory_large;
std::uint32_t pad0[4];
};
auto initialize_kits() -> void
{
// Search the relative calls
// call ItemSystem
// push dword ptr [esi+0Ch]
// lea ecx, [eax+4]
// call CEconItemSchema::GetPaintKitDefinition
const auto sig_address = platform::find_pattern("client.dll", "\xE8\x00\x00\x00\x00\xFF\x76\x0C\x8D\x48\x04\xE8", "x????xxxxxxx");
// Skip the opcode, read rel32 address
const auto item_system_offset = *reinterpret_cast<std::int32_t*>(sig_address + 1);
// Add the offset to the end of the instruction
const auto item_system_fn = reinterpret_cast<CCStrike15ItemSystem* (*)()>(sig_address + 5 + item_system_offset);
// Skip VTable, first member variable of ItemSystem is ItemSchema
const auto item_schema = reinterpret_cast<CCStrike15ItemSchema*>(std::uintptr_t(item_system_fn()) + sizeof(void*));
// Dump paint kits
{
// Skip the instructions between, skip the opcode, read rel32 address
const auto get_paint_kit_definition_offset = *reinterpret_cast<std::int32_t*>(sig_address + 11 + 1);
// Add the offset to the end of the instruction
const auto get_paint_kit_definition_fn = reinterpret_cast<CPaintKit*(__thiscall*)(CCStrike15ItemSchema*, int)>(sig_address + 11 + 5 + get_paint_kit_definition_offset);
// The last offset is start_element, we need that
// push ebp
// mov ebp, esp
// sub esp, 0Ch
// mov eax, [ecx+298h]
// Skip instructions, skip opcode, read offset
const auto start_element_offset = *reinterpret_cast<std::intptr_t*>(std::uintptr_t(get_paint_kit_definition_fn) + 8 + 2);
// Calculate head base from start_element's offset
const auto head_offset = start_element_offset - 12;
const auto map_head = reinterpret_cast<Head_t<int, CPaintKit*>*>(std::uintptr_t(item_schema) + head_offset);
for(auto i = 0; i <= map_head->last_element; ++i)
{
const auto paint_kit = map_head->memory[i].value;
if(paint_kit->id == 9001)
continue;
const auto wide_name = g_localize->Find(paint_kit->item_name.buffer + 1);
char name[256];
size_t retval;
wcstombs_s(&retval, name, sizeof(name) - 1, wide_name, sizeof(name) - 1);
if(paint_kit->id < 10000)
k_skins.push_back({ paint_kit->id, name });
else
k_gloves.push_back({ paint_kit->id, name });
}
std::sort(k_skins.begin(), k_skins.end());
std::sort(k_gloves.begin(), k_gloves.end());
}
// Dump sticker kits
{
const auto sticker_sig = platform::find_pattern("client.dll", "\x53\x8D\x48\x04\xE8\x00\x00\x00\x00\x8B\x4D\x10", "xxxxx????xxx") + 4;
// Skip the opcode, read rel32 address
const auto get_sticker_kit_definition_offset = *reinterpret_cast<std::intptr_t*>(sticker_sig + 1);
// Add the offset to the end of the instruction
const auto get_sticker_kit_definition_fn = reinterpret_cast<CPaintKit*(__thiscall*)(CCStrike15ItemSchema*, int)>(sticker_sig + 5 + get_sticker_kit_definition_offset);
// The last offset is head_element, we need that
// push ebp
// mov ebp, esp
// push ebx
// push esi
// push edi
// mov edi, ecx
// mov eax, [edi + 2BCh]
// Skip instructions, skip opcode, read offset
const auto start_element_offset = *reinterpret_cast<intptr_t*>(std::uintptr_t(get_sticker_kit_definition_fn) + 8 + 2);
// Calculate head base from start_element's offset
const auto head_offset = start_element_offset - 12;
const auto map_head = reinterpret_cast<Head_t<int, CStickerKit*>*>(std::uintptr_t(item_schema) + head_offset);
for(auto i = 0; i <= map_head->last_element; ++i)
{
const auto sticker_kit = map_head->memory[i].value;
char sticker_name_if_valve_fucked_up_their_translations[64];
auto sticker_name_ptr = sticker_kit->item_name.buffer + 1;
if(strstr(sticker_name_ptr, "StickerKit_dhw2014_dignitas"))
{
strcpy_s(sticker_name_if_valve_fucked_up_their_translations, "StickerKit_dhw2014_teamdignitas");
strcat_s(sticker_name_if_valve_fucked_up_their_translations, sticker_name_ptr + 27);
sticker_name_ptr = sticker_name_if_valve_fucked_up_their_translations;
}
const auto wide_name = g_localize->Find(sticker_name_ptr);
char name[256];
size_t retval;
wcstombs_s(&retval, name, sizeof(name) - 1, wide_name, sizeof(name) - 1);
k_stickers.push_back({ sticker_kit->id, name });
}
std::sort(k_stickers.begin(), k_stickers.end());
k_stickers.insert(k_stickers.begin(), { 0, "None" });
}
}
<commit_msg>fix unicode skin names that i accidentally broke<commit_after>/* This file is part of nSkinz by namazso, licensed under the MIT license:
*
* MIT License
*
* Copyright (c) namazso 2018
*
* 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 "kit_parser.hpp"
#include "Utilities/platform.hpp"
#include "nSkinz.hpp"
#include <algorithm>
std::vector<paint_kit> k_skins;
std::vector<paint_kit> k_gloves;
std::vector<paint_kit> k_stickers;
class CCStrike15ItemSchema;
class CCStrike15ItemSystem;
template <typename Key, typename Value>
struct Node_t
{
int previous_id; //0x0000
int next_id; //0x0004
void* _unknown_ptr; //0x0008
int _unknown; //0x000C
Key key; //0x0010
Value value; //0x0014
};
template <typename Key, typename Value>
struct Head_t
{
Node_t<Key, Value>* memory; //0x0000
int allocation_count; //0x0004
int grow_size; //0x0008
int start_element; //0x000C
int next_available; //0x0010
int _unknown; //0x0014
int last_element; //0x0018
}; //Size=0x001C
// could use CUtlString but this is just easier and CUtlString isn't needed anywhere else
struct String_t
{
char* buffer; //0x0000
int capacity; //0x0004
int grow_size; //0x0008
int length; //0x000C
}; //Size=0x0010
struct CPaintKit
{
int id; //0x0000
String_t name; //0x0004
String_t description; //0x0014
String_t item_name; //0x0024
String_t material_name; //0x0034
String_t image_inventory; //0x0044
char pad_0x0054[0x8C]; //0x0054
}; //Size=0x00E0
struct CStickerKit
{
int id;
int item_rarity;
String_t name;
String_t description;
String_t item_name;
String_t material_name;
String_t image_inventory;
int tournament_event_id;
int tournament_team_id;
int tournament_player_id;
bool is_custom_sticker_material;
float rotate_end;
float rotate_start;
float scale_min;
float scale_max;
float wear_min;
float wear_max;
String_t image_inventory2;
String_t image_inventory_large;
std::uint32_t pad0[4];
};
auto initialize_kits() -> void
{
const auto V_UCS2ToUTF8 = static_cast<int(*)(const wchar_t* ucs2, char* utf8, int len)>(platform::get_export("vstdlib.dll", "V_UCS2ToUTF8"));
// Search the relative calls
// call ItemSystem
// push dword ptr [esi+0Ch]
// lea ecx, [eax+4]
// call CEconItemSchema::GetPaintKitDefinition
const auto sig_address = platform::find_pattern("client.dll", "\xE8\x00\x00\x00\x00\xFF\x76\x0C\x8D\x48\x04\xE8", "x????xxxxxxx");
// Skip the opcode, read rel32 address
const auto item_system_offset = *reinterpret_cast<std::int32_t*>(sig_address + 1);
// Add the offset to the end of the instruction
const auto item_system_fn = reinterpret_cast<CCStrike15ItemSystem* (*)()>(sig_address + 5 + item_system_offset);
// Skip VTable, first member variable of ItemSystem is ItemSchema
const auto item_schema = reinterpret_cast<CCStrike15ItemSchema*>(std::uintptr_t(item_system_fn()) + sizeof(void*));
// Dump paint kits
{
// Skip the instructions between, skip the opcode, read rel32 address
const auto get_paint_kit_definition_offset = *reinterpret_cast<std::int32_t*>(sig_address + 11 + 1);
// Add the offset to the end of the instruction
const auto get_paint_kit_definition_fn = reinterpret_cast<CPaintKit*(__thiscall*)(CCStrike15ItemSchema*, int)>(sig_address + 11 + 5 + get_paint_kit_definition_offset);
// The last offset is start_element, we need that
// push ebp
// mov ebp, esp
// sub esp, 0Ch
// mov eax, [ecx+298h]
// Skip instructions, skip opcode, read offset
const auto start_element_offset = *reinterpret_cast<std::intptr_t*>(std::uintptr_t(get_paint_kit_definition_fn) + 8 + 2);
// Calculate head base from start_element's offset
const auto head_offset = start_element_offset - 12;
const auto map_head = reinterpret_cast<Head_t<int, CPaintKit*>*>(std::uintptr_t(item_schema) + head_offset);
for(auto i = 0; i <= map_head->last_element; ++i)
{
const auto paint_kit = map_head->memory[i].value;
if(paint_kit->id == 9001)
continue;
const auto wide_name = g_localize->Find(paint_kit->item_name.buffer + 1);
char name[256];
//size_t retval;
//wcstombs_s(&retval, name, sizeof(name) - 1, wide_name, sizeof(name) - 1);
//g_localize->ConvertUnicodeToANSI(wide_name, name, sizeof(name));
V_UCS2ToUTF8(wide_name, name, sizeof(name));
if(paint_kit->id < 10000)
k_skins.push_back({ paint_kit->id, name });
else
k_gloves.push_back({ paint_kit->id, name });
}
std::sort(k_skins.begin(), k_skins.end());
std::sort(k_gloves.begin(), k_gloves.end());
}
// Dump sticker kits
{
const auto sticker_sig = platform::find_pattern("client.dll", "\x53\x8D\x48\x04\xE8\x00\x00\x00\x00\x8B\x4D\x10", "xxxxx????xxx") + 4;
// Skip the opcode, read rel32 address
const auto get_sticker_kit_definition_offset = *reinterpret_cast<std::intptr_t*>(sticker_sig + 1);
// Add the offset to the end of the instruction
const auto get_sticker_kit_definition_fn = reinterpret_cast<CPaintKit*(__thiscall*)(CCStrike15ItemSchema*, int)>(sticker_sig + 5 + get_sticker_kit_definition_offset);
// The last offset is head_element, we need that
// push ebp
// mov ebp, esp
// push ebx
// push esi
// push edi
// mov edi, ecx
// mov eax, [edi + 2BCh]
// Skip instructions, skip opcode, read offset
const auto start_element_offset = *reinterpret_cast<intptr_t*>(std::uintptr_t(get_sticker_kit_definition_fn) + 8 + 2);
// Calculate head base from start_element's offset
const auto head_offset = start_element_offset - 12;
const auto map_head = reinterpret_cast<Head_t<int, CStickerKit*>*>(std::uintptr_t(item_schema) + head_offset);
for(auto i = 0; i <= map_head->last_element; ++i)
{
const auto sticker_kit = map_head->memory[i].value;
char sticker_name_if_valve_fucked_up_their_translations[64];
auto sticker_name_ptr = sticker_kit->item_name.buffer + 1;
if(strstr(sticker_name_ptr, "StickerKit_dhw2014_dignitas"))
{
strcpy_s(sticker_name_if_valve_fucked_up_their_translations, "StickerKit_dhw2014_teamdignitas");
strcat_s(sticker_name_if_valve_fucked_up_their_translations, sticker_name_ptr + 27);
sticker_name_ptr = sticker_name_if_valve_fucked_up_their_translations;
}
const auto wide_name = g_localize->Find(sticker_name_ptr);
char name[256];
//size_t retval;
//wcstombs_s(&retval, name, sizeof(name) - 1, wide_name, sizeof(name) - 1);
//g_localize->ConvertUnicodeToANSI(wide_name, name, sizeof(name));
V_UCS2ToUTF8(wide_name, name, sizeof(name));
k_stickers.push_back({ sticker_kit->id, name });
}
std::sort(k_stickers.begin(), k_stickers.end());
k_stickers.insert(k_stickers.begin(), { 0, "None" });
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "Session.hxx"
#include "strmap.hxx"
#include "pool/tpool.hxx"
#include "http/CookieServer.hxx"
#include <string.h>
#include <stdlib.h>
unsigned
lb_session_get(const StringMap &request_headers, const char *cookie_name)
{
const TempPoolLease tpool;
const char *cookie = request_headers.Get("cookie");
if (cookie == NULL)
return 0;
const auto jar = cookie_map_parse(*tpool, cookie);
const char *session = jar.Get(cookie_name);
if (session == NULL)
return 0;
size_t length = strlen(session);
if (length > 8)
/* only parse the upper 32 bits */
session += length - 8;
char *endptr;
unsigned long id = strtoul(session, &endptr, 16);
if (endptr == session || *endptr != 0)
return 0;
return (unsigned)id;
}
<commit_msg>lb/Session: compare only the endptr value<commit_after>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "Session.hxx"
#include "strmap.hxx"
#include "pool/tpool.hxx"
#include "http/CookieServer.hxx"
#include <string.h>
#include <stdlib.h>
unsigned
lb_session_get(const StringMap &request_headers, const char *cookie_name)
{
const TempPoolLease tpool;
const char *cookie = request_headers.Get("cookie");
if (cookie == NULL)
return 0;
const auto jar = cookie_map_parse(*tpool, cookie);
const char *session = jar.Get(cookie_name);
if (session == NULL)
return 0;
size_t length = strlen(session);
const char *end = session + length;
if (length > 8)
/* only parse the upper 32 bits */
session += length - 8;
char *endptr;
unsigned long id = strtoul(session, &endptr, 16);
if (endptr != end)
return 0;
return (unsigned)id;
}
<|endoftext|> |
<commit_before>#include "BedShapeDialog.hpp"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/wx.h>
#include "Polygon.hpp"
#include "BoundingBox.hpp"
#include <wx/numformatter.h>
#include "Model.hpp"
#include "boost/nowide/iostream.hpp"
namespace Slic3r {
namespace GUI {
void BedShapeDialog::build_dialog(ConfigOptionPoints* default_pt)
{
m_panel = new BedShapePanel(this);
m_panel->build_panel(default_pt);
auto main_sizer = new wxBoxSizer(wxVERTICAL);
main_sizer->Add(m_panel, 1, wxEXPAND);
main_sizer->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALIGN_CENTER_HORIZONTAL | wxBOTTOM, 10);
SetSizer(main_sizer);
SetMinSize(GetSize());
main_sizer->SetSizeHints(this);
// needed to actually free memory
this->Bind(wxEVT_CLOSE_WINDOW, ([this](wxCloseEvent e){
EndModal(wxID_OK);
Destroy();
}));
}
void BedShapePanel::build_panel(ConfigOptionPoints* default_pt)
{
// on_change(nullptr);
auto box = new wxStaticBox(this, wxID_ANY, _(L("Shape")));
auto sbsizer = new wxStaticBoxSizer(box, wxVERTICAL);
// shape options
m_shape_options_book = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxSize(300, -1), wxCHB_TOP);
sbsizer->Add(m_shape_options_book);
auto optgroup = init_shape_options_page(_(L("Rectangular")));
ConfigOptionDef def;
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(200, 200) };
def.label = L("Size");
def.tooltip = L("Size in X and Y of the rectangular plate.");
Option option(def, "rect_size");
optgroup->append_single_option_line(option);
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(0, 0) };
def.label = L("Origin");
def.tooltip = L("Distance of the 0,0 G-code coordinate from the front left corner of the rectangle.");
option = Option(def, "rect_origin");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_(L("Circular")));
def.type = coFloat;
def.default_value = new ConfigOptionFloat(200);
def.sidetext = L("mm");
def.label = L("Diameter");
def.tooltip = L("Diameter of the print bed. It is assumed that origin (0,0) is located in the center.");
option = Option(def, "diameter");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_(L("Custom")));
Line line{ "", "" };
line.full_width = 1;
line.widget = [this](wxWindow* parent) {
auto btn = new wxButton(parent, wxID_ANY, _(L("Load shape from STL...")), wxDefaultPosition, wxDefaultSize);
auto sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(btn);
btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent e)
{
load_stl();
}));
return sizer;
};
optgroup->append_line(line);
Bind(wxEVT_CHOICEBOOK_PAGE_CHANGED, ([this](wxCommandEvent e)
{
update_shape();
}));
// right pane with preview canvas
m_canvas = new Bed_2D(this);
m_canvas->m_bed_shape = default_pt->values;
// main sizer
auto top_sizer = new wxBoxSizer(wxHORIZONTAL);
top_sizer->Add(sbsizer, 0, wxEXPAND | wxLeft | wxTOP | wxBOTTOM, 10);
if (m_canvas)
top_sizer->Add(m_canvas, 1, wxEXPAND | wxALL, 10) ;
SetSizerAndFit(top_sizer);
set_shape(default_pt);
update_preview();
}
#define SHAPE_RECTANGULAR 0
#define SHAPE_CIRCULAR 1
#define SHAPE_CUSTOM 2
// Called from the constructor.
// Create a panel for a rectangular / circular / custom bed shape.
ConfigOptionsGroupShp BedShapePanel::init_shape_options_page(wxString title){
auto panel = new wxPanel(m_shape_options_book);
ConfigOptionsGroupShp optgroup;
optgroup = std::make_shared<ConfigOptionsGroup>(panel, _(L("Settings")));
optgroup->label_width = 100;
optgroup->m_on_change = [this](t_config_option_key opt_key, boost::any value){
update_shape();
};
m_optgroups.push_back(optgroup);
panel->SetSizerAndFit(optgroup->sizer);
m_shape_options_book->AddPage(panel, title);
return optgroup;
}
// Called from the constructor.
// Set the initial bed shape from a list of points.
// Deduce the bed shape type(rect, circle, custom)
// This routine shall be smart enough if the user messes up
// with the list of points in the ini file directly.
void BedShapePanel::set_shape(ConfigOptionPoints* points)
{
auto polygon = Polygon::new_scale(points->values);
// is this a rectangle ?
if (points->size() == 4) {
auto lines = polygon.lines();
if (lines[0].parallel_to(lines[2]) && lines[1].parallel_to(lines[3])) {
// okay, it's a rectangle
// find origin
// the || 0 hack prevents "-0" which might confuse the user
int x_min, x_max, y_min, y_max;
x_max = x_min = points->values[0].x;
y_max = y_min = points->values[0].y;
for (auto pt : points->values){
if (x_min > pt.x) x_min = pt.x;
if (x_max < pt.x) x_max = pt.x;
if (y_min > pt.y) y_min = pt.y;
if (y_max < pt.y) y_max = pt.y;
}
if (x_min < 0) x_min = 0;
if (x_max < 0) x_max = 0;
if (y_min < 0) y_min = 0;
if (y_max < 0) y_max = 0;
auto origin = new ConfigOptionPoints{ Pointf(-x_min, -y_min) };
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(x_max - x_min, y_max - y_min) });//[x_max - x_min, y_max - y_min]);
optgroup->set_value("rect_origin", origin);
update_shape();
return;
}
}
// is this a circle ?
{
// Analyze the array of points.Do they reside on a circle ?
auto center = polygon.bounding_box().center();
std::vector<double> vertex_distances;
double avg_dist = 0;
for (auto pt: polygon.points)
{
double distance = center.distance_to(pt);
vertex_distances.push_back(distance);
avg_dist += distance;
}
avg_dist /= vertex_distances.size();
bool defined_value = true;
for (auto el: vertex_distances)
{
if (abs(el - avg_dist) > 10 * SCALED_EPSILON)
defined_value = false;
break;
}
if (defined_value) {
// all vertices are equidistant to center
m_shape_options_book->SetSelection(SHAPE_CIRCULAR);
auto optgroup = m_optgroups[SHAPE_CIRCULAR];
boost::any ret = wxNumberFormatter::ToString(unscale(avg_dist * 2), 0);
optgroup->set_value("diameter", ret);
update_shape();
return;
}
}
if (points->size() < 3) {
// Invalid polygon.Revert to default bed dimensions.
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(200, 200) });
optgroup->set_value("rect_origin", new ConfigOptionPoints{ Pointf(0, 0) });
update_shape();
return;
}
// This is a custom bed shape, use the polygon provided.
m_shape_options_book->SetSelection(SHAPE_CUSTOM);
// Copy the polygon to the canvas, make a copy of the array.
m_canvas->m_bed_shape = points->values;
update_shape();
}
void BedShapePanel::update_preview()
{
if (m_canvas) m_canvas->Refresh();
Refresh();
}
// Update the bed shape from the dialog fields.
void BedShapePanel::update_shape()
{
auto page_idx = m_shape_options_book->GetSelection();
if (page_idx == SHAPE_RECTANGULAR) {
Pointf rect_size, rect_origin;
try{
rect_size = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_size")); }
catch (const std::exception &e){
return;}
try{
rect_origin = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_origin"));
}
catch (const std::exception &e){
return;}
auto x = rect_size.x;
auto y = rect_size.y;
// empty strings or '-' or other things
if (x == 0 || y == 0) return;
double x0 = 0.0;
double y0 = 0.0;
double x1 = x;
double y1 = y;
auto dx = rect_origin.x;
auto dy = rect_origin.y;
x0 -= dx;
x1 -= dx;
y0 -= dy;
y1 -= dy;
m_canvas->m_bed_shape = { Pointf(x0, y0),
Pointf(x1, y0),
Pointf(x1, y1),
Pointf(x0, y1)};
}
else if(page_idx == SHAPE_CIRCULAR) {
double diameter;
try{
diameter = boost::any_cast<double>(m_optgroups[SHAPE_CIRCULAR]->get_value("diameter"));
}
catch (const std::exception &e){
return;
}
if (diameter == 0.0) return ;
auto r = diameter / 2;
auto twopi = 2 * PI;
auto edges = 60;
std::vector<Pointf> points;
for (size_t i = 1; i <= 60; ++i){
auto angle = i * twopi / edges;
points.push_back(Pointf(r*cos(angle), r*sin(angle)));
}
m_canvas->m_bed_shape = points;
}
// $self->{on_change}->();
update_preview();
}
// Loads an stl file, projects it to the XY plane and calculates a polygon.
void BedShapePanel::load_stl()
{
t_file_wild_card vec_FILE_WILDCARDS = get_file_wild_card();
std::vector<std::string> file_types = { "known", "stl", "obj", "amf", "3mf", "prusa" };
wxString MODEL_WILDCARD;
for (auto file_type: file_types)
MODEL_WILDCARD += vec_FILE_WILDCARDS.at(file_type) + "|";
auto dialog = new wxFileDialog(this, _(L("Choose a file to import bed shape from (STL/OBJ/AMF/3MF/PRUSA):")), "", "",
MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (dialog->ShowModal() != wxID_OK) {
dialog->Destroy();
return;
}
wxArrayString input_file;
dialog->GetPaths(input_file);
dialog->Destroy();
std::string file_name = input_file[0].ToStdString();
Model model;
try {
model = Model::read_from_file(file_name);
}
catch (std::exception &e) {
auto msg = _(L("Error! ")) + file_name + " : " + e.what() + ".";
show_error(this, msg);
exit(1);
}
auto mesh = model.mesh();
auto expolygons = mesh.horizontal_projection();
if (expolygons.size() == 0) {
show_error(this, _(L("The selected file contains no geometry.")));
return;
}
if (expolygons.size() > 1) {
show_error(this, _(L("The selected file contains several disjoint areas. This is not supported.")));
return;
}
auto polygon = expolygons[0].contour;
std::vector<Pointf> points;
for (auto pt : polygon.points)
points.push_back(Pointf::new_unscale(pt));
m_canvas->m_bed_shape = points;
update_preview();
}
} // GUI
} // Slic3r
<commit_msg>Fixed calculation of bed origin in bed shape dialog<commit_after>#include "BedShapeDialog.hpp"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/wx.h>
#include "Polygon.hpp"
#include "BoundingBox.hpp"
#include <wx/numformatter.h>
#include "Model.hpp"
#include "boost/nowide/iostream.hpp"
#include <algorithm>
namespace Slic3r {
namespace GUI {
void BedShapeDialog::build_dialog(ConfigOptionPoints* default_pt)
{
m_panel = new BedShapePanel(this);
m_panel->build_panel(default_pt);
auto main_sizer = new wxBoxSizer(wxVERTICAL);
main_sizer->Add(m_panel, 1, wxEXPAND);
main_sizer->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALIGN_CENTER_HORIZONTAL | wxBOTTOM, 10);
SetSizer(main_sizer);
SetMinSize(GetSize());
main_sizer->SetSizeHints(this);
// needed to actually free memory
this->Bind(wxEVT_CLOSE_WINDOW, ([this](wxCloseEvent e){
EndModal(wxID_OK);
Destroy();
}));
}
void BedShapePanel::build_panel(ConfigOptionPoints* default_pt)
{
// on_change(nullptr);
auto box = new wxStaticBox(this, wxID_ANY, _(L("Shape")));
auto sbsizer = new wxStaticBoxSizer(box, wxVERTICAL);
// shape options
m_shape_options_book = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxSize(300, -1), wxCHB_TOP);
sbsizer->Add(m_shape_options_book);
auto optgroup = init_shape_options_page(_(L("Rectangular")));
ConfigOptionDef def;
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(200, 200) };
def.label = L("Size");
def.tooltip = L("Size in X and Y of the rectangular plate.");
Option option(def, "rect_size");
optgroup->append_single_option_line(option);
def.type = coPoints;
def.default_value = new ConfigOptionPoints{ Pointf(0, 0) };
def.label = L("Origin");
def.tooltip = L("Distance of the 0,0 G-code coordinate from the front left corner of the rectangle.");
option = Option(def, "rect_origin");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_(L("Circular")));
def.type = coFloat;
def.default_value = new ConfigOptionFloat(200);
def.sidetext = L("mm");
def.label = L("Diameter");
def.tooltip = L("Diameter of the print bed. It is assumed that origin (0,0) is located in the center.");
option = Option(def, "diameter");
optgroup->append_single_option_line(option);
optgroup = init_shape_options_page(_(L("Custom")));
Line line{ "", "" };
line.full_width = 1;
line.widget = [this](wxWindow* parent) {
auto btn = new wxButton(parent, wxID_ANY, _(L("Load shape from STL...")), wxDefaultPosition, wxDefaultSize);
auto sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(btn);
btn->Bind(wxEVT_BUTTON, ([this](wxCommandEvent e)
{
load_stl();
}));
return sizer;
};
optgroup->append_line(line);
Bind(wxEVT_CHOICEBOOK_PAGE_CHANGED, ([this](wxCommandEvent e)
{
update_shape();
}));
// right pane with preview canvas
m_canvas = new Bed_2D(this);
m_canvas->m_bed_shape = default_pt->values;
// main sizer
auto top_sizer = new wxBoxSizer(wxHORIZONTAL);
top_sizer->Add(sbsizer, 0, wxEXPAND | wxLeft | wxTOP | wxBOTTOM, 10);
if (m_canvas)
top_sizer->Add(m_canvas, 1, wxEXPAND | wxALL, 10) ;
SetSizerAndFit(top_sizer);
set_shape(default_pt);
update_preview();
}
#define SHAPE_RECTANGULAR 0
#define SHAPE_CIRCULAR 1
#define SHAPE_CUSTOM 2
// Called from the constructor.
// Create a panel for a rectangular / circular / custom bed shape.
ConfigOptionsGroupShp BedShapePanel::init_shape_options_page(wxString title){
auto panel = new wxPanel(m_shape_options_book);
ConfigOptionsGroupShp optgroup;
optgroup = std::make_shared<ConfigOptionsGroup>(panel, _(L("Settings")));
optgroup->label_width = 100;
optgroup->m_on_change = [this](t_config_option_key opt_key, boost::any value){
update_shape();
};
m_optgroups.push_back(optgroup);
panel->SetSizerAndFit(optgroup->sizer);
m_shape_options_book->AddPage(panel, title);
return optgroup;
}
// Called from the constructor.
// Set the initial bed shape from a list of points.
// Deduce the bed shape type(rect, circle, custom)
// This routine shall be smart enough if the user messes up
// with the list of points in the ini file directly.
void BedShapePanel::set_shape(ConfigOptionPoints* points)
{
auto polygon = Polygon::new_scale(points->values);
// is this a rectangle ?
if (points->size() == 4) {
auto lines = polygon.lines();
if (lines[0].parallel_to(lines[2]) && lines[1].parallel_to(lines[3])) {
// okay, it's a rectangle
// find origin
coordf_t x_min, x_max, y_min, y_max;
x_max = x_min = points->values[0].x;
y_max = y_min = points->values[0].y;
for (auto pt : points->values)
{
x_min = std::min(x_min, pt.x);
x_max = std::max(x_max, pt.x);
y_min = std::min(y_min, pt.y);
y_max = std::max(y_max, pt.y);
}
auto origin = new ConfigOptionPoints{ Pointf(-x_min, -y_min) };
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(x_max - x_min, y_max - y_min) });//[x_max - x_min, y_max - y_min]);
optgroup->set_value("rect_origin", origin);
update_shape();
return;
}
}
// is this a circle ?
{
// Analyze the array of points.Do they reside on a circle ?
auto center = polygon.bounding_box().center();
std::vector<double> vertex_distances;
double avg_dist = 0;
for (auto pt: polygon.points)
{
double distance = center.distance_to(pt);
vertex_distances.push_back(distance);
avg_dist += distance;
}
avg_dist /= vertex_distances.size();
bool defined_value = true;
for (auto el: vertex_distances)
{
if (abs(el - avg_dist) > 10 * SCALED_EPSILON)
defined_value = false;
break;
}
if (defined_value) {
// all vertices are equidistant to center
m_shape_options_book->SetSelection(SHAPE_CIRCULAR);
auto optgroup = m_optgroups[SHAPE_CIRCULAR];
boost::any ret = wxNumberFormatter::ToString(unscale(avg_dist * 2), 0);
optgroup->set_value("diameter", ret);
update_shape();
return;
}
}
if (points->size() < 3) {
// Invalid polygon.Revert to default bed dimensions.
m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(200, 200) });
optgroup->set_value("rect_origin", new ConfigOptionPoints{ Pointf(0, 0) });
update_shape();
return;
}
// This is a custom bed shape, use the polygon provided.
m_shape_options_book->SetSelection(SHAPE_CUSTOM);
// Copy the polygon to the canvas, make a copy of the array.
m_canvas->m_bed_shape = points->values;
update_shape();
}
void BedShapePanel::update_preview()
{
if (m_canvas) m_canvas->Refresh();
Refresh();
}
// Update the bed shape from the dialog fields.
void BedShapePanel::update_shape()
{
auto page_idx = m_shape_options_book->GetSelection();
if (page_idx == SHAPE_RECTANGULAR) {
Pointf rect_size, rect_origin;
try{
rect_size = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_size")); }
catch (const std::exception &e){
return;}
try{
rect_origin = boost::any_cast<Pointf>(m_optgroups[SHAPE_RECTANGULAR]->get_value("rect_origin"));
}
catch (const std::exception &e){
return;}
auto x = rect_size.x;
auto y = rect_size.y;
// empty strings or '-' or other things
if (x == 0 || y == 0) return;
double x0 = 0.0;
double y0 = 0.0;
double x1 = x;
double y1 = y;
auto dx = rect_origin.x;
auto dy = rect_origin.y;
x0 -= dx;
x1 -= dx;
y0 -= dy;
y1 -= dy;
m_canvas->m_bed_shape = { Pointf(x0, y0),
Pointf(x1, y0),
Pointf(x1, y1),
Pointf(x0, y1)};
}
else if(page_idx == SHAPE_CIRCULAR) {
double diameter;
try{
diameter = boost::any_cast<double>(m_optgroups[SHAPE_CIRCULAR]->get_value("diameter"));
}
catch (const std::exception &e){
return;
}
if (diameter == 0.0) return ;
auto r = diameter / 2;
auto twopi = 2 * PI;
auto edges = 60;
std::vector<Pointf> points;
for (size_t i = 1; i <= 60; ++i){
auto angle = i * twopi / edges;
points.push_back(Pointf(r*cos(angle), r*sin(angle)));
}
m_canvas->m_bed_shape = points;
}
// $self->{on_change}->();
update_preview();
}
// Loads an stl file, projects it to the XY plane and calculates a polygon.
void BedShapePanel::load_stl()
{
t_file_wild_card vec_FILE_WILDCARDS = get_file_wild_card();
std::vector<std::string> file_types = { "known", "stl", "obj", "amf", "3mf", "prusa" };
wxString MODEL_WILDCARD;
for (auto file_type: file_types)
MODEL_WILDCARD += vec_FILE_WILDCARDS.at(file_type) + "|";
auto dialog = new wxFileDialog(this, _(L("Choose a file to import bed shape from (STL/OBJ/AMF/3MF/PRUSA):")), "", "",
MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (dialog->ShowModal() != wxID_OK) {
dialog->Destroy();
return;
}
wxArrayString input_file;
dialog->GetPaths(input_file);
dialog->Destroy();
std::string file_name = input_file[0].ToStdString();
Model model;
try {
model = Model::read_from_file(file_name);
}
catch (std::exception &e) {
auto msg = _(L("Error! ")) + file_name + " : " + e.what() + ".";
show_error(this, msg);
exit(1);
}
auto mesh = model.mesh();
auto expolygons = mesh.horizontal_projection();
if (expolygons.size() == 0) {
show_error(this, _(L("The selected file contains no geometry.")));
return;
}
if (expolygons.size() > 1) {
show_error(this, _(L("The selected file contains several disjoint areas. This is not supported.")));
return;
}
auto polygon = expolygons[0].contour;
std::vector<Pointf> points;
for (auto pt : polygon.points)
points.push_back(Pointf::new_unscale(pt));
m_canvas->m_bed_shape = points;
update_preview();
}
} // GUI
} // Slic3r
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <cv_tracker/image_obj_ranged.h>
#include <std_msgs/Header.h>
#include <fusion_func.h>
#include <runtime_manager/ConfigCarFusion.h>
static void publishTopic();
static ros::Publisher fused_objects;
static std_msgs::Header sensor_header;
static bool ready_;
static void DetectedObjectsCallback(const cv_tracker::image_obj& image_object)
{
ready_ = false;
setDetectedObjects(image_object);
ready_ = true;
}
/*static void ScanImageCallback(const scan2image::ScanImage& scan_image)
{
setScanImage(scan_image);
sensor_header = scan_image.header;
calcDistance();
publishTopic();
}*/
static void PointsImageCallback(const points2image::PointsImage& points_image)
{
if (ready_)
{
setPointsImage(points_image);
sensor_header = points_image.header;
fuse();
publishTopic();
ready_ = false;
}
}
static void publishTopic()
{
/*
* Publish topic(obj position ranged).
*/
cv_tracker::image_obj_ranged fused_objects_msg;
fused_objects_msg.header = sensor_header;
fused_objects_msg.type = getObjectsType();
fused_objects_msg.obj = getObjectsRectRanged();
fused_objects.publish(fused_objects_msg);
}
static void config_cb(const runtime_manager::ConfigCarFusion::ConstPtr& param)
{
setParams(param->min_low_height,
param->max_low_height,
param->max_height,
param->min_points,
param->dispersion);
}
int main(int argc, char **argv)
{
init();
ros::init(argc, argv, "range_fusion");
ros::NodeHandle n;
ros::NodeHandle private_nh("~");
std::string image_topic;
std::string points_topic;
if (private_nh.getParam("image_node", image_topic))
{
ROS_INFO("Setting image node to %s", image_topic.c_str());
}
else
{
ROS_INFO("No image node received, defaulting to image_obj, you can use _image_node:=YOUR_TOPIC");
image_topic = "image_obj";
}
if (private_nh.getParam("points_node", points_topic))
{
ROS_INFO("Setting points node to %s", points_topic.c_str());
}
else
{
ROS_INFO("No points node received, defaulting to vscan_image, you can use _points_node:=YOUR_TOPIC");
points_topic = "/vscan_image";
}
ros::Subscriber image_obj_sub = n.subscribe(image_topic, 1, DetectedObjectsCallback);
//ros::Subscriber scan_image_sub = n.subscribe("scan_image", 1, ScanImageCallback);
ros::Subscriber points_image_sub =n.subscribe(points_topic, 1, PointsImageCallback);
#if _DEBUG
ros::Subscriber image_sub = n.subscribe(IMAGE_TOPIC, 1, IMAGE_CALLBACK);
#endif
fused_objects = n.advertise<cv_tracker::image_obj_ranged>("image_obj_ranged", 1);
ros::Subscriber config_subscriber;
std::string config_topic("/config");
config_topic += ros::this_node::getNamespace() + "/fusion";
config_subscriber = n.subscribe(config_topic, 1, config_cb);
ros::spin();
destroy();
return 0;
}
<commit_msg>change publish timing in range fusion<commit_after>/*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <cv_tracker/image_obj_ranged.h>
#include <std_msgs/Header.h>
#include <fusion_func.h>
#include <runtime_manager/ConfigCarFusion.h>
static void publishTopic();
static ros::Publisher fused_objects;
static std_msgs::Header sensor_header;
bool ready_ = false;
static void DetectedObjectsCallback(const cv_tracker::image_obj& image_object)
{
if (ready_) {
setDetectedObjects(image_object);
fuse();
publishTopic();
ready_ = false;
return;
}
ready_ = true;
}
/*static void ScanImageCallback(const scan2image::ScanImage& scan_image)
{
setScanImage(scan_image);
sensor_header = scan_image.header;
calcDistance();
publishTopic();
}*/
static void PointsImageCallback(const points2image::PointsImage& points_image)
{
if (ready_) {
setPointsImage(points_image);
sensor_header = points_image.header;
fuse();
publishTopic();
ready_ = false;
return;
}
ready_ = true;
}
static void publishTopic()
{
/*
* Publish topic(obj position ranged).
*/
cv_tracker::image_obj_ranged fused_objects_msg;
fused_objects_msg.header = sensor_header;
fused_objects_msg.type = getObjectsType();
fused_objects_msg.obj = getObjectsRectRanged();
fused_objects.publish(fused_objects_msg);
}
static void config_cb(const runtime_manager::ConfigCarFusion::ConstPtr& param)
{
setParams(param->min_low_height,
param->max_low_height,
param->max_height,
param->min_points,
param->dispersion);
}
int main(int argc, char **argv)
{
init();
ros::init(argc, argv, "range_fusion");
ros::NodeHandle n;
ros::NodeHandle private_nh("~");
std::string image_topic;
std::string points_topic;
if (private_nh.getParam("image_node", image_topic))
{
ROS_INFO("Setting image node to %s", image_topic.c_str());
}
else
{
ROS_INFO("No image node received, defaulting to image_obj, you can use _image_node:=YOUR_TOPIC");
image_topic = "image_obj";
}
if (private_nh.getParam("points_node", points_topic))
{
ROS_INFO("Setting points node to %s", points_topic.c_str());
}
else
{
ROS_INFO("No points node received, defaulting to vscan_image, you can use _points_node:=YOUR_TOPIC");
points_topic = "/vscan_image";
}
ros::Subscriber image_obj_sub = n.subscribe(image_topic, 1, DetectedObjectsCallback);
//ros::Subscriber scan_image_sub = n.subscribe("scan_image", 1, ScanImageCallback);
ros::Subscriber points_image_sub =n.subscribe(points_topic, 1, PointsImageCallback);
#if _DEBUG
ros::Subscriber image_sub = n.subscribe(IMAGE_TOPIC, 1, IMAGE_CALLBACK);
#endif
fused_objects = n.advertise<cv_tracker::image_obj_ranged>("image_obj_ranged", 1);
ros::Subscriber config_subscriber;
std::string config_topic("/config");
config_topic += ros::this_node::getNamespace() + "/fusion";
config_subscriber = n.subscribe(config_topic, 1, config_cb);
ros::spin();
destroy();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <vector>
#include "nyx_container.h"
namespace nyx {
class nyx_list : public PyObject {
using ObjectVector = std::vector<PyObject*>;
ObjectVector* vec_{};
public:
inline void _init(void) {
vec_ = new ObjectVector();
}
inline void _dealloc(void) {
if (vec_ != nullptr) {
_clear();
delete vec_;
}
}
inline int _contains(PyObject* o) const {
int cmp{};
for (auto* x : *vec_) {
cmp = PyObject_RichCompareBool(o, x, Py_EQ);
if (cmp != 0)
break;
}
return cmp;
}
inline void _clear(void) {
for (auto* x : *vec_)
Py_DECREF(x);
vec_->clear();
}
inline Py_ssize_t _size(void) const {
return vec_->size();
}
std::string _repr(void) const {
std::ostringstream oss;
oss << "[";
auto begin = vec_->begin();
while (begin != vec_->end()) {
if (PyString_Check(*begin))
oss << "'" << PyString_AsString(*begin) << "'";
else
oss << PyString_AsString(PyObject_Repr(*begin));
if (++begin != vec_->end())
oss << ", ";
}
oss << "]";
return oss.str();
}
inline void _append(PyObject* x) {
vec_->push_back(x);
}
};
static int _nyxlist_init(
nyx_list* self, PyObject* /*args*/, PyObject* /*kwargs*/) {
self->_init();
return 0;
}
static void _nyxlist_dealloc(nyx_list* self) {
self->_dealloc();
}
static PyObject* _nyxlist_repr(nyx_list* self) {
return Py_BuildValue("s", self->_repr().c_str());
}
static PyObject* _nyxlist_clear(nyx_list* self) {
self->_clear();
Py_RETURN_NONE;
}
static PyObject* _nyxlist_size(nyx_list* self) {
return Py_BuildValue("l", self->_size());
}
static PyObject* _nyxlist_append(nyx_list* self, PyObject* v) {
if (v == nullptr)
return nullptr;
if (self == v) {
PyErr_SetString(PyExc_RuntimeError, "append(v): can not append self");
return nullptr;
}
Py_INCREF(v);
self->_append(v);
Py_RETURN_NONE;
}
static Py_ssize_t _nyxlist__meth_length(nyx_list* self) {
return self->_size();
}
static int _nyxlist__meth_contains(nyx_list* self, PyObject* o) {
return self->_contains(o);
}
PyDoc_STRVAR(_nyxlist_doc,
"nyx_list() -> new empty nyx_list\n"
"nyx_list(iterable) -> new nyx_list initialized from iterable's items");
PyDoc_STRVAR(__clear_doc,
"L.clear() -- clear all L items");
PyDoc_STRVAR(__size_doc,
"L.size() -- return number of L items");
PyDoc_STRVAR(__append_doc,
"L.append(object) -- append object to end");
static PySequenceMethods _nyxlist_as_sequence = {
(lenfunc)_nyxlist__meth_length, // sq_length
0, // sq_concat
0, // sq_repeat
0, // sq_item
0, // sq_slice
0, // sq_ass_item
0, // sq_ass_slice
(objobjproc)_nyxlist__meth_contains, // sq_contains
0, // sq_inplace_concat
0, // sq_inplace_repeat
};
static PyMappingMethods _nyxlist_as_mapping = {
(lenfunc)_nyxlist__meth_length, // mp_length
0, // mp_subscript
0, // map_ass_subscript
};
static PyMethodDef _nyxlist_methods[] = {
{"clear", (PyCFunction)_nyxlist_clear, METH_NOARGS, __clear_doc},
{"size", (PyCFunction)_nyxlist_size, METH_NOARGS, __size_doc},
{"append", (PyCFunction)_nyxlist_append, METH_O, __append_doc},
{nullptr}
};
static PyTypeObject _nyxlist_type = {
PyObject_HEAD_INIT(nullptr)
0, // ob_size
"_nyxcore.nyx_list", // tp_name
sizeof(nyx_list), // tp_basicsize
0, // tp_itemsize
(destructor)_nyxlist_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
(reprfunc)_nyxlist_repr, // tp_repr
0, // tp_as_number
&_nyxlist_as_sequence, // tp_as_sequence
&_nyxlist_as_mapping, // tp_as_mapping
(hashfunc)PyObject_HashNotImplemented, // tp_hash
0, // tp_call
(reprfunc)_nyxlist_repr, // tp_str
PyObject_GenericGetAttr, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
_nyxlist_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
_nyxlist_methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)_nyxlist_init, // tp_init
0, // tp_alloc
PyType_GenericNew, // tp_new
};
void nyx_list_wrap(PyObject* m) {
if (PyType_Ready(&_nyxlist_type) < 0)
return;
auto* _type = reinterpret_cast<PyObject*>(&_nyxlist_type);
Py_INCREF(_type);
PyModule_AddObject(m, "nyx_list", _type);
}
}
<commit_msg>:construction: chore(nyx_list): add insert method for nyx_list<commit_after>// Copyright (c) 2018 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <sstream>
#include <vector>
#include "nyx_container.h"
namespace nyx {
class nyx_list : public PyObject {
using ObjectVector = std::vector<PyObject*>;
ObjectVector* vec_{};
public:
inline void _init(void) {
vec_ = new ObjectVector();
}
inline void _dealloc(void) {
if (vec_ != nullptr) {
_clear();
delete vec_;
}
}
inline int _contains(PyObject* o) const {
int cmp{};
for (auto* x : *vec_) {
cmp = PyObject_RichCompareBool(o, x, Py_EQ);
if (cmp != 0)
break;
}
return cmp;
}
inline void _clear(void) {
for (auto* x : *vec_)
Py_DECREF(x);
vec_->clear();
}
inline Py_ssize_t _size(void) const {
return vec_->size();
}
std::string _repr(void) const {
std::ostringstream oss;
oss << "[";
auto begin = vec_->begin();
while (begin != vec_->end()) {
if (PyString_Check(*begin))
oss << "'" << PyString_AsString(*begin) << "'";
else
oss << PyString_AsString(PyObject_Repr(*begin));
if (++begin != vec_->end())
oss << ", ";
}
oss << "]";
return oss.str();
}
inline void _append(PyObject* x) {
vec_->push_back(x);
}
inline void _insert(Py_ssize_t i, PyObject* x) {
vec_->insert(vec_->begin() + i, x);
}
};
static int _nyxlist_init(
nyx_list* self, PyObject* /*args*/, PyObject* /*kwargs*/) {
self->_init();
return 0;
}
static void _nyxlist_dealloc(nyx_list* self) {
self->_dealloc();
}
static PyObject* _nyxlist_repr(nyx_list* self) {
return Py_BuildValue("s", self->_repr().c_str());
}
static PyObject* _nyxlist_clear(nyx_list* self) {
self->_clear();
Py_RETURN_NONE;
}
static PyObject* _nyxlist_size(nyx_list* self) {
return Py_BuildValue("l", self->_size());
}
static PyObject* _nyxlist_append(nyx_list* self, PyObject* v) {
if (v == nullptr)
return nullptr;
if (self == v) {
PyErr_SetString(PyExc_RuntimeError, "append(object): can not append self");
return nullptr;
}
Py_INCREF(v);
self->_append(v);
Py_RETURN_NONE;
}
static PyObject* _nyxlist_insert(nyx_list* self, PyObject* args) {
Py_ssize_t i;
PyObject* v;
if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
return nullptr;
if (v == nullptr) {
PyErr_BadInternalCall();
return nullptr;
}
if (self == v) {
PyErr_SetString(PyExc_RuntimeError,
"insert(index, object): cannot insert self");
return nullptr;
}
auto n = self->_size();
if (n == PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"insert(index, object): cannot add more objects to list");
return nullptr;
}
if (i < 0)
i += n;
if (i < 0 || i > n) {
PyErr_SetString(PyExc_IndexError,
"insert(index, object): index out of range");
return nullptr;
}
Py_INCREF(v);
self->_insert(i, v);
Py_RETURN_NONE;
}
static Py_ssize_t _nyxlist__meth_length(nyx_list* self) {
return self->_size();
}
static int _nyxlist__meth_contains(nyx_list* self, PyObject* o) {
return self->_contains(o);
}
PyDoc_STRVAR(_nyxlist_doc,
"nyx_list() -> new empty nyx_list\n"
"nyx_list(iterable) -> new nyx_list initialized from iterable's items");
PyDoc_STRVAR(__clear_doc,
"L.clear() -- clear all L items");
PyDoc_STRVAR(__size_doc,
"L.size() -- return number of L items");
PyDoc_STRVAR(__append_doc,
"L.append(object) -- append object to end");
PyDoc_STRVAR(__insert_doc,
"L.insert(index, object) -- insert object before index");
static PySequenceMethods _nyxlist_as_sequence = {
(lenfunc)_nyxlist__meth_length, // sq_length
0, // sq_concat
0, // sq_repeat
0, // sq_item
0, // sq_slice
0, // sq_ass_item
0, // sq_ass_slice
(objobjproc)_nyxlist__meth_contains, // sq_contains
0, // sq_inplace_concat
0, // sq_inplace_repeat
};
static PyMappingMethods _nyxlist_as_mapping = {
(lenfunc)_nyxlist__meth_length, // mp_length
0, // mp_subscript
0, // map_ass_subscript
};
static PyMethodDef _nyxlist_methods[] = {
{"clear", (PyCFunction)_nyxlist_clear, METH_NOARGS, __clear_doc},
{"size", (PyCFunction)_nyxlist_size, METH_NOARGS, __size_doc},
{"append", (PyCFunction)_nyxlist_append, METH_O, __append_doc},
{"insert", (PyCFunction)_nyxlist_insert, METH_VARARGS, __insert_doc},
{nullptr}
};
static PyTypeObject _nyxlist_type = {
PyObject_HEAD_INIT(nullptr)
0, // ob_size
"_nyxcore.nyx_list", // tp_name
sizeof(nyx_list), // tp_basicsize
0, // tp_itemsize
(destructor)_nyxlist_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
(reprfunc)_nyxlist_repr, // tp_repr
0, // tp_as_number
&_nyxlist_as_sequence, // tp_as_sequence
&_nyxlist_as_mapping, // tp_as_mapping
(hashfunc)PyObject_HashNotImplemented, // tp_hash
0, // tp_call
(reprfunc)_nyxlist_repr, // tp_str
PyObject_GenericGetAttr, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
_nyxlist_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
_nyxlist_methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)_nyxlist_init, // tp_init
0, // tp_alloc
PyType_GenericNew, // tp_new
};
void nyx_list_wrap(PyObject* m) {
if (PyType_Ready(&_nyxlist_type) < 0)
return;
auto* _type = reinterpret_cast<PyObject*>(&_nyxlist_type);
Py_INCREF(_type);
PyModule_AddObject(m, "nyx_list", _type);
}
}
<|endoftext|> |
<commit_before>// torBlock.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <algorithm>
#include <sstream>
#include <stdarg.h>
#include <vector>
#include <stdio.h>
#include <assert.h>
#include <map>
#include <vector>
inline std::string tolower(const std::string& s)
{
std::string trans = s;
for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i)
*i = ::tolower(*i);
return trans;
}
std::string format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char temp[2048];
vsprintf(temp,fmt, args);
std::string result = temp;
va_end(args);
return result;
}
std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){
std::vector<std::string> tokens;
int numTokens = 0;
bool inQuote = false;
std::ostringstream currentToken;
std::string::size_type pos = in.find_first_not_of(delims);
int currentChar = (pos == std::string::npos) ? -1 : in[pos];
bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
while (pos != std::string::npos && !enoughTokens) {
// get next token
bool tokenDone = false;
bool foundSlash = false;
currentChar = (pos < in.size()) ? in[pos] : -1;
while ((currentChar != -1) && !tokenDone){
tokenDone = false;
if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim
pos ++;
break; // breaks out of while loop
}
if (!useQuotes){
currentToken << char(currentChar);
} else {
switch (currentChar){
case '\\' : // found a backslash
if (foundSlash){
currentToken << char(currentChar);
foundSlash = false;
} else {
foundSlash = true;
}
break;
case '\"' : // found a quote
if (foundSlash){ // found \"
currentToken << char(currentChar);
foundSlash = false;
} else { // found unescaped "
if (inQuote){ // exiting a quote
// finish off current token
tokenDone = true;
inQuote = false;
//slurp off one additional delimeter if possible
if (pos+1 < in.size() &&
delims.find(in[pos+1]) != std::string::npos) {
pos++;
}
} else { // entering a quote
// finish off current token
tokenDone = true;
inQuote = true;
}
}
break;
default:
if (foundSlash){ // don't care about slashes except for above cases
currentToken << '\\';
foundSlash = false;
}
currentToken << char(currentChar);
break;
}
}
pos++;
currentChar = (pos < in.size()) ? in[pos] : -1;
} // end of getting a Token
if (currentToken.str().size() > 0){ // if the token is something add to list
tokens.push_back(currentToken.str());
currentToken.str("");
numTokens ++;
}
enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
if (enoughTokens){
break;
} else{
pos = in.find_first_not_of(delims,pos);
}
} // end of getting all tokens -- either EOL or max tokens reached
if (enoughTokens && pos != std::string::npos) {
std::string lastToken = in.substr(pos);
if (lastToken.size() > 0)
tokens.push_back(lastToken);
}
return tokens;
}
BZ_GET_PLUGIN_VERSION
std::string torMasterList("http://belegost.mit.edu/tor/status/authority");
double lastUpdateTime = -99999.0;
double updateInterval = 3600.0;
std::vector<std::string> exitNodes;
class Handler : public bz_EventHandler
{
public:
virtual void process ( bz_EventData *eventData );
};
Handler handler;
class MyURLHandler: public bz_BaseURLHandler
{
public:
std::string page;
virtual void done ( const char* URL, void * data, unsigned int size, bool complete )
{
char *str = (char*)malloc(size+1);
memcpy(str,data,size);
str[size] = 0;
page += str;
if (!complete)
return;
std::vector<std::string> tokes = tokenize(page,std::string("\n"),0,false);
bool gotKey = false;
for (unsigned int i = 0; i < tokes.size(); i++ )
{
if (!gotKey)
{
if ( tokes[i] == "-----END RSA PUBLIC KEY-----")
{
gotKey = true;
exitNodes.clear(); // only clear when we have a list
}
}
else
{
if ( tokes[i].size() )
{
std::vector<std::string> chunks = tokenize(tokes[i],std::string(" "),0,false);
if ( chunks.size() > 1 )
{
if ( chunks[0] == "r" && chunks.size() > 7 )
exitNodes.push_back(chunks[6]);
}
}
}
}
}
};
class mySlashCommand : public bz_CustomSlashCommandHandler
{
public:
virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params )
{
bz_sendTextMessage(BZ_SERVER,playerID,"torBlock List");
for ( unsigned int i = 0; i < exitNodes.size(); i++ )
bz_sendTextMessage(BZ_SERVER,playerID,exitNodes[i].c_str());
return true;
}
};
mySlashCommand mySlash;
MyURLHandler myURL;
void updateTorList ( void )
{
if ( bz_getCurrentTime() - lastUpdateTime >= updateInterval)
{
lastUpdateTime = bz_getCurrentTime();
myURL.page.clear();
bz_addURLJob(torMasterList.c_str(),&myURL);
}
}
bool isTorAddress ( const char* addy )
{
for ( unsigned int i = 0; i < exitNodes.size(); i++ )
{
if (exitNodes[i] == addy)
return true;
}
return false;
}
BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ )
{
bz_debugMessage(4,"torBlock plugin loaded");
bz_registerEvent(bz_eAllowPlayer,&handler);
bz_registerEvent(bz_eTickEvent,&handler);
bz_registerCustomSlashCommand("torlist",&mySlash);
lastUpdateTime = -updateInterval * 2;
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeCustomSlashCommand("torlist");
bz_removeEvent(bz_eTickEvent,&handler);
bz_removeEvent(bz_eAllowPlayer,&handler);
bz_debugMessage(4,"torBlock plugin unloaded");
return 0;
}
void Handler::process ( bz_EventData *eventData )
{
if (!eventData)
return;
switch (eventData->eventType)
{
case bz_eAllowPlayer:
{
bz_AllowPlayerEventData_V1 *data = (bz_AllowPlayerEventData_V1*)eventData;
if (isTorAddress(data->ipAddress.c_str()))
{
data->allow = false;
data->reason = "Proxy Network Ban";
}
}
break;
case bz_eTickEvent:
updateTorList();
break;
default:
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>that which goes malloc() must also go free()<commit_after>// torBlock.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <algorithm>
#include <sstream>
#include <stdarg.h>
#include <vector>
#include <stdio.h>
#include <assert.h>
#include <map>
#include <vector>
inline std::string tolower(const std::string& s)
{
std::string trans = s;
for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i)
*i = ::tolower(*i);
return trans;
}
std::string format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char temp[2048];
vsprintf(temp,fmt, args);
std::string result = temp;
va_end(args);
return result;
}
std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){
std::vector<std::string> tokens;
int numTokens = 0;
bool inQuote = false;
std::ostringstream currentToken;
std::string::size_type pos = in.find_first_not_of(delims);
int currentChar = (pos == std::string::npos) ? -1 : in[pos];
bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
while (pos != std::string::npos && !enoughTokens) {
// get next token
bool tokenDone = false;
bool foundSlash = false;
currentChar = (pos < in.size()) ? in[pos] : -1;
while ((currentChar != -1) && !tokenDone){
tokenDone = false;
if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim
pos ++;
break; // breaks out of while loop
}
if (!useQuotes){
currentToken << char(currentChar);
} else {
switch (currentChar){
case '\\' : // found a backslash
if (foundSlash){
currentToken << char(currentChar);
foundSlash = false;
} else {
foundSlash = true;
}
break;
case '\"' : // found a quote
if (foundSlash){ // found \"
currentToken << char(currentChar);
foundSlash = false;
} else { // found unescaped "
if (inQuote){ // exiting a quote
// finish off current token
tokenDone = true;
inQuote = false;
//slurp off one additional delimeter if possible
if (pos+1 < in.size() &&
delims.find(in[pos+1]) != std::string::npos) {
pos++;
}
} else { // entering a quote
// finish off current token
tokenDone = true;
inQuote = true;
}
}
break;
default:
if (foundSlash){ // don't care about slashes except for above cases
currentToken << '\\';
foundSlash = false;
}
currentToken << char(currentChar);
break;
}
}
pos++;
currentChar = (pos < in.size()) ? in[pos] : -1;
} // end of getting a Token
if (currentToken.str().size() > 0){ // if the token is something add to list
tokens.push_back(currentToken.str());
currentToken.str("");
numTokens ++;
}
enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
if (enoughTokens){
break;
} else{
pos = in.find_first_not_of(delims,pos);
}
} // end of getting all tokens -- either EOL or max tokens reached
if (enoughTokens && pos != std::string::npos) {
std::string lastToken = in.substr(pos);
if (lastToken.size() > 0)
tokens.push_back(lastToken);
}
return tokens;
}
BZ_GET_PLUGIN_VERSION
std::string torMasterList("http://belegost.mit.edu/tor/status/authority");
double lastUpdateTime = -99999.0;
double updateInterval = 3600.0;
std::vector<std::string> exitNodes;
class Handler : public bz_EventHandler
{
public:
virtual void process ( bz_EventData *eventData );
};
Handler handler;
class MyURLHandler: public bz_BaseURLHandler
{
public:
std::string page;
virtual void done ( const char* URL, void * data, unsigned int size, bool complete )
{
char *str = (char*)malloc(size+1);
memcpy(str,data,size);
str[size] = 0;
page += str;
free(str);
if (!complete)
return;
std::vector<std::string> tokes = tokenize(page,std::string("\n"),0,false);
bool gotKey = false;
for (unsigned int i = 0; i < tokes.size(); i++ )
{
if (!gotKey)
{
if ( tokes[i] == "-----END RSA PUBLIC KEY-----")
{
gotKey = true;
exitNodes.clear(); // only clear when we have a list
}
}
else
{
if ( tokes[i].size() )
{
std::vector<std::string> chunks = tokenize(tokes[i],std::string(" "),0,false);
if ( chunks.size() > 1 )
{
if ( chunks[0] == "r" && chunks.size() > 7 )
exitNodes.push_back(chunks[6]);
}
}
}
}
}
};
class mySlashCommand : public bz_CustomSlashCommandHandler
{
public:
virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params )
{
bz_sendTextMessage(BZ_SERVER,playerID,"torBlock List");
for ( unsigned int i = 0; i < exitNodes.size(); i++ )
bz_sendTextMessage(BZ_SERVER,playerID,exitNodes[i].c_str());
return true;
}
};
mySlashCommand mySlash;
MyURLHandler myURL;
void updateTorList ( void )
{
if ( bz_getCurrentTime() - lastUpdateTime >= updateInterval)
{
lastUpdateTime = bz_getCurrentTime();
myURL.page.clear();
bz_addURLJob(torMasterList.c_str(),&myURL);
}
}
bool isTorAddress ( const char* addy )
{
for ( unsigned int i = 0; i < exitNodes.size(); i++ )
{
if (exitNodes[i] == addy)
return true;
}
return false;
}
BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ )
{
bz_debugMessage(4,"torBlock plugin loaded");
bz_registerEvent(bz_eAllowPlayer,&handler);
bz_registerEvent(bz_eTickEvent,&handler);
bz_registerCustomSlashCommand("torlist",&mySlash);
lastUpdateTime = -updateInterval * 2;
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeCustomSlashCommand("torlist");
bz_removeEvent(bz_eTickEvent,&handler);
bz_removeEvent(bz_eAllowPlayer,&handler);
bz_debugMessage(4,"torBlock plugin unloaded");
return 0;
}
void Handler::process ( bz_EventData *eventData )
{
if (!eventData)
return;
switch (eventData->eventType)
{
case bz_eAllowPlayer:
{
bz_AllowPlayerEventData_V1 *data = (bz_AllowPlayerEventData_V1*)eventData;
if (isTorAddress(data->ipAddress.c_str()))
{
data->allow = false;
data->reason = "Proxy Network Ban";
}
}
break;
case bz_eTickEvent:
updateTorList();
break;
default:
break;
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//******************************************************************************
//*
//* FULLNAME: Single-Chip Microcontroller Real-Time Operating System
//*
//* NICKNAME: scmRTOS
//*
//* PROCESSOR: MSP430 (Texas Instruments)
//*
//* TOOLKIT: EW430 (IAR Systems)
//*
//* PURPOSE: Target Dependent Stuff Source
//*
//* Version: 5.0.0
//*
//*
//* Copyright (c) 2003-2015, scmRTOS Team
//*
//* 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.
//*
//* =================================================================
//* Project sources: https://github.com/scmrtos/scmrtos
//* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation
//* Wiki: https://github.com/scmrtos/scmrtos/wiki
//* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects
//* =================================================================
//*
//******************************************************************************
//* IAR/MSP430 port by Harry E. Zhurov, Copyright (c) 2003-2015
#include <scmRTOS.h>
using namespace OS;
OS::TPrioMaskTable OS::PrioMaskTable;
//------------------------------------------------------------------------------
void TBaseProcess::init_stack_frame( stack_item_t * Stack
, void (*exec)()
#if scmRTOS_DEBUG_ENABLE == 1
, stack_item_t * StackBegin
#endif
)
{
const uint_fast8_t CONTEXT_SIZE = 12;
#if __CORE__ == __430X__
const uint_fast8_t STACK_ITEM_SIZE = 2;
#else
const uint_fast8_t STACK_ITEM_SIZE = 1;
#endif
#if scmRTOS_DEBUG_ENABLE == 1
//-----------------------------------------------------------------------
// Fill stack pool with predefined value for stack consumption checking
//
size_t StackSize = (Stack - StackBegin) - (CONTEXT_SIZE*STACK_ITEM_SIZE + 2);
for(size_t i = 0; i < StackSize; ++i)
{
StackBegin[i] = STACK_DEFAULT_PATTERN;
}
#endif // scmRTOS_DEBUG_ENABLE
//---------------------------------------------------------------
//
// Prepare Process Stack Frame
//
#if __CORE__ == __430X__
#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
uint32_t addr = reinterpret_cast<uint32_t>(exec);
uint16_t addr_l = addr;
uint16_t addr_h = addr >> 16;
*(--Stack) = addr_h; // return from interrupt address (4 MSBs)
*(--Stack) = addr_l; // return from interrupt address (16 LSBs)
*(--Stack) = 0x0008; // SR value: GIE set; ret from ISR address (4 MSBs)
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#else
uint32_t addr = reinterpret_cast<uint32_t>(exec);
uint16_t addr_l = addr;
uint16_t addr_h = addr >> 16;
*(--Stack) = addr_l; // return from interrupt address (16 LSBs)
*(--Stack) = 0x0008 + (addr_h << 12); // SR value: GIE set; ret from ISR address (4 MSBs)
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#endif // scmRTOS_CONTEXT_SWITCH_SCHEME
#else
*(--Stack) = reinterpret_cast<uint16_t>(exec); // return from interrupt address
*(--Stack) = 0x0008; // SR value: GIE set
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#endif
}
//------------------------------------------------------------------------------
#pragma vector=SYSTEM_TIMER_VECTOR
OS_INTERRUPT void OS::system_timer_isr()
{
scmRTOS_ISRW_TYPE ISR;
#if scmRTOS_SYSTIMER_HOOK_ENABLE == 1
system_timer_user_hook();
#endif
Kernel.system_timer();
#if scmRTOS_SYSTIMER_NEST_INTS_ENABLE == 1
ENABLE_NESTED_INTERRUPTS();
#endif
}
//--------------------------------------------------------------------------
<commit_msg>rename local var to prevent hiding of class memeber name<commit_after>//******************************************************************************
//*
//* FULLNAME: Single-Chip Microcontroller Real-Time Operating System
//*
//* NICKNAME: scmRTOS
//*
//* PROCESSOR: MSP430 (Texas Instruments)
//*
//* TOOLKIT: EW430 (IAR Systems)
//*
//* PURPOSE: Target Dependent Stuff Source
//*
//* Version: 5.0.0
//*
//*
//* Copyright (c) 2003-2015, scmRTOS Team
//*
//* 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.
//*
//* =================================================================
//* Project sources: https://github.com/scmrtos/scmrtos
//* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation
//* Wiki: https://github.com/scmrtos/scmrtos/wiki
//* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects
//* =================================================================
//*
//******************************************************************************
//* IAR/MSP430 port by Harry E. Zhurov, Copyright (c) 2003-2015
#include <scmRTOS.h>
using namespace OS;
OS::TPrioMaskTable OS::PrioMaskTable;
//------------------------------------------------------------------------------
void TBaseProcess::init_stack_frame( stack_item_t * Stack
, void (*exec)()
#if scmRTOS_DEBUG_ENABLE == 1
, stack_item_t * StackBegin
#endif
)
{
const uint_fast8_t CONTEXT_SIZE = 12;
#if __CORE__ == __430X__
const uint_fast8_t STACK_ITEM_SIZE = 2;
#else
const uint_fast8_t STACK_ITEM_SIZE = 1;
#endif
#if scmRTOS_DEBUG_ENABLE == 1
//-----------------------------------------------------------------------
// Fill stack pool with predefined value for stack consumption checking
//
size_t StackSz = (Stack - StackBegin) - (CONTEXT_SIZE*STACK_ITEM_SIZE + 2);
for(size_t i = 0; i < StackSz; ++i)
{
StackBegin[i] = STACK_DEFAULT_PATTERN;
}
#endif // scmRTOS_DEBUG_ENABLE
//---------------------------------------------------------------
//
// Prepare Process Stack Frame
//
#if __CORE__ == __430X__
#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
uint32_t addr = reinterpret_cast<uint32_t>(exec);
uint16_t addr_l = addr;
uint16_t addr_h = addr >> 16;
*(--Stack) = addr_h; // return from interrupt address (4 MSBs)
*(--Stack) = addr_l; // return from interrupt address (16 LSBs)
*(--Stack) = 0x0008; // SR value: GIE set; ret from ISR address (4 MSBs)
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#else
uint32_t addr = reinterpret_cast<uint32_t>(exec);
uint16_t addr_l = addr;
uint16_t addr_h = addr >> 16;
*(--Stack) = addr_l; // return from interrupt address (16 LSBs)
*(--Stack) = 0x0008 + (addr_h << 12); // SR value: GIE set; ret from ISR address (4 MSBs)
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#endif // scmRTOS_CONTEXT_SWITCH_SCHEME
#else
*(--Stack) = reinterpret_cast<uint16_t>(exec); // return from interrupt address
*(--Stack) = 0x0008; // SR value: GIE set
Stack -= CONTEXT_SIZE*STACK_ITEM_SIZE; // emulate 12 "push rxx"
StackPointer = Stack;
#endif
}
//------------------------------------------------------------------------------
#pragma vector=SYSTEM_TIMER_VECTOR
OS_INTERRUPT void OS::system_timer_isr()
{
scmRTOS_ISRW_TYPE ISR;
#if scmRTOS_SYSTIMER_HOOK_ENABLE == 1
system_timer_user_hook();
#endif
Kernel.system_timer();
#if scmRTOS_SYSTIMER_NEST_INTS_ENABLE == 1
ENABLE_NESTED_INTERRUPTS();
#endif
}
//--------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int flip(int a, int pos);
void flip(int* a, int pos);
void print(int a);
int solve(int a, int tgt);
int main() {
int a = 0;
for (int i = 0; i < 4; i++) {
string line;
cin >> line;
for (int j = 0; j < 4; j++) {
char c = line[j];
int tmp = (c == 'b') ? 1 : 0;
int shift = i * 4 + j;
a = a | (tmp << shift);
}
}
int minFlip = INT_MAX;
for (int i = 0; i < 16; i++) {
}
}
void print(int a) {
for (int i = 0; i <= 15; i++) {
int tmp = a;
cout << ((tmp >> i) & 1) << " ";
if (i % 4 == 3)
cout << endl;
}
cout << endl;
}
void flip(int* a, int pos) {
int row = pos / 4;
int col = pos % 4;
for (int i = row - 1; i <= row + 1; i++)
for (int j = col - 1; j <= col + 1; j++) {
if (i < 0 || i > 3 || j < 0 || j > 3)
continue;
if (((i == row - 1) && (j == col - 1))
|| ((i == row - 1) && (j == col + 1))
|| ((i == row + 1) && (j == col - 1))
|| ((i == row + 1) && (j == col + 1)))
continue;
int shift = i * 4 + j;
int mask = 1 << shift;
if (mask & *a)
*a = (~mask) & *a;
else
*a = mask | *a;
}
}
int flip(int a, int pos) {
int row = pos / 4;
int col = pos % 4;
for (int i = row - 1; i <= row + 1; i++)
for (int j = col - 1; j <= col + 1; j++) {
if (i < 0 || i > 3 || j < 0 || j > 3)
continue;
if (((i == row - 1) && (j == col - 1))
|| ((i == row - 1) && (j == col + 1))
|| ((i == row + 1) && (j == col - 1))
|| ((i == row + 1) && (j == col + 1)))
continue;
int shift = i * 4 + j;
int mask = 1 << shift;
if (mask & a)
a = (~mask) & a;
else
a = mask | a;
}
return a;
}
int solve(int a, int tgt) {
int step = 0;
for (int i = 0; i < 16; i++) {
int tmp = a;
int bit = (tmp >> i) & 1;
if (bit == tgt)
continue;
int pos = i + 4;
if (pos >= 16)
return INT_MAX;
flip(&a, pos);
print(a);
step++;
}
return step;
}
<commit_msg>p1753b WA<commit_after>#include <iostream>
#include <climits>
using namespace std;
int flip(int a, int pos);
void flip(int* a, int pos);
void print(int a);
int solve(int a, int tgt);
int topDown2LeftRight(int a);
int reverseDirection(int a);
int main() {
int a = 0;
for (int i = 0; i < 4; i++) {
string line;
cin >> line;
for (int j = 0; j < 4; j++) {
char c = line[j];
int tmp = (c == 'b') ? 1 : 0;
int shift = i * 4 + j;
a = a | (tmp << shift);
}
}
int arr[4];
arr[0] = a;
/*
print(arr[0]);
arr[2] = reverseDirection(a);
print(arr[2]);
*/
arr[1] = reverseDirection(a);
arr[2] = topDown2LeftRight(a);
arr[3] = reverseDirection(arr[2]);
int minFlip = INT_MAX;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 4; j++) {
int tmp = solve(arr[j], i);
if (tmp < INT_MAX)
minFlip = tmp;
}
if (minFlip == INT_MAX)
cout << "Impossible" << endl;
else
cout << minFlip << endl;
}
int topDown2LeftRight(int a) {
int ret = 0;
int shift = 0;
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
int pos = row * 4 + col;
int tmp = a;
ret = ret | (((tmp >> pos) & 1) << shift);
shift++;
}
}
return ret;
}
int reverseDirection(int a) {
int ret = 0;
int mask = 0xf;
int shift = 12;
while (a) {
ret = ret | ((a & mask) << shift);
a = a >> 4;
shift -= 4;
}
return ret;
}
void print(int a) {
for (int i = 0; i <= 15; i++) {
int tmp = a;
cout << ((tmp >> i) & 1) << " ";
if (i % 4 == 3)
cout << endl;
}
cout << endl;
}
void flip(int* a, int pos) {
int row = pos / 4;
int col = pos % 4;
for (int i = row - 1; i <= row + 1; i++)
for (int j = col - 1; j <= col + 1; j++) {
if (i < 0 || i > 3 || j < 0 || j > 3)
continue;
if (((i == row - 1) && (j == col - 1))
|| ((i == row - 1) && (j == col + 1))
|| ((i == row + 1) && (j == col - 1))
|| ((i == row + 1) && (j == col + 1)))
continue;
int shift = i * 4 + j;
int mask = 1 << shift;
if (mask & *a)
*a = (~mask) & *a;
else
*a = mask | *a;
}
}
int flip(int a, int pos) {
int row = pos / 4;
int col = pos % 4;
for (int i = row - 1; i <= row + 1; i++)
for (int j = col - 1; j <= col + 1; j++) {
if (i < 0 || i > 3 || j < 0 || j > 3)
continue;
if (((i == row - 1) && (j == col - 1))
|| ((i == row - 1) && (j == col + 1))
|| ((i == row + 1) && (j == col - 1))
|| ((i == row + 1) && (j == col + 1)))
continue;
int shift = i * 4 + j;
int mask = 1 << shift;
if (mask & a)
a = (~mask) & a;
else
a = mask | a;
}
return a;
}
int solve(int a, int tgt) {
int step = 0;
for (int i = 0; i < 16; i++) {
int tmp = a;
int bit = (tmp >> i) & 1;
if (bit == tgt)
continue;
int pos = i + 4;
if (pos >= 16)
return INT_MAX;
flip(&a, pos);
//print(a);
step++;
}
return step;
}
<|endoftext|> |
<commit_before>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* 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.
*/
/*
* This file is part of the CMSIS++ proposal, intended as a CMSIS
* replacement for C++ applications.
*
* [Partly inspired from the LLVM libcxx sources].
* Copyright (c) 2009-2013 by the contributors listed in
* 'LLVM libcxx Credits.txt'. See 'LLVM libcxx License.txt' for details.
*
* References are to ISO/IEC 14882:2011(E) Third edition (2011-09-01)
*/
/**
* @file
* @brief Global synchronised new/delete definitions.
*/
#include <cstddef>
#include <cstdlib>
#include <new>
#include <cmsis-plus/iso/malloc.h>
const std::nothrow_t std::nothrow = std::nothrow_t
{ };
using std::new_handler;
namespace
{
/**
* @brief The current new handler.
* @details
* The initial new_handler is a null pointer.
*/
new_handler __new_handler;
}
/**
* @brief Establishes the function designated by handler as the current new_handler.
* @param handler
* @return The previous handler.
* @details
* The initial new_handler is a null pointer.
*/
new_handler
std::set_new_handler (new_handler handler) noexcept
{
new_handler prev_handler;
// TODO: add scheduler lock
prev_handler = __new_handler;
__new_handler = handler;
return prev_handler;
}
new_handler
std::get_new_handler () noexcept
{
new_handler handler;
// TODO: add scheduler lock
handler = __new_handler;
return handler;
}
/**
* @details
* The allocation function (3.7.4.1) called by a new-expression (5.3.4)
* to allocate size bytes of storage suitably aligned to represent
* any object of that size.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else throw a bad-alloc exception. This requirement is
* binding on a replacement version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void *
__attribute__((weak))
#if defined(__EXCEPTIONS) || defined(__DOXYGEN__)
operator new (std::size_t size) noexcept(false)
#else
operator new (std::size_t size) noexcept
#endif
{ //
if (size == 0)
{
size = 1;
}
void* p;
// Synchronisation primitives already used by estd::malloc,
// no need to use them again here.
while ((p = os::estd::malloc (size)) == 0)
{
// If malloc() fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
{
__new_handler ();
}
else
{
#if defined(__EXCEPTIONS)
throw std::bad_alloc ();
#else
break;
#endif
}
}
return p;
}
/**
* @details
* Same as new(size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else return a null pointer. This nothrow version of operator new
* returns a pointer obtained as if acquired from the (possibly replaced)
* ordinary version. This requirement is binding on a replacement
* version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new (std::size_t size, const std::nothrow_t&) noexcept
{
void* p = 0;
#if defined(__EXCEPTIONS)
try
{
p = ::operator new (size);
}
catch (...)
{
}
#else
p = ::operator new (size);
#endif // __EXCEPTIONS
return p;
}
/**
* @details
* The allocation function (3.7.4.1) called by the array form of a
* new-expression (5.3.4) to allocate size bytes of storage suitably
* aligned to represent any array object of that size or smaller.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
#if defined(__EXCEPTIONS) || defined(__DOXYGEN__)
operator new[] (std::size_t size) noexcept(false)
#else
operator new[] (std::size_t size) noexcept
#endif
{
return ::operator new (size);
}
/**
* @details
* Same as new[](size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t size, const std::nothrow_t&) noexcept
{
void* p = 0;
#if defined(__EXCEPTIONS)
try
{
p = ::operator new[] (size);
}
catch (...)
{
}
#else
p = ::operator new[] (size);
#endif // __EXCEPTIONS
return p;
}
/**
* @details
* The deallocation function (3.7.4.2) called by a delete-expression
* to render the value of ptr invalid.
*
* ptr shall be a null pointer or its value shall be a value returned by
* an earlier call to the (possibly replaced) operator new(os::std::size_t)
* or operator new(os::std::size_t,const std::nothrow_t&) which has not
* been invalidated by an intervening call to operator delete(void*).
*
* If ptr is null, does nothing. Otherwise, reclaims the storage
* allocated by the earlier call to operator new.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr) noexcept
{
if (ptr)
{
// Synchronisation primitives used by free()
os::estd::free (ptr);
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete (void* ptr, std::size_t size __attribute__((unused))) noexcept
{
if (ptr)
{
// Synchronisation primitives used by free()
os::estd::free (ptr);
}
}
#pragma GCC diagnostic push
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation
* to render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the new-expression throws
* an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr, const std::nothrow_t&) noexcept
{
::operator delete (ptr);
}
/**
* @details
* The deallocation function (3.7.4.2) called by the array form of
* a delete-expression to render the value of ptr invalid.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete[] (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete[] (void* ptr, std::size_t size __attribute__((unused))) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation to
* render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the array new-expression
* throws an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr, const std::nothrow_t&) noexcept
{
::operator delete[] (ptr);
}
<commit_msg>libcpp/new.cpp: use scheduler lock<commit_after>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* 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.
*/
/*
* This file is part of the CMSIS++ proposal, intended as a CMSIS
* replacement for C++ applications.
*
* [Partly inspired from the LLVM libcxx sources].
* Copyright (c) 2009-2013 by the contributors listed in
* 'LLVM libcxx Credits.txt'. See 'LLVM libcxx License.txt' for details.
*
* References are to ISO/IEC 14882:2011(E) Third edition (2011-09-01)
*/
/**
* @file
* @brief Global synchronised new/delete definitions.
*/
#include <cstddef>
#include <cstdlib>
#include <new>
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/iso/malloc.h>
const std::nothrow_t std::nothrow = std::nothrow_t
{ };
using std::new_handler;
namespace
{
/**
* @brief The current new handler.
* @details
* The initial new_handler is a null pointer.
*/
new_handler __new_handler;
}
/**
* @brief Establishes the function designated by handler as the current new_handler.
* @param handler
* @return The previous handler.
* @details
* The initial new_handler is a null pointer.
*/
new_handler
std::set_new_handler (new_handler handler) noexcept
{
new_handler prev_handler;
// Use scheduler lock to synchronise access to the handler.
os::rtos::scheduler::critical_section scs;
prev_handler = __new_handler;
__new_handler = handler;
return prev_handler;
}
new_handler
std::get_new_handler () noexcept
{
new_handler handler;
// Use scheduler lock to synchronise access to the handler.
os::rtos::scheduler::critical_section scs;
handler = __new_handler;
return handler;
}
/**
* @details
* The allocation function (3.7.4.1) called by a new-expression (5.3.4)
* to allocate size bytes of storage suitably aligned to represent
* any object of that size.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else throw a bad-alloc exception. This requirement is
* binding on a replacement version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void *
__attribute__((weak))
#if defined(__EXCEPTIONS) || defined(__DOXYGEN__)
operator new (std::size_t size) noexcept(false)
#else
operator new (std::size_t size) noexcept
#endif
{ //
if (size == 0)
{
size = 1;
}
void* p;
// Synchronisation primitives already used by estd::malloc,
// no need to use them again here.
while ((p = os::estd::malloc (size)) == 0)
{
// If malloc() fails and there is a new_handler,
// call it to try free up memory.
if (__new_handler)
{
__new_handler ();
}
else
{
#if defined(__EXCEPTIONS)
throw std::bad_alloc ();
#else
break;
#endif
}
}
return p;
}
/**
* @details
* Same as new(size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* Return a non-null pointer to suitably aligned storage (3.7.4),
* or else return a null pointer. This nothrow version of operator new
* returns a pointer obtained as if acquired from the (possibly replaced)
* ordinary version. This requirement is binding on a replacement
* version of this function.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new (std::size_t size, const std::nothrow_t&) noexcept
{
void* p = 0;
#if defined(__EXCEPTIONS)
try
{
p = ::operator new (size);
}
catch (...)
{
}
#else
p = ::operator new (size);
#endif // __EXCEPTIONS
return p;
}
/**
* @details
* The allocation function (3.7.4.1) called by the array form of a
* new-expression (5.3.4) to allocate size bytes of storage suitably
* aligned to represent any array object of that size or smaller.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
#if defined(__EXCEPTIONS) || defined(__DOXYGEN__)
operator new[] (std::size_t size) noexcept(false)
#else
operator new[] (std::size_t size) noexcept
#endif
{
return ::operator new (size);
}
/**
* @details
* Same as new[](size), except that it is called by a placement
* version of a new-expression when a C++ program prefers a null
* pointer result as an error indication, instead of a bad_alloc exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void*
__attribute__((weak))
operator new[] (std::size_t size, const std::nothrow_t&) noexcept
{
void* p = 0;
#if defined(__EXCEPTIONS)
try
{
p = ::operator new[] (size);
}
catch (...)
{
}
#else
p = ::operator new[] (size);
#endif // __EXCEPTIONS
return p;
}
/**
* @details
* The deallocation function (3.7.4.2) called by a delete-expression
* to render the value of ptr invalid.
*
* ptr shall be a null pointer or its value shall be a value returned by
* an earlier call to the (possibly replaced) operator new(os::std::size_t)
* or operator new(os::std::size_t,const std::nothrow_t&) which has not
* been invalidated by an intervening call to operator delete(void*).
*
* If ptr is null, does nothing. Otherwise, reclaims the storage
* allocated by the earlier call to operator new.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr) noexcept
{
if (ptr)
{
// Synchronisation primitives used by free()
os::estd::free (ptr);
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete (void* ptr, std::size_t size __attribute__((unused))) noexcept
{
if (ptr)
{
// Synchronisation primitives used by free()
os::estd::free (ptr);
}
}
#pragma GCC diagnostic push
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation
* to render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the new-expression throws
* an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete (void* ptr, const std::nothrow_t&) noexcept
{
::operator delete (ptr);
}
/**
* @details
* The deallocation function (3.7.4.2) called by the array form of
* a delete-expression to render the value of ptr invalid.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wc++14-compat"
void
operator delete[] (void* ptr, std::size_t size) noexcept;
void
__attribute__((weak))
operator delete[] (void* ptr, std::size_t size __attribute__((unused))) noexcept
{
::operator delete (ptr);
}
#pragma GCC diagnostic push
/**
* @details
* The deallocation function (3.7.4.2) called by the implementation to
* render the value of ptr invalid when the constructor invoked
* from a nothrow placement version of the array new-expression
* throws an exception.
*
* @note A C++ program may define a function with this function signature
* that displaces the default version defined by the C++ standard library.
*/
void
__attribute__((weak))
operator delete[] (void* ptr, const std::nothrow_t&) noexcept
{
::operator delete[] (ptr);
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2016-2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#if GRPC_ARES != 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
struct grpc_ares_request {
char val;
};
static grpc_ares_request* grpc_dns_lookup_ares_locked_impl(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, bool check_grpclb,
char** service_config_json, int query_timeout_ms,
std::shared_ptr<WorkSerializer> work_serializer) {
return NULL;
}
grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, bool check_grpclb,
char** service_config_json, int query_timeout_ms,
std::shared_ptr<WorkSerializer> work_serializer) =
grpc_dns_lookup_ares_locked_impl;
static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {}
void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
grpc_cancel_ares_request_locked_impl;
grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
void grpc_ares_cleanup(void) {}
static void grpc_resolve_address_ares_impl(const char* name,
const char* default_port,
grpc_pollset_set* interested_parties,
grpc_closure* on_done,
grpc_resolved_addresses** addrs) {}
void (*grpc_resolve_address_ares)(
const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
#endif /* GRPC_ARES != 1 */
<commit_msg>Compiler error<commit_after>/*
*
* Copyright 2016-2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#if GRPC_ARES != 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
struct grpc_ares_request {
char val;
};
static grpc_ares_request* grpc_dns_lookup_ares_locked_impl(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, bool check_grpclb,
char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) {
return NULL;
}
grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, bool check_grpclb,
char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) =
grpc_dns_lookup_ares_locked_impl;
static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {}
void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
grpc_cancel_ares_request_locked_impl;
grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
void grpc_ares_cleanup(void) {}
static void grpc_resolve_address_ares_impl(const char* name,
const char* default_port,
grpc_pollset_set* interested_parties,
grpc_closure* on_done,
grpc_resolved_addresses** addrs) {}
void (*grpc_resolve_address_ares)(
const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
#endif /* GRPC_ARES != 1 */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, 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 "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"
#include <string>
#include <sstream>
namespace libtorrent
{
std::string make_magnet_uri(torrent_handle const& handle)
{
std::stringstream ret;
if (!handle.is_valid()) return ret.str();
std::string name = handle.name();
ret << "magnet:?xt=urn:btih:" << base32encode((char*)handle.info_hash().begin());
if (!name.empty())
ret << "&dn=" << escape_string(name.c_str(), name.length());
torrent_status st = handle.status();
if (!st.current_tracker.empty())
{
ret << "&tr=" << escape_string(st.current_tracker.c_str()
, st.current_tracker.length());
}
else
{
std::vector<announce_entry> const& tr = handle.trackers();
if (!tr.empty())
{
ret << "&tr=" << escape_string(tr[0].url.c_str()
, tr[0].url.length());
}
}
return ret.str();
}
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, fs::path const& save_path
, storage_mode_t storage_mode
, bool paused
, storage_constructor_type sc
, void* userdata)
{
std::string name;
std::string tracker;
boost::optional<std::string> display_name = url_has_argument(uri, "dn");
if (display_name) name = unescape_string(display_name->c_str());
boost::optional<std::string> tracker_string = url_has_argument(uri, "tr");
if (tracker_string) tracker = unescape_string(tracker_string->c_str());
boost::optional<std::string> btih = url_has_argument(uri, "xt");
if (!btih) return torrent_handle();
if (btih->compare(0, 9, "urn:btih:") != 0) return torrent_handle();
sha1_hash info_hash(base32decode(btih->substr(9)));
return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
, name.empty() ? 0 : name.c_str(), save_path, entry()
, storage_mode, paused, sc, userdata);
}
}
<commit_msg>fixed bug in make_magnet_uri<commit_after>/*
Copyright (c) 2007, 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 "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"
#include <string>
#include <sstream>
namespace libtorrent
{
std::string make_magnet_uri(torrent_handle const& handle)
{
std::stringstream ret;
if (!handle.is_valid()) return ret.str();
std::string name = handle.name();
ret << "magnet:?xt=urn:btih:" << base32encode(
std::string((char*)handle.info_hash().begin(), 20));
if (!name.empty())
ret << "&dn=" << escape_string(name.c_str(), name.length());
torrent_status st = handle.status();
if (!st.current_tracker.empty())
{
ret << "&tr=" << escape_string(st.current_tracker.c_str()
, st.current_tracker.length());
}
else
{
std::vector<announce_entry> const& tr = handle.trackers();
if (!tr.empty())
{
ret << "&tr=" << escape_string(tr[0].url.c_str()
, tr[0].url.length());
}
}
return ret.str();
}
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, fs::path const& save_path
, storage_mode_t storage_mode
, bool paused
, storage_constructor_type sc
, void* userdata)
{
std::string name;
std::string tracker;
boost::optional<std::string> display_name = url_has_argument(uri, "dn");
if (display_name) name = unescape_string(display_name->c_str());
boost::optional<std::string> tracker_string = url_has_argument(uri, "tr");
if (tracker_string) tracker = unescape_string(tracker_string->c_str());
boost::optional<std::string> btih = url_has_argument(uri, "xt");
if (!btih) return torrent_handle();
if (btih->compare(0, 9, "urn:btih:") != 0) return torrent_handle();
sha1_hash info_hash(base32decode(btih->substr(9)));
return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
, name.empty() ? 0 : name.c_str(), save_path, entry()
, storage_mode, paused, sc, userdata);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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.1 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "gtest/gtest.h"
#include "utils/Filename.h"
using namespace medialibrary;
TEST( FsUtils, extension )
{
ASSERT_EQ( "ext", utils::file::extension( "file.ext" ) );
ASSERT_EQ( "", utils::file::extension( "file." ) );
ASSERT_EQ( "ext2", utils::file::extension( "file.ext.ext2" ) );
ASSERT_EQ( "", utils::file::extension( "" ) );
ASSERT_EQ( "", utils::file::extension( "file.ext." ) );
}
TEST( FsUtils, directory )
{
ASSERT_EQ( "/a/b/c/", utils::file::directory( "/a/b/c/d.e" ) );
ASSERT_EQ( "/a/b/c/", utils::file::directory( "/a/b/c/" ) );
ASSERT_EQ( "/a/b/", utils::file::directory( "/a/b/c" ) );
ASSERT_EQ( "", utils::file::directory( "" ) );
ASSERT_EQ( "", utils::file::directory( "file.test" ) );
}
TEST( FsUtils, directoryName )
{
ASSERT_EQ( "dé", utils::file::directoryName( "/a/b/c/dé/" ) );
ASSERT_EQ( ".cache", utils::file::directoryName( "/a/b/c/.cache/" ) );
ASSERT_EQ( "p17", utils::file::directoryName( "/c/p/p17" ) );
ASSERT_EQ( ".ssh", utils::file::directoryName( "~/.ssh" ) );
ASSERT_EQ( "emacs.d", utils::file::directoryName( "/home/blob/emacs.d" ) );
ASSERT_EQ( "zef", utils::file::directoryName( "zef" ) );
ASSERT_EQ( "home", utils::file::directoryName( "/home" ) );
ASSERT_EQ( "", utils::file::directoryName( "/" ) );
ASSERT_EQ( "", utils::file::directoryName( "" ) );
ASSERT_EQ( "kill", utils::file::directoryName( "/kill/" ) );
ASSERT_EQ( "bill", utils::file::directoryName( "bill/" ) );
}
TEST( FsUtils, fileName )
{
ASSERT_EQ( "d.e", utils::file::fileName( "/a/b/c/d.e" ) );
ASSERT_EQ( "noextfile", utils::file::fileName( "/a/b/noextfile" ) );
ASSERT_EQ( "file.test", utils::file::fileName( "file.test" ) );
}
TEST( FsUtils, firstFolder )
{
ASSERT_EQ( "f00", utils::file::firstFolder( "f00/bar/" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "/f00/bar" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "////f00/bar" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "/f00/" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "f00/" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/f00" ) );
ASSERT_EQ( "", utils::file::firstFolder( "" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/foo.bar" ) );
}
TEST( FsUtils, removePath )
{
ASSERT_EQ( "bar/", utils::file::removePath( "f00/bar/", "f00" ) );
ASSERT_EQ( "bar/", utils::file::removePath( "/f00/bar/", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "f00/bar", "f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00/bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "////f00/bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00///bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00///bar", "/f00/" ) );
ASSERT_EQ( "bar", utils::file::removePath( "bar", "" ) );
ASSERT_EQ( "", utils::file::removePath( "bar/", "bar" ) );
ASSERT_EQ( "", utils::file::removePath( "/f00/", "/f00/" ) );
ASSERT_EQ( "/f00", utils::file::removePath( "/f00", "/path/not/found" ) );
ASSERT_EQ( "/f00", utils::file::removePath( "/f00", "/loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongstring/" ) );
}
TEST( FsUtils, parentFolder )
{
ASSERT_EQ( "/a/b/", utils::file::parentDirectory( "/a/b/c/" ) );
ASSERT_EQ( "/a/b/", utils::file::parentDirectory( "/a/b/c" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "" ) );
#ifdef _WIN32
ASSERT_EQ( "C:\\a/b/", utils::file::parentDirectory( "C:\\a/b/c" ) );
ASSERT_EQ( "C:/a/b/", utils::file::parentDirectory( "C:/a/b/c\\" ) );
ASSERT_EQ( "C:\\a\\b\\", utils::file::parentDirectory( "C:\\a\\b\\c\\" ) );
ASSERT_EQ( "C:\\a\\b\\", utils::file::parentDirectory( "C:\\a\\b\\c" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "C:\\" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "C:/" ) );
#endif
}
TEST( FsUtils, toLocalPath )
{
#ifndef _WIN32
ASSERT_EQ( "/a/b/c/movie.avi", utils::file::toLocalPath( "file:///a/b/c/movie.avi" ) );
ASSERT_EQ( "/yea /sp ace", utils::file::toLocalPath( "file:///yea%20/sp%20ace" ) );
ASSERT_EQ( "/tést/ßóíú/file", utils::file::toLocalPath( "file:///t%C3%A9st/%C3%9F%C3%B3%C3%AD%C3%BA/file" ) );
ASSERT_EQ( "/&/#/~", utils::file::toLocalPath( "file:///%26/%23/%7E" ) );
#else
ASSERT_EQ( "a\\b\\c\\movie.avi", utils::file::toLocalPath( "file:///a/b/c/movie.avi" ) );
ASSERT_EQ( "x\\yea \\sp ace", utils::file::toLocalPath( "file:///x/yea%20/sp%20ace" ) );
ASSERT_EQ( "d\\tést\\ßóíú\\file", utils::file::toLocalPath( "file:///d/t%C3%A9st/%C3%9F%C3%B3%C3%AD%C3%BA/file" ) );
ASSERT_EQ( "c\\&\\#\\~", utils::file::toLocalPath( "file:///c/%26/%23/%7E" ) );
#endif
}
TEST( FsUtils, stripScheme )
{
ASSERT_EQ( "space%20marine", utils::file::stripScheme( "sc2://space%20marine" ) );
ASSERT_EQ( "bl%40bla", utils::file::stripScheme( "bl%40bla" ) );
ASSERT_EQ( "", utils::file::stripScheme( "vlc://" ) );
ASSERT_EQ( "leaf/ern/%C3%A7a/pak.one", utils::file::stripScheme( "bteam://leaf/ern/%C3%A7a/pak.one" ) );
ASSERT_EQ( "/I", utils::file::stripScheme( "file:///I" ) );
}
TEST( FsUtils, scheme )
{
ASSERT_EQ( "scheme://", utils::file::scheme( "scheme://on/them/33.spy" ) );
ASSERT_EQ( "file://", utils::file::scheme( "file:///l/z/4/" ) );
ASSERT_EQ( "miel://", utils::file::scheme( "miel://nuage.mkv" ) );
ASSERT_EQ( "://", utils::file::scheme( ":////\\//" ) );
}
TEST( FsUtils, schemeIs )
{
ASSERT_TRUE( utils::file::schemeIs( "attachment://", "attachment://" ) );
ASSERT_TRUE( utils::file::schemeIs( "attachment://", "attachment://picture0.jpg" ) );
ASSERT_FALSE( utils::file::schemeIs( "boboop://", "/path/to/spaces%20here" ) );
}
TEST( FsUtils, splitPath )
{
std::stack<std::string> st_file;
st_file.push( "[ MACHiN ] 2001 nice movie!.mkv" );
st_file.push( "films & séries" );
st_file.push( "léà" );
st_file.push( "home" );
auto split = utils::file::splitPath( "/home/léà/films & séries/[ MACHiN ] 2001 nice movie!.mkv", false );
ASSERT_TRUE( st_file == split );
std::stack<std::string> st_folder;
st_folder.push( "Русские песни" );
st_folder.push( "~" );
split = utils::file::splitPath( "~/Русские песни/", true );
ASSERT_TRUE( st_folder == split );
}
TEST( FsUtils, stripExtension )
{
ASSERT_EQ( "seaOtter", utils::file::stripExtension( "seaOtter.mkv" ) );
ASSERT_EQ( "", utils::file::stripExtension( "" ) );
ASSERT_EQ( "dummy", utils::file::stripExtension( "dummy" ) );
ASSERT_EQ( "test.with.dot", utils::file::stripExtension( "test.with.dot.ext" ) );
}
<commit_msg>tests: Add a path -> mrl test<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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.1 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "gtest/gtest.h"
#include "utils/Filename.h"
using namespace medialibrary;
TEST( FsUtils, extension )
{
ASSERT_EQ( "ext", utils::file::extension( "file.ext" ) );
ASSERT_EQ( "", utils::file::extension( "file." ) );
ASSERT_EQ( "ext2", utils::file::extension( "file.ext.ext2" ) );
ASSERT_EQ( "", utils::file::extension( "" ) );
ASSERT_EQ( "", utils::file::extension( "file.ext." ) );
}
TEST( FsUtils, directory )
{
ASSERT_EQ( "/a/b/c/", utils::file::directory( "/a/b/c/d.e" ) );
ASSERT_EQ( "/a/b/c/", utils::file::directory( "/a/b/c/" ) );
ASSERT_EQ( "/a/b/", utils::file::directory( "/a/b/c" ) );
ASSERT_EQ( "", utils::file::directory( "" ) );
ASSERT_EQ( "", utils::file::directory( "file.test" ) );
}
TEST( FsUtils, directoryName )
{
ASSERT_EQ( "dé", utils::file::directoryName( "/a/b/c/dé/" ) );
ASSERT_EQ( ".cache", utils::file::directoryName( "/a/b/c/.cache/" ) );
ASSERT_EQ( "p17", utils::file::directoryName( "/c/p/p17" ) );
ASSERT_EQ( ".ssh", utils::file::directoryName( "~/.ssh" ) );
ASSERT_EQ( "emacs.d", utils::file::directoryName( "/home/blob/emacs.d" ) );
ASSERT_EQ( "zef", utils::file::directoryName( "zef" ) );
ASSERT_EQ( "home", utils::file::directoryName( "/home" ) );
ASSERT_EQ( "", utils::file::directoryName( "/" ) );
ASSERT_EQ( "", utils::file::directoryName( "" ) );
ASSERT_EQ( "kill", utils::file::directoryName( "/kill/" ) );
ASSERT_EQ( "bill", utils::file::directoryName( "bill/" ) );
}
TEST( FsUtils, fileName )
{
ASSERT_EQ( "d.e", utils::file::fileName( "/a/b/c/d.e" ) );
ASSERT_EQ( "noextfile", utils::file::fileName( "/a/b/noextfile" ) );
ASSERT_EQ( "file.test", utils::file::fileName( "file.test" ) );
}
TEST( FsUtils, firstFolder )
{
ASSERT_EQ( "f00", utils::file::firstFolder( "f00/bar/" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "/f00/bar" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "////f00/bar" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "/f00/" ) );
ASSERT_EQ( "f00", utils::file::firstFolder( "f00/" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/f00" ) );
ASSERT_EQ( "", utils::file::firstFolder( "" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/" ) );
ASSERT_EQ( "", utils::file::firstFolder( "/foo.bar" ) );
}
TEST( FsUtils, removePath )
{
ASSERT_EQ( "bar/", utils::file::removePath( "f00/bar/", "f00" ) );
ASSERT_EQ( "bar/", utils::file::removePath( "/f00/bar/", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "f00/bar", "f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00/bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "////f00/bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00///bar", "/f00" ) );
ASSERT_EQ( "bar", utils::file::removePath( "/f00///bar", "/f00/" ) );
ASSERT_EQ( "bar", utils::file::removePath( "bar", "" ) );
ASSERT_EQ( "", utils::file::removePath( "bar/", "bar" ) );
ASSERT_EQ( "", utils::file::removePath( "/f00/", "/f00/" ) );
ASSERT_EQ( "/f00", utils::file::removePath( "/f00", "/path/not/found" ) );
ASSERT_EQ( "/f00", utils::file::removePath( "/f00", "/loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongstring/" ) );
}
TEST( FsUtils, parentFolder )
{
ASSERT_EQ( "/a/b/", utils::file::parentDirectory( "/a/b/c/" ) );
ASSERT_EQ( "/a/b/", utils::file::parentDirectory( "/a/b/c" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "" ) );
#ifdef _WIN32
ASSERT_EQ( "C:\\a/b/", utils::file::parentDirectory( "C:\\a/b/c" ) );
ASSERT_EQ( "C:/a/b/", utils::file::parentDirectory( "C:/a/b/c\\" ) );
ASSERT_EQ( "C:\\a\\b\\", utils::file::parentDirectory( "C:\\a\\b\\c\\" ) );
ASSERT_EQ( "C:\\a\\b\\", utils::file::parentDirectory( "C:\\a\\b\\c" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "C:\\" ) );
ASSERT_EQ( "", utils::file::parentDirectory( "C:/" ) );
#endif
}
TEST( FsUtils, toLocalPath )
{
#ifndef _WIN32
ASSERT_EQ( "/a/b/c/movie.avi", utils::file::toLocalPath( "file:///a/b/c/movie.avi" ) );
ASSERT_EQ( "/yea /sp ace", utils::file::toLocalPath( "file:///yea%20/sp%20ace" ) );
ASSERT_EQ( "/tést/ßóíú/file", utils::file::toLocalPath( "file:///t%C3%A9st/%C3%9F%C3%B3%C3%AD%C3%BA/file" ) );
ASSERT_EQ( "/&/#/~", utils::file::toLocalPath( "file:///%26/%23/%7E" ) );
#else
ASSERT_EQ( "a\\b\\c\\movie.avi", utils::file::toLocalPath( "file:///a/b/c/movie.avi" ) );
ASSERT_EQ( "x\\yea \\sp ace", utils::file::toLocalPath( "file:///x/yea%20/sp%20ace" ) );
ASSERT_EQ( "d\\tést\\ßóíú\\file", utils::file::toLocalPath( "file:///d/t%C3%A9st/%C3%9F%C3%B3%C3%AD%C3%BA/file" ) );
ASSERT_EQ( "c\\&\\#\\~", utils::file::toLocalPath( "file:///c/%26/%23/%7E" ) );
#endif
}
TEST( FsUtils, toMrl )
{
#ifndef _WIN32
ASSERT_EQ( "/yea /sp ace", utils::file::toLocalPath( "file:///yea%20/sp%20ace" ) );
ASSERT_EQ( "/c/foo/bar.mkv", utils::file::toLocalPath( "file:///c/foo/bar.mkv" ) );
#else
ASSERT_EQ( "c\\foo\\bar.mkv", utils::file::toLocalPath( "file:///c/foo/bar.mkv" ) );
ASSERT_EQ( "x\\yea \\sp ace", utils::file::toLocalPath( "file:///x/yea%20/sp%20ace" ) );
#endif
}
TEST( FsUtils, stripScheme )
{
ASSERT_EQ( "space%20marine", utils::file::stripScheme( "sc2://space%20marine" ) );
ASSERT_EQ( "bl%40bla", utils::file::stripScheme( "bl%40bla" ) );
ASSERT_EQ( "", utils::file::stripScheme( "vlc://" ) );
ASSERT_EQ( "leaf/ern/%C3%A7a/pak.one", utils::file::stripScheme( "bteam://leaf/ern/%C3%A7a/pak.one" ) );
ASSERT_EQ( "/I", utils::file::stripScheme( "file:///I" ) );
}
TEST( FsUtils, scheme )
{
ASSERT_EQ( "scheme://", utils::file::scheme( "scheme://on/them/33.spy" ) );
ASSERT_EQ( "file://", utils::file::scheme( "file:///l/z/4/" ) );
ASSERT_EQ( "miel://", utils::file::scheme( "miel://nuage.mkv" ) );
ASSERT_EQ( "://", utils::file::scheme( ":////\\//" ) );
}
TEST( FsUtils, schemeIs )
{
ASSERT_TRUE( utils::file::schemeIs( "attachment://", "attachment://" ) );
ASSERT_TRUE( utils::file::schemeIs( "attachment://", "attachment://picture0.jpg" ) );
ASSERT_FALSE( utils::file::schemeIs( "boboop://", "/path/to/spaces%20here" ) );
}
TEST( FsUtils, splitPath )
{
std::stack<std::string> st_file;
st_file.push( "[ MACHiN ] 2001 nice movie!.mkv" );
st_file.push( "films & séries" );
st_file.push( "léà" );
st_file.push( "home" );
auto split = utils::file::splitPath( "/home/léà/films & séries/[ MACHiN ] 2001 nice movie!.mkv", false );
ASSERT_TRUE( st_file == split );
std::stack<std::string> st_folder;
st_folder.push( "Русские песни" );
st_folder.push( "~" );
split = utils::file::splitPath( "~/Русские песни/", true );
ASSERT_TRUE( st_folder == split );
}
TEST( FsUtils, stripExtension )
{
ASSERT_EQ( "seaOtter", utils::file::stripExtension( "seaOtter.mkv" ) );
ASSERT_EQ( "", utils::file::stripExtension( "" ) );
ASSERT_EQ( "dummy", utils::file::stripExtension( "dummy" ) );
ASSERT_EQ( "test.with.dot", utils::file::stripExtension( "test.with.dot.ext" ) );
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "note.h"
#include "filesystemmodel.h"
#include "preferences.h"
#include <QTextStream>
#include <QFile>
#include <QModelIndex>
#include <QInputDialog>
#include <QMouseEvent>
#include <QDesktopServices>
#include <QtConcurrentRun>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
NobleNote::NobleNote(){
setupUi(this);
//TODO: enable drag and drop.
//TrayIcon
QIcon icon = QIcon(":nobleNote");
TIcon = new QSystemTrayIcon(this);
TIcon->setIcon(icon);
TIcon->show();
//TrayIconContextMenu
iMenu = new QMenu(this);
minimize_restore_action = new QAction(tr("&Minimize"),this);
quit_action = new QAction(tr("&Quit"),this);
iMenu->addAction(minimize_restore_action);
iMenu->addAction(quit_action);
TIcon->setContextMenu(iMenu); //setting contextmenu for the systray
QDir nbDir(QDir::homePath() + "/.nobleNote/Journals");
if(!nbDir.exists())
nbDir.mkdir(QDir::homePath() + "/.nobleNote/Journals");
QString file(QDir::homePath() + "/.nobleNote/nobleNote.conf");
QSettings settings(file, QSettings::IniFormat);
if(!settings.isWritable()){
QTextStream myOutput;
myOutput << "W: nobelNote.conf is not writable!" << endl;
}
pref = new Preferences(this);
pref->lineEdit->setText(settings.value("Path to note folders").toString());
if(pref->lineEdit->text().isEmpty())
origPath = QDir::homePath() + "/.nobleNote";
else
origPath = pref->lineEdit->text();
splitter = new QSplitter(centralwidget);
gridLayout->addWidget(splitter, 0, 0);
folderModel = new FileSystemModel(this);
folderModel->setRootPath(origPath);
folderModel->setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
folderModel->setReadOnly(false); // enable drag drop
//folderModel->setNameFilters(QStringList("Journals")); TODO:DON'T show journals.
noteModel = new FileSystemModel(this);
noteModel->setRootPath(origPath); //just as an example
noteModel->setFilter(QDir::Files);
noteModel->setReadOnly(false);
folderList = new QListView(splitter);
noteList = new QListView(splitter);
QList<QListView*> listViews;
listViews << folderList << noteList;
foreach(QListView* list, listViews)
{
list->setContextMenuPolicy(Qt::CustomContextMenu);
//list->setSelectionMode(QAbstractItemView::SingleSelection); // single item can be draged or droped
list->setDragDropMode(QAbstractItemView::DragDrop);
list->viewport()->setAcceptDrops(true);
list->setDropIndicatorShown(true);
list->setDefaultDropAction(Qt::MoveAction);
}
noteList->setDragEnabled(true);
folderList->setDragEnabled(false);
folderList->setModel(folderModel);
folderList->setRootIndex(folderModel->index(origPath));
noteList->setEditTriggers(QListView::EditKeyPressed);
noteList->setModel(noteModel);
noteList->setRootIndex(noteModel->index(origPath));
//QTimer::singleShot(2000,this,SLOT(setFirstFolderCurrent()));
//TODO: make it possible to import notes from some other folder or even another program
// single shot connect
connect(folderModel,SIGNAL(directoryLoaded(QString)), this,
SLOT(setFirstFolderCurrent(QString)),Qt::QueuedConnection);
connect(actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(TIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); //handles systray-symbol
connect(minimize_restore_action, SIGNAL(triggered()), this, SLOT(tray_actions()));
connect(quit_action, SIGNAL(triggered()), qApp, SLOT(quit())); //contextmenu "Quit" for the systray
connect(folderList, SIGNAL(clicked(const QModelIndex &)), this,
SLOT(setCurrentFolder(const QModelIndex &)));
connect(folderList,SIGNAL(activated(QModelIndex)), this,
SLOT(setCurrentFolder(QModelIndex)));
connect(noteList,SIGNAL(activated(QModelIndex)), this,
SLOT(openNote(QModelIndex)));
connect(folderList, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showContextMenuF(const QPoint &)));
connect(noteList, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showContextMenuN(const QPoint &)));
connect(action_Configure, SIGNAL(triggered()), pref, SLOT(show()));
connect(pref, SIGNAL(sendPathChanged()), this, SLOT(changeRootIndex()));
}
NobleNote::~NobleNote(){}
void NobleNote::setFirstFolderCurrent(QString path)
{
// this slot gets (probably) called by the QFileSystemModel gatherer thread
// due to some race conditions:
// disconnecting this slot will not work button disconnect() will return true
// qDebug() may work or not work depending how many time has elapsed in this function
static bool thisMethodHasBeenCalled = false;
if(thisMethodHasBeenCalled)
return;
QModelIndex idx = folderList->indexAt(QPoint(0,0));
if(!idx.isValid())
return;
folderList->selectionModel()->select(idx,QItemSelectionModel::Select);
setCurrentFolder(idx);
thisMethodHasBeenCalled = true;
}
void NobleNote::setCurrentFolder(const QModelIndex &ind){
noteList->setRootIndex(noteModel->setRootPath(folderModel->filePath(ind)));
}
void NobleNote::changeRootIndex(){
if(pref->lineEdit->text().isEmpty()){
origPath = QDir::homePath() + "/.nobleNote";
folderModel->setRootPath(origPath);
noteModel->setRootPath(origPath);
folderList->setRootIndex(folderModel->index(origPath));
noteList->setRootIndex(noteModel->index(origPath));
}
else{
folderModel->setRootPath(pref->lineEdit->text());
noteModel->setRootPath(pref->lineEdit->text());
folderList->setRootIndex(folderModel->index(pref->lineEdit->text()));
noteList->setRootIndex(noteModel->index(pref->lineEdit->text()));
}
}
void NobleNote::iconActivated(QSystemTrayIcon::ActivationReason reason){
if(reason == QSystemTrayIcon::Trigger)
tray_actions();
}
void NobleNote::tray_actions(){
if(isMinimized() || isHidden()) //in case that the window is minimized or hidden
showNormal();
else
hide();
}
void NobleNote::showEvent(QShowEvent* show_window){
minimize_restore_action->setText(tr("&Minimize"));
QWidget::showEvent(show_window);
}
void NobleNote::hideEvent(QHideEvent* window_hide){
minimize_restore_action->setText(tr("&Restore"));
QWidget::hideEvent(window_hide);
}
void NobleNote::closeEvent(QCloseEvent* window_close){
//if(!pref->getQuitOnClose())
hide();
//else
//qApp->quit();
QWidget::closeEvent(window_close);
}
void NobleNote::keyPressEvent(QKeyEvent *kEvent){
if(kEvent->modifiers() == Qt::ControlModifier)
if(kEvent->key() == Qt::Key_Q)
qApp->quit();
}
void NobleNote::openNote(const QModelIndex &index /* = new QModelIndex*/){
QModelIndex ind = index;
if(!ind.isValid()) // default constructed model index
ind = noteList->currentIndex();
QString notesPath = noteModel->filePath(ind);
QFile noteFile(notesPath);
if(!noteFile.open(QIODevice::ReadOnly))
return;
QTextStream streamN(¬eFile);
text = streamN.readAll();
noteFile.close();
QString journalsPath = QDir::homePath() + "/.nobleNote/Journals/" +
noteModel->fileName(ind) + ".journal";
QFile journalFile(journalsPath);
if(!journalFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
return;
if(!journalFile.exists()){
QTextStream streamJ(&journalFile);
streamJ << text;
}
journalFile.close();
//TODO:
//if(QFileInfo(journalsPath).lastModified().toString() == QFileInfo(notesPath).lastModified().toString());
Note *notes = new Note(this);
notes->text = text;
notes->notesPath = notesPath;
notes->journalsPath = journalsPath;
notes->show();
notes->setAttribute(Qt::WA_DeleteOnClose);
}
void NobleNote::newFolder(){
QString path = folderModel->rootPath() + "/" + tr("new folder");
int counter = 0;
while(QDir(path).exists())
{
++counter;
path = folderModel->rootPath() + "/" + tr("new folder (%1)").arg(QString::number(counter));
}
QDir().mkdir(path);
}
void NobleNote::newNote(){
QString name = noteModel->rootPath() + "/" + tr("new note");
int counter = 0;
while(QFile::exists(name))
{
++counter;
name = noteModel->rootPath() + "/" + tr("new note (%1)").arg(QString::number(counter));
}
QFile file(name);
if(!file.open(QIODevice::WriteOnly))
return;
file.close();
}
void NobleNote::renameFolder(){
folderList->edit(folderList->currentIndex());
}
void NobleNote::renameNote(){
noteList->edit(noteList->currentIndex());
}
void NobleNote::removeFolder(){
//folderModel->rmdir(folderList->currentIndex());
QDir dir(folderModel->filePath(folderList->currentIndex()));
if(!dir.rmdir(folderModel->filePath(folderList->currentIndex()))){
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Warning"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Window);
msgBox.setInformativeText(tr("The directory \"%1\" is not empty!").arg(
folderModel->filePath(folderList->currentIndex())));
QTimer::singleShot(6000, &msgBox, SLOT(close()));
msgBox.exec();
}
#ifdef Q_OS_WIN32
// gives error QFileSystemWatcher: FindNextChangeNotification failed!! (Zugriff verweigert)
// and dir deletion is delayed until another dir has been selected or the application is closed
folderList->setRowHidden(ind.row(),true);
#endif
//TODO: check why:
//QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: Datei oder Verzeichnis nicht gefunden
//QFileSystemWatcher: failed to add paths: /home/hakaishi/.nobleNote/new folder
}
void NobleNote::removeNote(){
noteModel->remove(noteList->currentIndex());
}
void NobleNote::showContextMenuF(const QPoint &pos){
QPoint globalPos = this->mapToGlobal(pos);
QMenu menu;
QAction* addNewF = new QAction(tr("New &folder"), &menu);
connect(addNewF, SIGNAL(triggered()), this, SLOT(newFolder()));
menu.addAction(addNewF);
if(folderList->indexAt(pos).isValid()) // if index exists at position
{
QAction* renameF = new QAction(tr("R&ename folder"), &menu);
QAction* removeFolder = new QAction(tr("&Remove folder"), &menu);
connect(renameF, SIGNAL(triggered()), this, SLOT(renameFolder()));
connect(removeFolder, SIGNAL(triggered()), this, SLOT(removeFolder()));
menu.addAction(renameF);
menu.addAction(removeFolder);
}
menu.exec(globalPos);
}
void NobleNote::showContextMenuN(const QPoint &pos){
QPoint globalPos = this->mapToGlobal(pos);
QMenu menu;
QAction* addNewN = new QAction(tr("New ¬e"), &menu);
connect(addNewN, SIGNAL(triggered()), this, SLOT(newNote()));
menu.addAction(addNewN);
if(noteList->indexAt(pos).isValid()) // if index exists at position
{
QAction* renameN = new QAction(tr("Ren&ame note"), &menu);
QAction* removeNote = new QAction(tr("Re&move note"), &menu);
connect(renameN, SIGNAL(triggered()), this, SLOT(renameNote()));
connect(removeNote, SIGNAL(triggered()), this, SLOT(removeNote()));
menu.addAction(renameN);
menu.addAction(removeNote);
}
menu.exec(globalPos);
}
<commit_msg>no duplicate .journals<commit_after>#include "mainwindow.h"
#include "note.h"
#include "filesystemmodel.h"
#include "preferences.h"
#include <QTextStream>
#include <QFile>
#include <QModelIndex>
#include <QInputDialog>
#include <QMouseEvent>
#include <QDesktopServices>
#include <QtConcurrentRun>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
NobleNote::NobleNote(){
setupUi(this);
//TODO: enable drag and drop.
//TrayIcon
QIcon icon = QIcon(":nobleNote");
TIcon = new QSystemTrayIcon(this);
TIcon->setIcon(icon);
TIcon->show();
//TrayIconContextMenu
iMenu = new QMenu(this);
minimize_restore_action = new QAction(tr("&Minimize"),this);
quit_action = new QAction(tr("&Quit"),this);
iMenu->addAction(minimize_restore_action);
iMenu->addAction(quit_action);
TIcon->setContextMenu(iMenu); //setting contextmenu for the systray
QDir nbDir(QDir::homePath() + "/.nobleNote/Journals");
if(!nbDir.exists())
nbDir.mkdir(QDir::homePath() + "/.nobleNote/Journals");
QString file(QDir::homePath() + "/.nobleNote/nobleNote.conf");
QSettings settings(file, QSettings::IniFormat);
if(!settings.isWritable()){
QTextStream myOutput;
myOutput << "W: nobelNote.conf is not writable!" << endl;
}
pref = new Preferences(this);
pref->lineEdit->setText(settings.value("Path to note folders").toString());
if(pref->lineEdit->text().isEmpty())
origPath = QDir::homePath() + "/.nobleNote";
else
origPath = pref->lineEdit->text();
splitter = new QSplitter(centralwidget);
gridLayout->addWidget(splitter, 0, 0);
folderModel = new FileSystemModel(this);
folderModel->setRootPath(origPath);
folderModel->setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
folderModel->setReadOnly(false); // enable drag drop
//folderModel->setNameFilters(QStringList("Journals")); TODO:DON'T show journals.
noteModel = new FileSystemModel(this);
noteModel->setRootPath(origPath); //just as an example
noteModel->setFilter(QDir::Files);
noteModel->setReadOnly(false);
folderList = new QListView(splitter);
noteList = new QListView(splitter);
QList<QListView*> listViews;
listViews << folderList << noteList;
foreach(QListView* list, listViews)
{
list->setContextMenuPolicy(Qt::CustomContextMenu);
//list->setSelectionMode(QAbstractItemView::SingleSelection); // single item can be draged or droped
list->setDragDropMode(QAbstractItemView::DragDrop);
list->viewport()->setAcceptDrops(true);
list->setDropIndicatorShown(true);
list->setDefaultDropAction(Qt::MoveAction);
}
noteList->setDragEnabled(true);
folderList->setDragEnabled(false);
folderList->setModel(folderModel);
folderList->setRootIndex(folderModel->index(origPath));
noteList->setEditTriggers(QListView::EditKeyPressed);
noteList->setModel(noteModel);
noteList->setRootIndex(noteModel->index(origPath));
//QTimer::singleShot(2000,this,SLOT(setFirstFolderCurrent()));
//TODO: make it possible to import notes from some other folder or even another program
// single shot connect
connect(folderModel,SIGNAL(directoryLoaded(QString)), this,
SLOT(setFirstFolderCurrent(QString)),Qt::QueuedConnection);
connect(actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(TIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); //handles systray-symbol
connect(minimize_restore_action, SIGNAL(triggered()), this, SLOT(tray_actions()));
connect(quit_action, SIGNAL(triggered()), qApp, SLOT(quit())); //contextmenu "Quit" for the systray
connect(folderList, SIGNAL(clicked(const QModelIndex &)), this,
SLOT(setCurrentFolder(const QModelIndex &)));
connect(folderList,SIGNAL(activated(QModelIndex)), this,
SLOT(setCurrentFolder(QModelIndex)));
connect(noteList,SIGNAL(activated(QModelIndex)), this,
SLOT(openNote(QModelIndex)));
connect(folderList, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showContextMenuF(const QPoint &)));
connect(noteList, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(showContextMenuN(const QPoint &)));
connect(action_Configure, SIGNAL(triggered()), pref, SLOT(show()));
connect(pref, SIGNAL(sendPathChanged()), this, SLOT(changeRootIndex()));
}
NobleNote::~NobleNote(){}
void NobleNote::setFirstFolderCurrent(QString path)
{
// this slot gets (probably) called by the QFileSystemModel gatherer thread
// due to some race conditions:
// disconnecting this slot will not work button disconnect() will return true
// qDebug() may work or not work depending how many time has elapsed in this function
static bool thisMethodHasBeenCalled = false;
if(thisMethodHasBeenCalled)
return;
QModelIndex idx = folderList->indexAt(QPoint(0,0));
if(!idx.isValid())
return;
folderList->selectionModel()->select(idx,QItemSelectionModel::Select);
setCurrentFolder(idx);
thisMethodHasBeenCalled = true;
}
void NobleNote::setCurrentFolder(const QModelIndex &ind){
noteList->setRootIndex(noteModel->setRootPath(folderModel->filePath(ind)));
}
void NobleNote::changeRootIndex(){
if(pref->lineEdit->text().isEmpty()){
origPath = QDir::homePath() + "/.nobleNote";
folderModel->setRootPath(origPath);
noteModel->setRootPath(origPath);
folderList->setRootIndex(folderModel->index(origPath));
noteList->setRootIndex(noteModel->index(origPath));
}
else{
folderModel->setRootPath(pref->lineEdit->text());
noteModel->setRootPath(pref->lineEdit->text());
folderList->setRootIndex(folderModel->index(pref->lineEdit->text()));
noteList->setRootIndex(noteModel->index(pref->lineEdit->text()));
}
}
void NobleNote::iconActivated(QSystemTrayIcon::ActivationReason reason){
if(reason == QSystemTrayIcon::Trigger)
tray_actions();
}
void NobleNote::tray_actions(){
if(isMinimized() || isHidden()) //in case that the window is minimized or hidden
showNormal();
else
hide();
}
void NobleNote::showEvent(QShowEvent* show_window){
minimize_restore_action->setText(tr("&Minimize"));
QWidget::showEvent(show_window);
}
void NobleNote::hideEvent(QHideEvent* window_hide){
minimize_restore_action->setText(tr("&Restore"));
QWidget::hideEvent(window_hide);
}
void NobleNote::closeEvent(QCloseEvent* window_close){
//if(!pref->getQuitOnClose())
hide();
//else
//qApp->quit();
QWidget::closeEvent(window_close);
}
void NobleNote::keyPressEvent(QKeyEvent *kEvent){
if(kEvent->modifiers() == Qt::ControlModifier)
if(kEvent->key() == Qt::Key_Q)
qApp->quit();
}
void NobleNote::openNote(const QModelIndex &index /* = new QModelIndex*/){
QModelIndex ind = index;
if(!ind.isValid()) // default constructed model index
ind = noteList->currentIndex();
QString notesPath = noteModel->filePath(ind);
QFile noteFile(notesPath);
if(!noteFile.open(QIODevice::ReadOnly))
return;
QTextStream streamN(¬eFile);
text = streamN.readAll();
noteFile.close();
QString journalsPath = QDir::homePath() + "/.nobleNote/Journals/" +
folderModel->fileName(folderList->currentIndex()) + "_" + noteModel->fileName(ind) + ".journal";
QFile journalFile(journalsPath);
if(!journalFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
return;
if(!journalFile.exists()){
QTextStream streamJ(&journalFile);
streamJ << text;
}
journalFile.close();
//TODO:
//if(QFileInfo(journalsPath).lastModified().toString() == QFileInfo(notesPath).lastModified().toString());
Note *notes = new Note(this);
notes->text = text;
notes->notesPath = notesPath;
notes->journalsPath = journalsPath;
notes->show();
notes->setAttribute(Qt::WA_DeleteOnClose);
}
void NobleNote::newFolder(){
QString path = folderModel->rootPath() + "/" + tr("new folder");
int counter = 0;
while(QDir(path).exists())
{
++counter;
path = folderModel->rootPath() + "/" + tr("new folder (%1)").arg(QString::number(counter));
}
QDir().mkdir(path);
}
void NobleNote::newNote(){
QString name = noteModel->rootPath() + "/" + tr("new note");
int counter = 0;
while(QFile::exists(name))
{
++counter;
name = noteModel->rootPath() + "/" + tr("new note (%1)").arg(QString::number(counter));
}
QFile file(name);
if(!file.open(QIODevice::WriteOnly))
return;
file.close();
}
void NobleNote::renameFolder(){
folderList->edit(folderList->currentIndex());
}
void NobleNote::renameNote(){
noteList->edit(noteList->currentIndex());
}
void NobleNote::removeFolder(){
//folderModel->rmdir(folderList->currentIndex());
QDir dir(folderModel->filePath(folderList->currentIndex()));
if(!dir.rmdir(folderModel->filePath(folderList->currentIndex()))){
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Warning"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Window);
msgBox.setInformativeText(tr("The directory \"%1\" is not empty!").arg(
folderModel->filePath(folderList->currentIndex())));
QTimer::singleShot(6000, &msgBox, SLOT(close()));
msgBox.exec();
}
#ifdef Q_OS_WIN32
// gives error QFileSystemWatcher: FindNextChangeNotification failed!! (Zugriff verweigert)
// and dir deletion is delayed until another dir has been selected or the application is closed
folderList->setRowHidden(ind.row(),true);
#endif
//TODO: check why:
//QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: Datei oder Verzeichnis nicht gefunden
//QFileSystemWatcher: failed to add paths: /home/hakaishi/.nobleNote/new folder
}
void NobleNote::removeNote(){
noteModel->remove(noteList->currentIndex());
}
void NobleNote::showContextMenuF(const QPoint &pos){
QPoint globalPos = this->mapToGlobal(pos);
QMenu menu;
QAction* addNewF = new QAction(tr("New &folder"), &menu);
connect(addNewF, SIGNAL(triggered()), this, SLOT(newFolder()));
menu.addAction(addNewF);
if(folderList->indexAt(pos).isValid()) // if index exists at position
{
QAction* renameF = new QAction(tr("R&ename folder"), &menu);
QAction* removeFolder = new QAction(tr("&Remove folder"), &menu);
connect(renameF, SIGNAL(triggered()), this, SLOT(renameFolder()));
connect(removeFolder, SIGNAL(triggered()), this, SLOT(removeFolder()));
menu.addAction(renameF);
menu.addAction(removeFolder);
}
menu.exec(globalPos);
}
void NobleNote::showContextMenuN(const QPoint &pos){
QPoint globalPos = this->mapToGlobal(pos);
QMenu menu;
QAction* addNewN = new QAction(tr("New ¬e"), &menu);
connect(addNewN, SIGNAL(triggered()), this, SLOT(newNote()));
menu.addAction(addNewN);
if(noteList->indexAt(pos).isValid()) // if index exists at position
{
QAction* renameN = new QAction(tr("Ren&ame note"), &menu);
QAction* removeNote = new QAction(tr("Re&move note"), &menu);
connect(renameN, SIGNAL(triggered()), this, SLOT(renameNote()));
connect(removeNote, SIGNAL(triggered()), this, SLOT(removeNote()));
menu.addAction(renameN);
menu.addAction(removeNote);
}
menu.exec(globalPos);
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cassert>
#include <visionaray/math/math.h>
#include <gtest/gtest.h>
using namespace visionaray;
//-------------------------------------------------------------------------------------------------
// Helper functions
//
// nested for loop over matrices --------------------------
template <typename Func>
void for_each_mat2_e(Func f)
{
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
f(i, j);
}
}
}
template <typename Func>
void for_each_mat3_e(Func f)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
f(i, j);
}
}
}
template <typename Func>
void for_each_mat4_e(Func f)
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
f(i, j);
}
}
}
// get rows and columns -----------------------------------
template <size_t Dim>
vector<Dim, float> get_row(matrix<Dim, Dim, float> const& m, int i)
{
assert( i >= 0 && i < 4 );
vector<Dim, float> result;
for (size_t d = 0; d < Dim; ++d)
{
result[d] = m(i, d);
}
return result;
}
template <size_t Dim>
vector<Dim, float> get_col(matrix<Dim, Dim, float> const& m, int j)
{
assert( j >= 0 && j < 4 );
return m(j);
}
TEST(Matrix, Inverse)
{
//-------------------------------------------------------------------------
// mat2
//
{
mat2 I = mat2::identity();
// make some non-singular matrix
mat2 A(1, 2, 3, 4);
mat2 B = inverse(A);
mat2 C = A * B;
for_each_mat2_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
mat3 I = mat3::identity();
// make some non-singular matrix
mat3 A = mat3::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat3 B = inverse(A);
mat3 C = A * B;
for_each_mat3_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
mat4 I = mat4::identity();
// make some non-singular matrix
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = inverse(A);
mat4 C = A * B;
for_each_mat4_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
}
TEST(Matrix, Mult)
{
//-------------------------------------------------------------------------
// mat2
//
{
// make some matrices
mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat2 B = mat2::identity(); B(0, 0) = 11.0f; B(1, 0) = 6.28f; B(1, 1) = 3.0f;
mat2 C = A * B;
for_each_mat2_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
// make some matrices
mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat3 B = mat3::identity(); B(0, 1) = 11.0f; B(2, 1) = 6.28f; B(2, 2) = 3.0f;
mat3 C = A * B;
for_each_mat3_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
// make some matrices
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = mat4::translation(vec3(3, 4, 5));
mat4 C = A * B;
for_each_mat4_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
}
TEST(Matrix, Transpose)
{
//-------------------------------------------------------------------------
// mat2
//
{
// make some non-singular matrix
mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat2 B = transpose(A);
for_each_mat2_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
// make some non-singular matrix
mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat3 B = transpose(A);
for_each_mat3_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
// make some non-singular matrix
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = transpose(A);
for_each_mat4_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
}
<commit_msg>Unit test<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cassert>
#include <visionaray/math/math.h>
#include <gtest/gtest.h>
using namespace visionaray;
//-------------------------------------------------------------------------------------------------
// Helper functions
//
// nested for loop over matrices --------------------------
template <typename Func>
void for_each_mat2_e(Func f)
{
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
f(i, j);
}
}
}
template <typename Func>
void for_each_mat3_e(Func f)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
f(i, j);
}
}
}
template <typename Func>
void for_each_mat4_e(Func f)
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
f(i, j);
}
}
}
// get rows and columns -----------------------------------
template <size_t Dim>
vector<Dim, float> get_row(matrix<Dim, Dim, float> const& m, int i)
{
assert( i >= 0 && i < 4 );
vector<Dim, float> result;
for (size_t d = 0; d < Dim; ++d)
{
result[d] = m(i, d);
}
return result;
}
template <size_t Dim>
vector<Dim, float> get_col(matrix<Dim, Dim, float> const& m, int j)
{
assert( j >= 0 && j < 4 );
return m(j);
}
TEST(Matrix, Inverse)
{
//-------------------------------------------------------------------------
// mat2
//
{
mat2 I = mat2::identity();
// make some non-singular matrix
mat2 A(1, 2, 3, 4);
mat2 B = inverse(A);
mat2 C = A * B;
for_each_mat2_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
mat3 I = mat3::identity();
// make some non-singular matrix
mat3 A = mat3::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat3 B = inverse(A);
mat3 C = A * B;
for_each_mat3_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
mat4 I = mat4::identity();
// make some non-singular matrix
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = inverse(A);
mat4 C = A * B;
for_each_mat4_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), I(i, j));
}
);
}
}
TEST(Matrix, Mult)
{
//-------------------------------------------------------------------------
// mat2
//
{
// make some matrices
mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat2 B = mat2::identity(); B(0, 0) = 11.0f; B(1, 0) = 6.28f; B(1, 1) = 3.0f;
mat2 C = A * B;
for_each_mat2_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
// make some matrices
mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat3 B = mat3::identity(); B(0, 1) = 11.0f; B(2, 1) = 6.28f; B(2, 2) = 3.0f;
mat3 C = A * B;
for_each_mat3_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
// make some matrices
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = mat4::translation(vec3(3, 4, 5));
mat4 C = A * B;
for_each_mat4_e(
[&](int i, int j)
{
float d = dot(get_row(A, i), get_col(B, j));
EXPECT_FLOAT_EQ(C(i, j), d);
}
);
}
}
TEST(Matrix, Add)
{
//-------------------------------------------------------------------------
// mat4
//
{
// make some matrices
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = mat4::translation(vec3(3, 4, 5));
mat4 C = A + B;
for_each_mat4_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(C(i, j), A(i, j) + B(i, j));
}
);
}
}
TEST(Matrix, Transpose)
{
//-------------------------------------------------------------------------
// mat2
//
{
// make some non-singular matrix
mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat2 B = transpose(A);
for_each_mat2_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
//-------------------------------------------------------------------------
// mat3
//
{
// make some non-singular matrix
mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;
mat3 B = transpose(A);
for_each_mat3_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
//-------------------------------------------------------------------------
// mat4
//
{
// make some non-singular matrix
mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
mat4 B = transpose(A);
for_each_mat4_e(
[&](int i, int j)
{
EXPECT_FLOAT_EQ(A(i, j), B(j, i));
}
);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "problem.hpp"
#include "lsearch_types.h"
#include "batch_types.h"
#include "batch/gd.hpp"
#include "batch/cgd.hpp"
#include "batch/lbfgs.hpp"
namespace nano
{
///
/// \brief batch optimization (can detail the line-search parameters)
///
template
<
typename tproblem, ///< optimization problem
typename topulog, ///< logging operator (update)
typename tvector = typename tproblem::tvector,
typename tscalar = typename tproblem::tscalar
>
auto minimize(
const tproblem& problem,
const topulog& fn_ulog,
const tvector& x0,
const batch_optimizer optimizer, const std::size_t iterations, const tscalar epsilon,
const ls_initializer lsinit,
const ls_strategy lsstrat,
const std::size_t history_size = 6)
{
const batch_params_t<tproblem> param(iterations, epsilon, lsinit, lsstrat, history_size, fn_ulog);
switch (optimizer)
{
case batch_optimizer::LBFGS:
return batch_lbfgs_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD:
return batch_cgd_prp_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_CD:
return batch_cgd_cd_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DY:
return batch_cgd_dy_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_FR:
return batch_cgd_fr_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_HS:
return batch_cgd_hs_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_LS:
return batch_cgd_ls_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_N:
return batch_cgd_n_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_PRP:
return batch_cgd_prp_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DYCD:
return batch_cgd_dycd_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DYHS:
return batch_cgd_dyhs_t<tproblem>()(param, problem, x0);
case batch_optimizer::GD:
default:
return batch_gd_t<tproblem>()(param, problem, x0);
}
}
///
/// \brief batch optimization
///
template
<
typename tproblem, ///< optimization problem
typename topulog, ///< logging operator (update)
typename tvector = typename tproblem::tvector,
typename tscalar = typename tproblem::tscalar
>
auto minimize(
const tproblem& problem,
const topulog& fn_ulog,
const tvector& x0,
const batch_optimizer optimizer, const std::size_t iterations, const tscalar epsilon,
const std::size_t history_size = 6)
{
switch (optimizer)
{
case batch_optimizer::LBFGS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::unit, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD: // fall through!
case batch_optimizer::CGD_PRP:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_CD:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::unit, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_DY:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
case batch_optimizer::CGD_FR:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_armijo,
history_size);
case batch_optimizer::CGD_HS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
case batch_optimizer::CGD_LS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_N:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_DYCD:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::unit, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_DYHS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::GD:
default:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
}
}
}
<commit_msg>update default line-search options according to the latest benchmarking results<commit_after>#pragma once
#include "problem.hpp"
#include "lsearch_types.h"
#include "batch_types.h"
#include "batch/gd.hpp"
#include "batch/cgd.hpp"
#include "batch/lbfgs.hpp"
namespace nano
{
///
/// \brief batch optimization (can detail the line-search parameters)
///
template
<
typename tproblem, ///< optimization problem
typename topulog, ///< logging operator (update)
typename tvector = typename tproblem::tvector,
typename tscalar = typename tproblem::tscalar
>
auto minimize(
const tproblem& problem,
const topulog& fn_ulog,
const tvector& x0,
const batch_optimizer optimizer, const std::size_t iterations, const tscalar epsilon,
const ls_initializer lsinit,
const ls_strategy lsstrat,
const std::size_t history_size = 6)
{
const batch_params_t<tproblem> param(iterations, epsilon, lsinit, lsstrat, history_size, fn_ulog);
switch (optimizer)
{
case batch_optimizer::LBFGS:
return batch_lbfgs_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD:
return batch_cgd_prp_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_CD:
return batch_cgd_cd_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DY:
return batch_cgd_dy_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_FR:
return batch_cgd_fr_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_HS:
return batch_cgd_hs_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_LS:
return batch_cgd_ls_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_N:
return batch_cgd_n_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_PRP:
return batch_cgd_prp_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DYCD:
return batch_cgd_dycd_t<tproblem>()(param, problem, x0);
case batch_optimizer::CGD_DYHS:
return batch_cgd_dyhs_t<tproblem>()(param, problem, x0);
case batch_optimizer::GD:
default:
return batch_gd_t<tproblem>()(param, problem, x0);
}
}
///
/// \brief batch optimization
///
template
<
typename tproblem, ///< optimization problem
typename topulog, ///< logging operator (update)
typename tvector = typename tproblem::tvector,
typename tscalar = typename tproblem::tscalar
>
auto minimize(
const tproblem& problem,
const topulog& fn_ulog,
const tvector& x0,
const batch_optimizer optimizer, const std::size_t iterations, const tscalar epsilon,
const std::size_t history_size = 6)
{
switch (optimizer)
{
case batch_optimizer::LBFGS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD: // fall through!
case batch_optimizer::CGD_PRP:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_CD:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_DY:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
case batch_optimizer::CGD_FR:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_HS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_LS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_N:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::interpolation,
history_size);
case batch_optimizer::CGD_DYCD:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
case batch_optimizer::CGD_DYHS:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
case batch_optimizer::GD:
default:
return minimize(problem, fn_ulog, x0, optimizer, iterations, epsilon,
ls_initializer::quadratic, ls_strategy::backtrack_wolfe,
history_size);
}
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// mutate_test.cpp
//
// Identification: tests/executor/mutate_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include "harness.h"
#include "backend/catalog/schema.h"
#include "backend/common/value_factory.h"
#include "backend/common/pool.h"
#include "backend/executor/executor_context.h"
#include "backend/executor/delete_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/executor/seq_scan_executor.h"
#include "backend/executor/update_executor.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/table_factory.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "executor_tests_util.h"
#include "executor/mock_executor.h"
#include "backend/planner/delete_plan.h"
#include "backend/planner/insert_plan.h"
#include "backend/planner/seq_scan_plan.h"
#include "backend/planner/update_plan.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
//===------------------------------===//
// Utility
//===------------------------------===//
/**
* Cook a ProjectInfo object from a tuple.
* Simply use a ConstantValueExpression for each attribute.
*/
planner::ProjectInfo *MakeProjectInfoFromTuple(const storage::Tuple *tuple) {
planner::ProjectInfo::TargetList target_list;
planner::ProjectInfo::DirectMapList direct_map_list;
for (oid_t col_id = START_OID; col_id < tuple->GetColumnCount(); col_id++) {
auto value = tuple->GetValue(col_id);
auto expression = expression::ExpressionUtil::ConstantValueFactory(value);
target_list.emplace_back(col_id, expression);
}
return new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list));
}
//===--------------------------------------------------------------------===//
// Mutator Tests
//===--------------------------------------------------------------------===//
class MutateTests : public PelotonTest {};
std::atomic<int> tuple_id;
std::atomic<int> delete_tuple_id;
void InsertTuple(storage::DataTable *table, VarlenPool *pool) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
for (oid_t tuple_itr = 0; tuple_itr < 10; tuple_itr++) {
auto tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, pool);
auto project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node(table, project_info);
executor::InsertExecutor executor(&node, context.get());
executor.Execute();
delete tuple;
}
txn_manager.CommitTransaction();
}
void UpdateTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Update
std::vector<oid_t> update_column_ids = {2};
std::vector<Value> values;
Value update_val = ValueFactory::GetDoubleValue(23.5);
planner::ProjectInfo::TargetList target_list;
planner::ProjectInfo::DirectMapList direct_map_list;
target_list.emplace_back(
2, expression::ExpressionUtil::ConstantValueFactory(update_val));
std::cout << target_list.at(0).first << std::endl;
direct_map_list.emplace_back(0, std::pair<oid_t, oid_t>(0, 0));
direct_map_list.emplace_back(1, std::pair<oid_t, oid_t>(0, 1));
direct_map_list.emplace_back(3, std::pair<oid_t, oid_t>(0, 3));
planner::UpdatePlan update_node(
table, new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list)));
executor::UpdateExecutor update_executor(&update_node, context.get());
// Predicate
// WHERE ATTR_0 < 70
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(70));
auto predicate = new expression::ComparisonExpression<expression::CmpLt>(
EXPRESSION_TYPE_COMPARE_LESSTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
// Parent-Child relationship
update_node.AddChild(&seq_scan_node);
update_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(update_executor.Init());
while (update_executor.Execute())
;
txn_manager.CommitTransaction();
}
void DeleteTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
std::vector<storage::Tuple *> tuples;
// Delete
planner::DeletePlan delete_node(table, false);
executor::DeleteExecutor delete_executor(&delete_node, context.get());
// Predicate
// WHERE ATTR_0 > 60
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(60));
auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
EXPRESSION_TYPE_COMPARE_GREATERTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
// Parent-Child relationship
delete_node.AddChild(&seq_scan_node);
delete_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(delete_executor.Init());
EXPECT_TRUE(delete_executor.Execute());
// EXPECT_TRUE(delete_executor.Execute());
txn_manager.CommitTransaction();
}
TEST_F(MutateTests, StressTests) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
// Create insert node for this test.
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
// Pass through insert executor.
storage::Tuple *tuple;
tuple = ExecutorTestsUtil::GetNullTuple(table, testing_pool);
auto project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node(table, project_info);
executor::InsertExecutor executor(&node, context.get());
try {
executor.Execute();
}
catch (ConstraintException &ce) {
std::cout << ce.what();
}
delete tuple;
tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, testing_pool);
project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node2(table, project_info);
executor::InsertExecutor executor2(&node2, context.get());
executor2.Execute();
try {
executor2.Execute();
}
catch (ConstraintException &ce) {
std::cout << ce.what();
}
delete tuple;
txn_manager.CommitTransaction();
std::cout << "Start tests \n";
LaunchParallelTest(1, InsertTuple, table, testing_pool);
// std::cout << (*table);
LOG_INFO("---------------------------------------------");
// LaunchParallelTest(1, UpdateTuple, table);
// std::cout << (*table);
LOG_INFO("---------------------------------------------");
LaunchParallelTest(1, DeleteTuple, table);
// std::cout << (*table);
// PRIMARY KEY
std::vector<catalog::Column> columns;
columns.push_back(ExecutorTestsUtil::GetColumnInfo(0));
catalog::Schema *key_schema = new catalog::Schema(columns);
storage::Tuple *key1 = new storage::Tuple(key_schema, true);
storage::Tuple *key2 = new storage::Tuple(key_schema, true);
key1->SetValue(0, ValueFactory::GetIntegerValue(10), nullptr);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), nullptr);
delete key1;
delete key2;
delete key_schema;
// SEC KEY
columns.clear();
columns.push_back(ExecutorTestsUtil::GetColumnInfo(0));
columns.push_back(ExecutorTestsUtil::GetColumnInfo(1));
key_schema = new catalog::Schema(columns);
storage::Tuple *key3 = new storage::Tuple(key_schema, true);
storage::Tuple *key4 = new storage::Tuple(key_schema, true);
key3->SetValue(0, ValueFactory::GetIntegerValue(10), nullptr);
key3->SetValue(1, ValueFactory::GetIntegerValue(11), nullptr);
key4->SetValue(0, ValueFactory::GetIntegerValue(100), nullptr);
key4->SetValue(1, ValueFactory::GetIntegerValue(101), nullptr);
delete key3;
delete key4;
delete key_schema;
delete table;
tuple_id = 0;
}
// Insert a logical tile into a table
TEST_F(MutateTests, InsertTest) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
// We are going to insert a tile group into a table in this test
std::unique_ptr<storage::DataTable> source_data_table(
ExecutorTestsUtil::CreateAndPopulateTable());
std::unique_ptr<storage::DataTable> dest_data_table(
ExecutorTestsUtil::CreateTable());
const std::vector<storage::Tuple *> tuples;
EXPECT_EQ(source_data_table->GetTileGroupCount(), 3);
EXPECT_EQ(dest_data_table->GetTileGroupCount(), 1);
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
planner::InsertPlan node(dest_data_table.get(), nullptr);
executor::InsertExecutor executor(&node, context.get());
MockExecutor child_executor;
executor.AddChild(&child_executor);
// Uneventful init...
EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true));
// Will return one tile.
EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce(
Return(false));
// Construct input logical tile
auto physical_tile_group = source_data_table->GetTileGroup(0);
auto tile_count = physical_tile_group->GetTileCount();
std::vector<std::shared_ptr<storage::Tile> > physical_tile_refs;
for (oid_t tile_itr = 0; tile_itr < tile_count; tile_itr++)
physical_tile_refs.push_back(
physical_tile_group->GetTileReference(tile_itr));
std::unique_ptr<executor::LogicalTile> source_logical_tile(
executor::LogicalTileFactory::WrapTiles(physical_tile_refs));
EXPECT_CALL(child_executor, GetOutput())
.WillOnce(Return(source_logical_tile.release()));
EXPECT_TRUE(executor.Init());
EXPECT_TRUE(executor.Execute());
EXPECT_FALSE(executor.Execute());
txn_manager.CommitTransaction();
// We have inserted all the tuples in this logical tile
EXPECT_EQ(dest_data_table->GetTileGroupCount(), 1);
}
TEST_F(MutateTests, DeleteTest) {
// We are going to insert a tile group into a table in this test
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
LaunchParallelTest(1, DeleteTuple, table);
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, nullptr, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
EXPECT_EQ(tuple_cnt, 6);
delete table;
tuple_id = 0;
}
int SeqScanCount(storage::DataTable *table,
const std::vector<oid_t> &column_ids,
expression::AbstractExpression *predicate) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
return tuple_cnt;
}
TEST_F(MutateTests, UpdateTest) {
// We are going to insert a tile group into a table in this test
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
LaunchParallelTest(1, UpdateTuple, table);
// Seq scan to check number
std::vector<oid_t> column_ids = {0};
auto tuple_cnt = SeqScanCount(table, column_ids, nullptr);
EXPECT_EQ(tuple_cnt, 10);
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(2, 2);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetDoubleValue(23.5));
auto predicate = new expression::ComparisonExpression<expression::CmpEq>(
EXPRESSION_TYPE_COMPARE_EQUAL, tup_val_exp, const_val_exp);
tuple_cnt = SeqScanCount(table, column_ids, predicate);
EXPECT_EQ(tuple_cnt, 6);
delete table;
tuple_id = 0;
}
} // namespace test
} // namespace peloton
<commit_msg>fix bug in mutate_test<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// mutate_test.cpp
//
// Identification: tests/executor/mutate_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include "harness.h"
#include "backend/catalog/schema.h"
#include "backend/common/value_factory.h"
#include "backend/common/pool.h"
#include "backend/executor/executor_context.h"
#include "backend/executor/delete_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/executor/seq_scan_executor.h"
#include "backend/executor/update_executor.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/table_factory.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "executor_tests_util.h"
#include "executor/mock_executor.h"
#include "backend/planner/delete_plan.h"
#include "backend/planner/insert_plan.h"
#include "backend/planner/seq_scan_plan.h"
#include "backend/planner/update_plan.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
//===------------------------------===//
// Utility
//===------------------------------===//
/**
* Cook a ProjectInfo object from a tuple.
* Simply use a ConstantValueExpression for each attribute.
*/
planner::ProjectInfo *MakeProjectInfoFromTuple(const storage::Tuple *tuple) {
planner::ProjectInfo::TargetList target_list;
planner::ProjectInfo::DirectMapList direct_map_list;
for (oid_t col_id = START_OID; col_id < tuple->GetColumnCount(); col_id++) {
auto value = tuple->GetValue(col_id);
auto expression = expression::ExpressionUtil::ConstantValueFactory(value);
target_list.emplace_back(col_id, expression);
}
return new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list));
}
//===--------------------------------------------------------------------===//
// Mutator Tests
//===--------------------------------------------------------------------===//
class MutateTests : public PelotonTest {};
std::atomic<int> tuple_id;
std::atomic<int> delete_tuple_id;
void InsertTuple(storage::DataTable *table, VarlenPool *pool) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
for (oid_t tuple_itr = 0; tuple_itr < 10; tuple_itr++) {
auto tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, pool);
auto project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node(table, project_info);
executor::InsertExecutor executor(&node, context.get());
executor.Execute();
delete tuple;
}
txn_manager.CommitTransaction();
}
void UpdateTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Update
std::vector<oid_t> update_column_ids = {2};
std::vector<Value> values;
Value update_val = ValueFactory::GetDoubleValue(23.5);
planner::ProjectInfo::TargetList target_list;
planner::ProjectInfo::DirectMapList direct_map_list;
target_list.emplace_back(
2, expression::ExpressionUtil::ConstantValueFactory(update_val));
std::cout << target_list.at(0).first << std::endl;
direct_map_list.emplace_back(0, std::pair<oid_t, oid_t>(0, 0));
direct_map_list.emplace_back(1, std::pair<oid_t, oid_t>(0, 1));
direct_map_list.emplace_back(3, std::pair<oid_t, oid_t>(0, 3));
planner::UpdatePlan update_node(
table, new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list)));
executor::UpdateExecutor update_executor(&update_node, context.get());
// Predicate
// WHERE ATTR_0 < 70
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(70));
auto predicate = new expression::ComparisonExpression<expression::CmpLt>(
EXPRESSION_TYPE_COMPARE_LESSTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
// Parent-Child relationship
update_node.AddChild(&seq_scan_node);
update_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(update_executor.Init());
while (update_executor.Execute())
;
txn_manager.CommitTransaction();
}
void DeleteTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
std::vector<storage::Tuple *> tuples;
// Delete
planner::DeletePlan delete_node(table, false);
executor::DeleteExecutor delete_executor(&delete_node, context.get());
// Predicate
// WHERE ATTR_0 > 60
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(60));
auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
EXPRESSION_TYPE_COMPARE_GREATERTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
// Parent-Child relationship
delete_node.AddChild(&seq_scan_node);
delete_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(delete_executor.Init());
EXPECT_TRUE(delete_executor.Execute());
// EXPECT_TRUE(delete_executor.Execute());
txn_manager.CommitTransaction();
}
TEST_F(MutateTests, StressTests) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
// Create insert node for this test.
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
// Pass through insert executor.
storage::Tuple *tuple;
tuple = ExecutorTestsUtil::GetNullTuple(table, testing_pool);
auto project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node(table, project_info);
executor::InsertExecutor executor(&node, context.get());
try {
executor.Execute();
}
catch (ConstraintException &ce) {
std::cout << ce.what();
}
delete tuple;
tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, testing_pool);
project_info = MakeProjectInfoFromTuple(tuple);
planner::InsertPlan node2(table, project_info);
executor::InsertExecutor executor2(&node2, context.get());
executor2.Execute();
try {
executor2.Execute();
}
catch (ConstraintException &ce) {
std::cout << ce.what();
}
delete tuple;
txn_manager.CommitTransaction();
std::cout << "Start tests \n";
LaunchParallelTest(1, InsertTuple, table, testing_pool);
// std::cout << (*table);
LOG_INFO("---------------------------------------------");
// LaunchParallelTest(1, UpdateTuple, table);
// std::cout << (*table);
LOG_INFO("---------------------------------------------");
LaunchParallelTest(1, DeleteTuple, table);
// std::cout << (*table);
// PRIMARY KEY
std::vector<catalog::Column> columns;
columns.push_back(ExecutorTestsUtil::GetColumnInfo(0));
catalog::Schema *key_schema = new catalog::Schema(columns);
storage::Tuple *key1 = new storage::Tuple(key_schema, true);
storage::Tuple *key2 = new storage::Tuple(key_schema, true);
key1->SetValue(0, ValueFactory::GetIntegerValue(10), nullptr);
key2->SetValue(0, ValueFactory::GetIntegerValue(100), nullptr);
delete key1;
delete key2;
delete key_schema;
// SEC KEY
columns.clear();
columns.push_back(ExecutorTestsUtil::GetColumnInfo(0));
columns.push_back(ExecutorTestsUtil::GetColumnInfo(1));
key_schema = new catalog::Schema(columns);
storage::Tuple *key3 = new storage::Tuple(key_schema, true);
storage::Tuple *key4 = new storage::Tuple(key_schema, true);
key3->SetValue(0, ValueFactory::GetIntegerValue(10), nullptr);
key3->SetValue(1, ValueFactory::GetIntegerValue(11), nullptr);
key4->SetValue(0, ValueFactory::GetIntegerValue(100), nullptr);
key4->SetValue(1, ValueFactory::GetIntegerValue(101), nullptr);
delete key3;
delete key4;
delete key_schema;
delete table;
tuple_id = 0;
}
// Insert a logical tile into a table
TEST_F(MutateTests, InsertTest) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
// We are going to insert a tile group into a table in this test
std::unique_ptr<storage::DataTable> source_data_table(
ExecutorTestsUtil::CreateAndPopulateTable());
std::unique_ptr<storage::DataTable> dest_data_table(
ExecutorTestsUtil::CreateTable());
const std::vector<storage::Tuple *> tuples;
EXPECT_EQ(source_data_table->GetTileGroupCount(), 3);
EXPECT_EQ(dest_data_table->GetTileGroupCount(), 1);
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
planner::InsertPlan node(dest_data_table.get(), nullptr);
executor::InsertExecutor executor(&node, context.get());
MockExecutor child_executor;
executor.AddChild(&child_executor);
// Uneventful init...
EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true));
// Will return one tile.
EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce(
Return(false));
// Construct input logical tile
auto physical_tile_group = source_data_table->GetTileGroup(0);
auto tile_count = physical_tile_group->GetTileCount();
std::vector<std::shared_ptr<storage::Tile> > physical_tile_refs;
for (oid_t tile_itr = 0; tile_itr < tile_count; tile_itr++)
physical_tile_refs.push_back(
physical_tile_group->GetTileReference(tile_itr));
std::unique_ptr<executor::LogicalTile> source_logical_tile(
executor::LogicalTileFactory::WrapTiles(physical_tile_refs));
EXPECT_CALL(child_executor, GetOutput())
.WillOnce(Return(source_logical_tile.release()));
EXPECT_TRUE(executor.Init());
EXPECT_TRUE(executor.Execute());
EXPECT_FALSE(executor.Execute());
txn_manager.CommitTransaction();
// We have inserted all the tuples in this logical tile
EXPECT_EQ(dest_data_table->GetTileGroupCount(), 1);
}
TEST_F(MutateTests, DeleteTest) {
// We are going to insert a tile group into a table in this test
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
LaunchParallelTest(1, DeleteTuple, table);
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, nullptr, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
EXPECT_EQ(tuple_cnt, 6);
delete table;
tuple_id = 0;
}
int SeqScanCount(storage::DataTable *table,
const std::vector<oid_t> &column_ids,
expression::AbstractExpression *predicate) {
auto &txn_manager = concurrency::OptimisticTransactionManager::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
planner::SeqScanPlan seq_scan_node(table, predicate, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
return tuple_cnt;
}
TEST_F(MutateTests, UpdateTest) {
// We are going to insert a tile group into a table in this test
storage::DataTable *table = ExecutorTestsUtil::CreateTable();
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
LaunchParallelTest(1, UpdateTuple, table);
// Seq scan to check number
std::vector<oid_t> column_ids = {0};
auto tuple_cnt = SeqScanCount(table, column_ids, nullptr);
EXPECT_EQ(tuple_cnt, 10);
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(0, 2);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetDoubleValue(23.5));
auto predicate = new expression::ComparisonExpression<expression::CmpEq>(
EXPRESSION_TYPE_COMPARE_EQUAL, tup_val_exp, const_val_exp);
tuple_cnt = SeqScanCount(table, column_ids, predicate);
EXPECT_EQ(tuple_cnt, 6);
delete table;
tuple_id = 0;
}
} // namespace test
} // namespace peloton
<|endoftext|> |
<commit_before>#include "common_inductives.hh"
/*-------------------------------------------------------------------------------------------*/
const SDD one = sdd::one<conf>();
const hom id = sdd::hom::Id<conf>();
/*-------------------------------------------------------------------------------------------*/
targeted_incr::targeted_incr(const std::string& var, unsigned int val)
: var_(var)
, value_(val)
{
}
bool
targeted_incr::skip(const std::string& var)
const noexcept
{
return var != var_;
}
hom
targeted_incr::operator()(const order<conf>& o, const SDD& x)
const
{
return Cons(o.identifier(), o, x, Inductive<conf>(*this));
}
hom
targeted_incr::operator()(const order<conf>& o, const bitset& val)
const
{
if (val.content().test(2))
{
return Cons(o.identifier(), o, val, id);
}
else
{
return Cons(o.identifier(), o, val << value_, id);
}
}
SDD
targeted_incr::operator()()
const noexcept
{
return one;
}
bool
targeted_incr::operator==(const targeted_incr& other)
const noexcept
{
return var_ == other.var_ and value_ == other.value_;
}
std::ostream&
operator<<(std::ostream& os, const targeted_incr& i)
{
return os << "target_incr(" << i.var_ << ", " << i.value_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
incr::incr(unsigned int val)
: value_(val)
{
}
bool
incr::skip(const std::string&)
const noexcept
{
return false;
}
bool
incr::selector()
const noexcept
{
return false;
}
hom
incr::operator()(const order<conf>& o, const SDD& x)
const
{
return Cons(o.identifier(), o, x, Inductive<conf>(*this));
}
hom
incr::operator()(const order<conf>& o, const bitset& val)
const
{
if (val.content().test(2))
{
return Cons(o.identifier(), o, val, id);
}
else
{
return Cons(o.identifier(), o, val << value_, id);
}
}
SDD
incr::operator()()
const noexcept
{
return one;
}
bool
incr::operator==(const incr& other)
const noexcept
{
return value_ == other.value_;
}
std::ostream&
operator<<(std::ostream& os, const incr& i)
{
return os << "incr(" << i.value_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
targeted_noop::targeted_noop(const std::string& v)
: var_(v)
{
}
bool
targeted_noop::skip(const std::string& var)
const noexcept
{
return var != var_;
}
bool
targeted_noop::selector()
const noexcept
{
return true;
}
hom
targeted_noop::operator()(const order<conf>& o, const SDD& val)
const
{
return Cons(o.identifier(), o, val, id);
}
hom
targeted_noop::operator()(const order<conf>& o, const bitset& val)
const
{
return Cons(o.identifier(), o, val, id);
}
SDD
targeted_noop::operator()()
const noexcept
{
return one;
}
bool
targeted_noop::operator==(const targeted_noop& other)
const noexcept
{
return var_ == other.var_;
}
std::ostream&
operator<<(std::ostream& os, const targeted_noop& i)
{
return os << "targeted_noop(" << i.var_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
namespace std {
std::size_t
hash<targeted_incr>::operator()(const targeted_incr& i)
const noexcept
{
return std::hash<std::string>()(i.var_) xor std::hash<unsigned char>()(i.value_);
}
std::size_t
hash<incr>::operator()(const incr& i)
const noexcept
{
return std::hash<unsigned char>()(i.value_);
}
std::size_t
hash<targeted_noop>::operator()(const targeted_noop& i)
const noexcept
{
return std::hash<std::string>()(i.var_);
}
} // namespace std
/*-------------------------------------------------------------------------------------------*/
<commit_msg>Correct hash functions for common inductives.<commit_after>#include "common_inductives.hh"
/*-------------------------------------------------------------------------------------------*/
const SDD one = sdd::one<conf>();
const hom id = sdd::hom::Id<conf>();
/*-------------------------------------------------------------------------------------------*/
targeted_incr::targeted_incr(const std::string& var, unsigned int val)
: var_(var)
, value_(val)
{
}
bool
targeted_incr::skip(const std::string& var)
const noexcept
{
return var != var_;
}
hom
targeted_incr::operator()(const order<conf>& o, const SDD& x)
const
{
return Cons(o.identifier(), o, x, Inductive<conf>(*this));
}
hom
targeted_incr::operator()(const order<conf>& o, const bitset& val)
const
{
if (val.content().test(2))
{
return Cons(o.identifier(), o, val, id);
}
else
{
return Cons(o.identifier(), o, val << value_, id);
}
}
SDD
targeted_incr::operator()()
const noexcept
{
return one;
}
bool
targeted_incr::operator==(const targeted_incr& other)
const noexcept
{
return var_ == other.var_ and value_ == other.value_;
}
std::ostream&
operator<<(std::ostream& os, const targeted_incr& i)
{
return os << "target_incr(" << i.var_ << ", " << i.value_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
incr::incr(unsigned int val)
: value_(val)
{
}
bool
incr::skip(const std::string&)
const noexcept
{
return false;
}
bool
incr::selector()
const noexcept
{
return false;
}
hom
incr::operator()(const order<conf>& o, const SDD& x)
const
{
return Cons(o.identifier(), o, x, Inductive<conf>(*this));
}
hom
incr::operator()(const order<conf>& o, const bitset& val)
const
{
if (val.content().test(2))
{
return Cons(o.identifier(), o, val, id);
}
else
{
return Cons(o.identifier(), o, val << value_, id);
}
}
SDD
incr::operator()()
const noexcept
{
return one;
}
bool
incr::operator==(const incr& other)
const noexcept
{
return value_ == other.value_;
}
std::ostream&
operator<<(std::ostream& os, const incr& i)
{
return os << "incr(" << i.value_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
targeted_noop::targeted_noop(const std::string& v)
: var_(v)
{
}
bool
targeted_noop::skip(const std::string& var)
const noexcept
{
return var != var_;
}
bool
targeted_noop::selector()
const noexcept
{
return true;
}
hom
targeted_noop::operator()(const order<conf>& o, const SDD& val)
const
{
return Cons(o.identifier(), o, val, id);
}
hom
targeted_noop::operator()(const order<conf>& o, const bitset& val)
const
{
return Cons(o.identifier(), o, val, id);
}
SDD
targeted_noop::operator()()
const noexcept
{
return one;
}
bool
targeted_noop::operator==(const targeted_noop& other)
const noexcept
{
return var_ == other.var_;
}
std::ostream&
operator<<(std::ostream& os, const targeted_noop& i)
{
return os << "targeted_noop(" << i.var_ << ")";
}
/*-------------------------------------------------------------------------------------------*/
namespace std {
std::size_t
hash<targeted_incr>::operator()(const targeted_incr& i)
const noexcept
{
return std::hash<std::string>()(i.var_) xor std::hash<unsigned int>()(i.value_);
}
std::size_t
hash<incr>::operator()(const incr& i)
const noexcept
{
return std::hash<unsigned int>()(i.value_);
}
std::size_t
hash<targeted_noop>::operator()(const targeted_noop& i)
const noexcept
{
return std::hash<std::string>()(i.var_);
}
} // namespace std
/*-------------------------------------------------------------------------------------------*/
<|endoftext|> |
<commit_before>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2015 Igor Mironchik
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.
*/
// Qt include.
#include <QAbstractButton>
#include <QFontMetrics>
#include <QPainter>
#include <QTextOption>
#include <QMap>
#include <QList>
#include <QFrame>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QResizeEvent>
#include <QFrame>
// QtMWidgets include.
#include "messagebox.hpp"
#include "fingergeometry.hpp"
#include "scrollarea.hpp"
#include "textlabel.hpp"
namespace QtMWidgets {
class MsgBoxButton;
//
// MsgBoxButtonPrivate
//
class MsgBoxButtonPrivate {
public:
MsgBoxButtonPrivate( const QString & t, MsgBoxButton * parent )
: q( parent )
, text( t )
, pressed( false )
{
}
void init();
MsgBoxButton * q;
QString text;
bool pressed;
}; // class MsgBoxButtonPrivate
//
// MsgBoxButton
//
class MsgBoxButton
: public QAbstractButton
{
Q_OBJECT
public:
explicit MsgBoxButton( const QString & text, QWidget * parent = 0 )
: QAbstractButton( parent )
, d( new MsgBoxButtonPrivate( text, this ) )
{
d->init();
connect( this, &QAbstractButton::pressed,
this, &MsgBoxButton::_q_pressed );
connect( this, &QAbstractButton::released,
this, &MsgBoxButton::_q_released );
}
virtual ~MsgBoxButton()
{
}
virtual QSize minimumSizeHint() const
{
const int margin = fontMetrics().height() / 3;
const QSize s = fontMetrics()
.boundingRect( QRect(), Qt::AlignCenter, d->text )
.marginsAdded( QMargins( margin, margin, margin, margin ) )
.size();
return QSize( qMax( s.width(), FingerGeometry::width() ),
qMax( s.height(), FingerGeometry::height() ) );
}
virtual QSize sizeHint() const
{
return minimumSizeHint();
}
protected:
virtual void paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setPen( palette().color( QPalette::WindowText ) );
p.drawText( rect(), d->text, QTextOption( Qt::AlignCenter ) );
if( d->pressed )
{
QColor c = palette().color( QPalette::Highlight );
c.setAlpha( 75 );
p.setPen( Qt::NoPen );
p.setBrush( c );
p.drawRect( rect() );
}
}
private slots:
void _q_pressed()
{
d->pressed = true;
update();
}
void _q_released()
{
d->pressed = false;
update();
}
private:
Q_DISABLE_COPY( MsgBoxButton )
QScopedPointer< MsgBoxButtonPrivate > d;
}; // class MsgBoxButton
//
// MsgBoxButtonPrivate
//
void
MsgBoxButtonPrivate::init()
{
q->setBackgroundRole( QPalette::Window );
q->setAutoFillBackground( true );
q->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
}
class MsgBoxTitle;
//
// MsgBoxTitlePrivate
//
class MsgBoxTitlePrivate {
public:
MsgBoxTitlePrivate( const QString & t, MsgBoxTitle * parent )
: q( parent )
, title( t )
, margin( 10 )
{
}
void init();
void prepareTitle();
MsgBoxTitle * q;
QString title;
int margin;
QString preparedTitle;
}; // class MsgBoxTitlePrivate
//
// MsgBoxTitle
//
class MsgBoxTitle
: public QWidget
{
public:
explicit MsgBoxTitle( const QString & title, QWidget * parent = 0 )
: QWidget( parent )
, d( new MsgBoxTitlePrivate( title, this ) )
{
d->init();
}
virtual ~MsgBoxTitle()
{
}
protected:
virtual void paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setPen( palette().color( QPalette::WindowText ) );
p.drawText( rect().marginsRemoved( QMargins( d->margin, 0,
d->margin, 0 ) ),
d->preparedTitle, QTextOption( Qt::AlignLeft | Qt::AlignVCenter ) );
}
virtual void resizeEvent( QResizeEvent * )
{
d->prepareTitle();
}
private:
Q_DISABLE_COPY( MsgBoxTitle )
QScopedPointer< MsgBoxTitlePrivate > d;
}; // class MsgBoxTitle
//
// MsgBoxTitlePrivate
//
void
MsgBoxTitlePrivate::init()
{
q->setBackgroundRole( QPalette::Window );
q->setAutoFillBackground( true );
q->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
q->setMinimumHeight( qMax( FingerGeometry::height(),
q->fontMetrics().height() + q->fontMetrics().height() / 3 ) );
prepareTitle();
}
void
MsgBoxTitlePrivate::prepareTitle()
{
const QRect r = q->rect().marginsRemoved( QMargins( margin, 0,
margin, 0 ) );
const QRect & b = q->fontMetrics().boundingRect( r,
Qt::AlignLeft, title );
preparedTitle = title;
if( b.width() > r.width() )
{
const int averageCount = r.width() / q->fontMetrics().averageCharWidth();
preparedTitle = title.left( averageCount - 3 );
preparedTitle.append( QLatin1String( "..." ) );
}
}
//
// MessageBoxPrivate
//
class MessageBoxPrivate {
public:
MessageBoxPrivate( const QString & titl,
const QString & txt, MessageBox * parent, QWidget * w )
: q( parent )
, frame( 0 )
, vbox( 0 )
, hbox( 0 )
, title( 0 )
, scrollArea( 0 )
, textLabel( 0 )
, okButton( 0 )
, clickedButton( 0 )
, screenMargin( 6 )
, window( w )
{
init( titl, txt );
}
void init( const QString & titl, const QString & txt );
void adjustSize();
MessageBox * q;
QMap< QAbstractButton*, MessageBox::ButtonRole > buttonsMap;
QFrame * frame;
QVBoxLayout * vbox;
QHBoxLayout * hbox;
MsgBoxTitle * title;
ScrollArea * scrollArea;
TextLabel * textLabel;
MsgBoxButton * okButton;
QList< QFrame * > buttonSeparators;
QAbstractButton * clickedButton;
QList< QAbstractButton* > buttons;
int screenMargin;
QWidget * window;
}; // class MessageBoxPrivate
void
MessageBoxPrivate::init( const QString & titl, const QString & txt )
{
q->setModal( true );
frame = new QFrame( q );
frame->setFrameStyle( QFrame::StyledPanel | QFrame::Sunken );
vbox = new QVBoxLayout( frame );
vbox->setSpacing( 0 );
vbox->setContentsMargins( 3, 3, 3, 3 );
title = new MsgBoxTitle( titl, frame );
vbox->addWidget( title );
QFrame * h1 = new QFrame( frame );
h1->setFrameStyle( QFrame::HLine | QFrame::Sunken );
vbox->addWidget( h1 );
scrollArea = new ScrollArea( frame );
scrollArea->setWidgetResizable( true );
textLabel = new TextLabel( frame );
textLabel->setBackgroundRole( QPalette::Window );
textLabel->setAutoFillBackground( true );
textLabel->setText( txt );
scrollArea->setWidget( textLabel );
vbox->addWidget( scrollArea );
QFrame * h2 = new QFrame( frame );
h2->setFrameStyle( QFrame::HLine | QFrame::Sunken );
vbox->addWidget( h2 );
hbox = new QHBoxLayout;
hbox->setSpacing( 0 );
hbox->setContentsMargins( 0, 0, 0, 0 );
okButton = new MsgBoxButton( QObject::tr( "OK" ), frame );
buttonsMap.insert( okButton, MessageBox::AcceptRole );
buttons.append( okButton );
hbox->addWidget( okButton );
vbox->addLayout( hbox );
q->resize( vbox->sizeHint() );
}
void
MessageBoxPrivate::adjustSize()
{
if( window )
{
const QSize ws = window->window()->size();
const QSize s = q->size();
const QRect wr = window->window()->rect();
if( s.width() > ws.width() - screenMargin * 2 ||
s.height() > ws.height() - screenMargin * 2 )
{
q->resize( QSize( qMin( s.width(), ws.width() - screenMargin * 2 ),
qMin( s.height(), ws.height() - screenMargin * 2 ) ) );
q->move( wr.x() + ( ws.width() - q->width() ) / 2,
wr.y() + ( ws.height() - q->height() ) / 2 );
vbox->update();
}
}
}
//
// MessageBox
//
MessageBox::MessageBox( const QString & title,
const QString & text, QWidget * parent )
: QDialog( parent, Qt::Dialog | Qt::ToolTip | Qt::FramelessWindowHint )
, d( new MessageBoxPrivate( title, text, this, parent ) )
{
connect( d->okButton, &MsgBoxButton::clicked,
this, &MessageBox::_q_clicked );
d->adjustSize();
}
MessageBox::~MessageBox()
{
}
void
MessageBox::addButton( QAbstractButton * button, ButtonRole role )
{
if( !d->buttonsMap.contains( button ) )
{
QFrame * line = new QFrame( d->frame );
line->setFrameStyle( QFrame::VLine | QFrame::Sunken );
d->buttonSeparators.append( line );
d->buttonsMap.insert( button, role );
d->buttons.append( button );
d->hbox->addWidget( line );
d->hbox->addWidget( button );
connect( button, &QAbstractButton::clicked,
this, &MessageBox::_q_clicked );
resize( d->vbox->sizeHint() );
}
}
QAbstractButton *
MessageBox::addButton( const QString & text, ButtonRole role )
{
MsgBoxButton * button = new MsgBoxButton( text, d->frame );
addButton( button, role );
return button;
}
QList< QAbstractButton* >
MessageBox::buttons( ButtonRole role ) const
{
QList< QAbstractButton* > list;
for( QMap< QAbstractButton*, ButtonRole >::const_iterator
it = d->buttonsMap.constBegin(), last = d->buttonsMap.constEnd();
it != last; ++it )
{
if( it.value() == role )
list.append( it.key() );
}
return list;
}
MessageBox::ButtonRole
MessageBox::buttonRole( QAbstractButton * button ) const
{
if( d->buttonsMap.contains( button ) )
return d->buttonsMap[ button ];
else
return InvalidRole;
}
const QList< QAbstractButton* > &
MessageBox::buttons() const
{
return d->buttons;
}
QAbstractButton *
MessageBox::clickedButton() const
{
return d->clickedButton;
}
void
MessageBox::removeButton( QAbstractButton * button )
{
if( d->okButton != button && d->buttonsMap.contains( button ) )
{
const int index = d->buttons.indexOf( button );
if( index != -1 )
{
QLayoutItem * b = d->hbox->takeAt( index * 2 );
QLayoutItem * l = d->hbox->takeAt( index * 2 - 1 );
if( l->widget() )
l->widget()->deleteLater();
delete b;
delete l;
d->buttons.removeAt( index );
d->buttonsMap.remove( button );
d->buttonSeparators.removeAt( index - 1 );
disconnect( button, 0, this, 0 );
resize( d->vbox->sizeHint() );
}
}
}
QString
MessageBox::text() const
{
return d->textLabel->text();
}
void
MessageBox::setText( const QString & t )
{
d->textLabel->setText( t );
d->adjustSize();
}
Qt::TextFormat
MessageBox::textFormat() const
{
return d->textLabel->textFormat();
}
void
MessageBox::setTextFormat( Qt::TextFormat fmt )
{
d->textLabel->setTextFormat( fmt );
}
void
MessageBox::resizeEvent( QResizeEvent * e )
{
d->frame->resize( e->size() );
d->adjustSize();
e->accept();
}
void
MessageBox::_q_clicked()
{
d->clickedButton = qobject_cast< QAbstractButton* > ( sender() );
ButtonRole role = d->buttonsMap[ d->clickedButton ];
switch( role )
{
case AcceptRole :
accept();
break;
case RejectRole :
reject();
break;
default :
break;
}
emit buttonClicked( d->clickedButton );
}
} /* namespace QtMWidgets */
#include "messagebox.moc"
<commit_msg>Improved adjustSize() in MessageBox.<commit_after>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2015 Igor Mironchik
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.
*/
// Qt include.
#include <QAbstractButton>
#include <QFontMetrics>
#include <QPainter>
#include <QTextOption>
#include <QMap>
#include <QList>
#include <QFrame>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QResizeEvent>
#include <QFrame>
#include <QApplication>
#include <QScreen>
// QtMWidgets include.
#include "messagebox.hpp"
#include "fingergeometry.hpp"
#include "scrollarea.hpp"
#include "textlabel.hpp"
namespace QtMWidgets {
class MsgBoxButton;
//
// MsgBoxButtonPrivate
//
class MsgBoxButtonPrivate {
public:
MsgBoxButtonPrivate( const QString & t, MsgBoxButton * parent )
: q( parent )
, text( t )
, pressed( false )
{
}
void init();
MsgBoxButton * q;
QString text;
bool pressed;
}; // class MsgBoxButtonPrivate
//
// MsgBoxButton
//
class MsgBoxButton
: public QAbstractButton
{
Q_OBJECT
public:
explicit MsgBoxButton( const QString & text, QWidget * parent = 0 )
: QAbstractButton( parent )
, d( new MsgBoxButtonPrivate( text, this ) )
{
d->init();
connect( this, &QAbstractButton::pressed,
this, &MsgBoxButton::_q_pressed );
connect( this, &QAbstractButton::released,
this, &MsgBoxButton::_q_released );
}
virtual ~MsgBoxButton()
{
}
virtual QSize minimumSizeHint() const
{
const int margin = fontMetrics().height() / 3;
const QSize s = fontMetrics()
.boundingRect( QRect(), Qt::AlignCenter, d->text )
.marginsAdded( QMargins( margin, margin, margin, margin ) )
.size();
return QSize( qMax( s.width(), FingerGeometry::width() ),
qMax( s.height(), FingerGeometry::height() ) );
}
virtual QSize sizeHint() const
{
return minimumSizeHint();
}
protected:
virtual void paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setPen( palette().color( QPalette::WindowText ) );
p.drawText( rect(), d->text, QTextOption( Qt::AlignCenter ) );
if( d->pressed )
{
QColor c = palette().color( QPalette::Highlight );
c.setAlpha( 75 );
p.setPen( Qt::NoPen );
p.setBrush( c );
p.drawRect( rect() );
}
}
private slots:
void _q_pressed()
{
d->pressed = true;
update();
}
void _q_released()
{
d->pressed = false;
update();
}
private:
Q_DISABLE_COPY( MsgBoxButton )
QScopedPointer< MsgBoxButtonPrivate > d;
}; // class MsgBoxButton
//
// MsgBoxButtonPrivate
//
void
MsgBoxButtonPrivate::init()
{
q->setBackgroundRole( QPalette::Window );
q->setAutoFillBackground( true );
q->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
}
class MsgBoxTitle;
//
// MsgBoxTitlePrivate
//
class MsgBoxTitlePrivate {
public:
MsgBoxTitlePrivate( const QString & t, MsgBoxTitle * parent )
: q( parent )
, title( t )
, margin( 10 )
{
}
void init();
void prepareTitle();
MsgBoxTitle * q;
QString title;
int margin;
QString preparedTitle;
}; // class MsgBoxTitlePrivate
//
// MsgBoxTitle
//
class MsgBoxTitle
: public QWidget
{
public:
explicit MsgBoxTitle( const QString & title, QWidget * parent = 0 )
: QWidget( parent )
, d( new MsgBoxTitlePrivate( title, this ) )
{
d->init();
}
virtual ~MsgBoxTitle()
{
}
protected:
virtual void paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setPen( palette().color( QPalette::WindowText ) );
p.drawText( rect().marginsRemoved( QMargins( d->margin, 0,
d->margin, 0 ) ),
d->preparedTitle, QTextOption( Qt::AlignLeft | Qt::AlignVCenter ) );
}
virtual void resizeEvent( QResizeEvent * )
{
d->prepareTitle();
}
private:
Q_DISABLE_COPY( MsgBoxTitle )
QScopedPointer< MsgBoxTitlePrivate > d;
}; // class MsgBoxTitle
//
// MsgBoxTitlePrivate
//
void
MsgBoxTitlePrivate::init()
{
q->setBackgroundRole( QPalette::Window );
q->setAutoFillBackground( true );
q->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
q->setMinimumHeight( qMax( FingerGeometry::height(),
q->fontMetrics().height() + q->fontMetrics().height() / 3 ) );
prepareTitle();
}
void
MsgBoxTitlePrivate::prepareTitle()
{
const QRect r = q->rect().marginsRemoved( QMargins( margin, 0,
margin, 0 ) );
const QRect & b = q->fontMetrics().boundingRect( r,
Qt::AlignLeft, title );
preparedTitle = title;
if( b.width() > r.width() )
{
const int averageCount = r.width() / q->fontMetrics().averageCharWidth();
preparedTitle = title.left( averageCount - 3 );
preparedTitle.append( QLatin1String( "..." ) );
}
}
//
// MessageBoxPrivate
//
class MessageBoxPrivate {
public:
MessageBoxPrivate( const QString & titl,
const QString & txt, MessageBox * parent, QWidget * w )
: q( parent )
, frame( 0 )
, vbox( 0 )
, hbox( 0 )
, title( 0 )
, scrollArea( 0 )
, textLabel( 0 )
, okButton( 0 )
, clickedButton( 0 )
, screenMargin( 6 )
, window( w )
, h1( 0 )
, h2( 0 )
{
init( titl, txt );
}
void init( const QString & titl, const QString & txt );
void adjustSize();
MessageBox * q;
QMap< QAbstractButton*, MessageBox::ButtonRole > buttonsMap;
QFrame * frame;
QVBoxLayout * vbox;
QHBoxLayout * hbox;
MsgBoxTitle * title;
ScrollArea * scrollArea;
TextLabel * textLabel;
MsgBoxButton * okButton;
QList< QFrame * > buttonSeparators;
QAbstractButton * clickedButton;
QList< QAbstractButton* > buttons;
int screenMargin;
QWidget * window;
QFrame * h1;
QFrame * h2;
}; // class MessageBoxPrivate
void
MessageBoxPrivate::init( const QString & titl, const QString & txt )
{
q->setModal( true );
frame = new QFrame( q );
frame->setFrameStyle( QFrame::StyledPanel | QFrame::Sunken );
vbox = new QVBoxLayout( frame );
vbox->setSpacing( 0 );
vbox->setContentsMargins( 3, 3, 3, 3 );
title = new MsgBoxTitle( titl, frame );
vbox->addWidget( title );
h1 = new QFrame( frame );
h1->setFrameStyle( QFrame::HLine | QFrame::Sunken );
vbox->addWidget( h1 );
scrollArea = new ScrollArea( frame );
scrollArea->setWidgetResizable( true );
textLabel = new TextLabel( frame );
textLabel->setBackgroundRole( QPalette::Window );
textLabel->setAutoFillBackground( true );
textLabel->setText( txt );
scrollArea->setWidget( textLabel );
vbox->addWidget( scrollArea );
h2 = new QFrame( frame );
h2->setFrameStyle( QFrame::HLine | QFrame::Sunken );
vbox->addWidget( h2 );
hbox = new QHBoxLayout;
hbox->setSpacing( 0 );
hbox->setContentsMargins( 0, 0, 0, 0 );
okButton = new MsgBoxButton( QObject::tr( "OK" ), frame );
buttonsMap.insert( okButton, MessageBox::AcceptRole );
buttons.append( okButton );
hbox->addWidget( okButton );
vbox->addLayout( hbox );
q->resize( vbox->sizeHint() );
}
void
MessageBoxPrivate::adjustSize()
{
QSize ws = QApplication::primaryScreen()->availableSize();
QSize s = q->size();
QRect wr = QApplication::primaryScreen()->availableGeometry();
if( window )
{
ws = window->window()->size();
wr = window->window()->rect();
}
qreal factor = (qreal) s.height() / (qreal) s.width();
if( factor > 1.5 )
{
const int width = qRound( (qreal) s.width() * factor );
s = QSize( width,
textLabel->heightForWidth( width ) + title->height() +
okButton->height() + h1->height() + h2->height() );
}
if( s.width() > ws.width() - screenMargin * 2 )
{
const int width = ws.width() - screenMargin * 2;
s = QSize( width,
textLabel->heightForWidth( width ) + title->height() +
okButton->height() + h1->height() + h2->height() );
}
if( s.height() > ws.height() - screenMargin * 2 )
s = QSize( s.width(), ws.height() - screenMargin * 2 );
q->resize( s );
q->move( wr.x() + ( ws.width() - s.width() ) / 2,
wr.y() + ( ws.height() - s.height() ) / 2 );
vbox->update();
}
//
// MessageBox
//
MessageBox::MessageBox( const QString & title,
const QString & text, QWidget * parent )
: QDialog( parent, Qt::Dialog | Qt::ToolTip | Qt::FramelessWindowHint )
, d( new MessageBoxPrivate( title, text, this, parent ) )
{
connect( d->okButton, &MsgBoxButton::clicked,
this, &MessageBox::_q_clicked );
d->adjustSize();
}
MessageBox::~MessageBox()
{
}
void
MessageBox::addButton( QAbstractButton * button, ButtonRole role )
{
if( !d->buttonsMap.contains( button ) )
{
QFrame * line = new QFrame( d->frame );
line->setFrameStyle( QFrame::VLine | QFrame::Sunken );
d->buttonSeparators.append( line );
d->buttonsMap.insert( button, role );
d->buttons.append( button );
d->hbox->addWidget( line );
d->hbox->addWidget( button );
connect( button, &QAbstractButton::clicked,
this, &MessageBox::_q_clicked );
resize( d->vbox->sizeHint() );
d->adjustSize();
}
}
QAbstractButton *
MessageBox::addButton( const QString & text, ButtonRole role )
{
MsgBoxButton * button = new MsgBoxButton( text, d->frame );
addButton( button, role );
return button;
}
QList< QAbstractButton* >
MessageBox::buttons( ButtonRole role ) const
{
QList< QAbstractButton* > list;
for( QMap< QAbstractButton*, ButtonRole >::const_iterator
it = d->buttonsMap.constBegin(), last = d->buttonsMap.constEnd();
it != last; ++it )
{
if( it.value() == role )
list.append( it.key() );
}
return list;
}
MessageBox::ButtonRole
MessageBox::buttonRole( QAbstractButton * button ) const
{
if( d->buttonsMap.contains( button ) )
return d->buttonsMap[ button ];
else
return InvalidRole;
}
const QList< QAbstractButton* > &
MessageBox::buttons() const
{
return d->buttons;
}
QAbstractButton *
MessageBox::clickedButton() const
{
return d->clickedButton;
}
void
MessageBox::removeButton( QAbstractButton * button )
{
if( d->okButton != button && d->buttonsMap.contains( button ) )
{
const int index = d->buttons.indexOf( button );
if( index != -1 )
{
QLayoutItem * b = d->hbox->takeAt( index * 2 );
QLayoutItem * l = d->hbox->takeAt( index * 2 - 1 );
if( l->widget() )
l->widget()->deleteLater();
delete b;
delete l;
d->buttons.removeAt( index );
d->buttonsMap.remove( button );
d->buttonSeparators.removeAt( index - 1 );
disconnect( button, 0, this, 0 );
resize( d->vbox->sizeHint() );
d->adjustSize();
}
}
}
QString
MessageBox::text() const
{
return d->textLabel->text();
}
void
MessageBox::setText( const QString & t )
{
d->textLabel->setText( t );
d->adjustSize();
}
Qt::TextFormat
MessageBox::textFormat() const
{
return d->textLabel->textFormat();
}
void
MessageBox::setTextFormat( Qt::TextFormat fmt )
{
d->textLabel->setTextFormat( fmt );
}
void
MessageBox::resizeEvent( QResizeEvent * e )
{
d->frame->resize( e->size() );
e->accept();
}
void
MessageBox::_q_clicked()
{
d->clickedButton = qobject_cast< QAbstractButton* > ( sender() );
ButtonRole role = d->buttonsMap[ d->clickedButton ];
switch( role )
{
case AcceptRole :
accept();
break;
case RejectRole :
reject();
break;
default :
break;
}
emit buttonClicked( d->clickedButton );
}
} /* namespace QtMWidgets */
#include "messagebox.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <limits>
#include <libport/ufloat.hh>
#include <libport/tr1/type_traits>
#include <libport/unit-test.hh>
#include <iostream>
using libport::test_suite;
using libport::ufloat;
static void check_comparison()
{
ufloat f = 1;
ufloat g = 10;
BOOST_CHECK_LT(f, g);
BOOST_CHECK_GT(g, f);
BOOST_CHECK_LE(f, g);
BOOST_CHECK_GE(g, f);
BOOST_CHECK_NE(f, g);
BOOST_CHECK_EQUAL(f, f);
BOOST_CHECK_LE(f, f);
BOOST_CHECK_GE(f, f);
}
/*---------------.
| numeric_cast. |
`---------------*/
#define CHECK_TO_AND_FRO(Value) \
do { \
T value = Value; \
BOOST_TEST_MESSAGE("Checking " #Value " = " << value); \
BOOST_CHECK_EQUAL(libport::numeric_cast<T>(ufloat(value)), \
value); \
} while (0)
#define CHECK_LIMIT(Name) \
CHECK_TO_AND_FRO(std::numeric_limits<T>::Name())
template <typename T>
static void check_max()
{
CHECK_LIMIT(max);
}
template <typename T>
static void check_unsigned_range()
{
CHECK_LIMIT(epsilon);
CHECK_LIMIT(min);
CHECK_TO_AND_FRO(0);
CHECK_TO_AND_FRO(1);
CHECK_TO_AND_FRO(100);
}
template <typename T>
static void check_signed_range()
{
check_unsigned_range<T>();
CHECK_TO_AND_FRO(-1);
CHECK_TO_AND_FRO(-100);
}
#undef CHECK_LIMIT
#undef CHECK_TO_AND_FRO
template <typename T>
static void check_rounding_cast()
{
#define CHECK_(In, Out) \
BOOST_CHECK_EQUAL(libport::rounding_cast<T>(ufloat(In)), Out)
#define CHECK(In, Out) \
do { \
CHECK_(In, Out); \
std::cerr << "Unsigned: " << std::tr1::is_unsigned<T>::value << std::endl; \
if (!std::tr1::is_unsigned<T>::value) \
CHECK_(-In, -Out); \
} while (false)
CHECK(0, 0);
CHECK(0.4999, 0);
CHECK(0.5, 0);
CHECK(0.50001, 1);
CHECK(0.9999, 1);
CHECK(1, 1);
CHECK(1.4, 1);
CHECK(1.45, 1);
CHECK(1.49999, 1);
CHECK(1.5, 2);
CHECK(1.50001, 2);
CHECK(255.0, 255);
#undef CHECK
#undef CHECK_
}
/*-------------------.
| numeric_castable. |
`-------------------*/
static void
check_castable()
{
BOOST_CHECK( libport::numeric_castable<int>(65536.0));
BOOST_CHECK(!libport::numeric_castable<int>(65536.1));
BOOST_CHECK(!libport::numeric_castable<int>(4294967296.0));
// Does not work on 32b machines where int == long.
if (32 <= sizeof(long))
{
BOOST_CHECK( libport::numeric_castable<long>(4294967296.0));
BOOST_CHECK(!libport::numeric_castable<long>(4294967296.1));
BOOST_CHECK( libport::numeric_castable<long>( 21474836470.0));
BOOST_CHECK( libport::numeric_castable<long>(-21474836470.0));
BOOST_CHECK(!libport::numeric_castable<long>( 21474836470.1));
}
// These do not fit into doubles.
// // std::numeric_limits<long long>::max()
// BOOST_CHECK( libport::numeric_castable<long long>(9223372036854775807.0));
// BOOST_CHECK(!libport::numeric_castable<long long>(9223372036854775807.1));
}
test_suite*
init_test_suite()
{
test_suite* suite = BOOST_TEST_SUITE("libport::ufloat");
suite->add(BOOST_TEST_CASE(check_comparison));
suite->add(BOOST_TEST_CASE(check_castable));
// The following use of "&" are required to please MSVC. Otherwise
// at runtime it just dies:
//
// unknown location(0): fatal error in "check_signed_range<int>":
// memory access violation
#define CHECK(Type) \
suite->add(BOOST_TEST_CASE(&check_signed_range<Type>)); \
suite->add(BOOST_TEST_CASE(&check_max<Type>)); \
suite->add(BOOST_TEST_CASE(&check_rounding_cast<Type>));
CHECK(char);
CHECK(unsigned char);
CHECK(short);
CHECK(unsigned short);
CHECK(int);
CHECK(unsigned int);
#undef CHECK
// long.
suite->add(BOOST_TEST_CASE(&check_signed_range<long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<long>));
// On 64 bits, long is like long long, see below...
#if !(defined LIBPORT_URBI_UFLOAT_DOUBLE && _LP64)
suite->add(BOOST_TEST_CASE(&check_max<long>));
#endif
// unsigned long.
suite->add(BOOST_TEST_CASE(&check_unsigned_range<unsigned long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<unsigned long>));
#if !(defined LIBPORT_URBI_UFLOAT_DOUBLE && _LP64)
suite->add(BOOST_TEST_CASE(&check_max<unsigned long>));
#endif
// long long.
suite->add(BOOST_TEST_CASE(&check_signed_range<long long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<long long>));
// unsigned long long.
suite->add(BOOST_TEST_CASE(&check_unsigned_range<unsigned long long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<unsigned long long>));
// We can't represent these values in doubles.
// suite->add(BOOST_TEST_CASE(check_max<long long>));
// suite->add(BOOST_TEST_CASE(check_max<unsigned long long>));
return suite;
}
<commit_msg>Libport.Ufloat: remove stray debug log.<commit_after>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <limits>
#include <libport/ufloat.hh>
#include <libport/tr1/type_traits>
#include <libport/unit-test.hh>
#include <iostream>
using libport::test_suite;
using libport::ufloat;
static void check_comparison()
{
ufloat f = 1;
ufloat g = 10;
BOOST_CHECK_LT(f, g);
BOOST_CHECK_GT(g, f);
BOOST_CHECK_LE(f, g);
BOOST_CHECK_GE(g, f);
BOOST_CHECK_NE(f, g);
BOOST_CHECK_EQUAL(f, f);
BOOST_CHECK_LE(f, f);
BOOST_CHECK_GE(f, f);
}
/*---------------.
| numeric_cast. |
`---------------*/
#define CHECK_TO_AND_FRO(Value) \
do { \
T value = Value; \
BOOST_TEST_MESSAGE("Checking " #Value " = " << value); \
BOOST_CHECK_EQUAL(libport::numeric_cast<T>(ufloat(value)), \
value); \
} while (0)
#define CHECK_LIMIT(Name) \
CHECK_TO_AND_FRO(std::numeric_limits<T>::Name())
template <typename T>
static void check_max()
{
CHECK_LIMIT(max);
}
template <typename T>
static void check_unsigned_range()
{
CHECK_LIMIT(epsilon);
CHECK_LIMIT(min);
CHECK_TO_AND_FRO(0);
CHECK_TO_AND_FRO(1);
CHECK_TO_AND_FRO(100);
}
template <typename T>
static void check_signed_range()
{
check_unsigned_range<T>();
CHECK_TO_AND_FRO(-1);
CHECK_TO_AND_FRO(-100);
}
#undef CHECK_LIMIT
#undef CHECK_TO_AND_FRO
template <typename T>
static void check_rounding_cast()
{
#define CHECK_(In, Out) \
BOOST_CHECK_EQUAL(libport::rounding_cast<T>(ufloat(In)), Out)
#define CHECK(In, Out) \
do { \
CHECK_(In, Out); \
if (!std::tr1::is_unsigned<T>::value) \
CHECK_(-In, -Out); \
} while (false)
CHECK(0, 0);
CHECK(0.4999, 0);
CHECK(0.5, 0);
CHECK(0.50001, 1);
CHECK(0.9999, 1);
CHECK(1, 1);
CHECK(1.4, 1);
CHECK(1.45, 1);
CHECK(1.49999, 1);
CHECK(1.5, 2);
CHECK(1.50001, 2);
CHECK(255.0, 255);
#undef CHECK
#undef CHECK_
}
/*-------------------.
| numeric_castable. |
`-------------------*/
static void
check_castable()
{
BOOST_CHECK( libport::numeric_castable<int>(65536.0));
BOOST_CHECK(!libport::numeric_castable<int>(65536.1));
BOOST_CHECK(!libport::numeric_castable<int>(4294967296.0));
// Does not work on 32b machines where int == long.
if (32 <= sizeof(long))
{
BOOST_CHECK( libport::numeric_castable<long>(4294967296.0));
BOOST_CHECK(!libport::numeric_castable<long>(4294967296.1));
BOOST_CHECK( libport::numeric_castable<long>( 21474836470.0));
BOOST_CHECK( libport::numeric_castable<long>(-21474836470.0));
BOOST_CHECK(!libport::numeric_castable<long>( 21474836470.1));
}
// These do not fit into doubles.
// // std::numeric_limits<long long>::max()
// BOOST_CHECK( libport::numeric_castable<long long>(9223372036854775807.0));
// BOOST_CHECK(!libport::numeric_castable<long long>(9223372036854775807.1));
}
test_suite*
init_test_suite()
{
test_suite* suite = BOOST_TEST_SUITE("libport::ufloat");
suite->add(BOOST_TEST_CASE(check_comparison));
suite->add(BOOST_TEST_CASE(check_castable));
// The following use of "&" are required to please MSVC. Otherwise
// at runtime it just dies:
//
// unknown location(0): fatal error in "check_signed_range<int>":
// memory access violation
#define CHECK(Type) \
suite->add(BOOST_TEST_CASE(&check_signed_range<Type>)); \
suite->add(BOOST_TEST_CASE(&check_max<Type>)); \
suite->add(BOOST_TEST_CASE(&check_rounding_cast<Type>));
CHECK(char);
CHECK(unsigned char);
CHECK(short);
CHECK(unsigned short);
CHECK(int);
CHECK(unsigned int);
#undef CHECK
// long.
suite->add(BOOST_TEST_CASE(&check_signed_range<long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<long>));
// On 64 bits, long is like long long, see below...
#if !(defined LIBPORT_URBI_UFLOAT_DOUBLE && _LP64)
suite->add(BOOST_TEST_CASE(&check_max<long>));
#endif
// unsigned long.
suite->add(BOOST_TEST_CASE(&check_unsigned_range<unsigned long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<unsigned long>));
#if !(defined LIBPORT_URBI_UFLOAT_DOUBLE && _LP64)
suite->add(BOOST_TEST_CASE(&check_max<unsigned long>));
#endif
// long long.
suite->add(BOOST_TEST_CASE(&check_signed_range<long long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<long long>));
// unsigned long long.
suite->add(BOOST_TEST_CASE(&check_unsigned_range<unsigned long long>));
suite->add(BOOST_TEST_CASE(&check_rounding_cast<unsigned long long>));
// We can't represent these values in doubles.
// suite->add(BOOST_TEST_CASE(check_max<long long>));
// suite->add(BOOST_TEST_CASE(check_max<unsigned long long>));
return suite;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <boost/test/unit_test.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/account_object.hpp>
#include <fc/crypto/digest.hpp>
#include "../common/database_fixture.hpp"
using namespace graphene::chain;
BOOST_FIXTURE_TEST_SUITE( database_tests, database_fixture )
BOOST_AUTO_TEST_CASE( undo_test )
{
try {
database db;
auto ses = db._undo_db.start_undo_session();
const auto& bal_obj1 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
/* no balances right now */
});
auto id1 = bal_obj1.id;
// abandon changes
ses.undo();
// start a new session
ses = db._undo_db.start_undo_session();
const auto& bal_obj2 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
/* no balances right now */
});
auto id2 = bal_obj2.id;
BOOST_CHECK( id1 == id2 );
} catch ( const fc::exception& e )
{
edump( (e.to_detail_string()) );
throw;
}
}
BOOST_AUTO_TEST_CASE( flat_index_test )
{
ACTORS((sam));
const auto& bitusd = create_bitasset("USDBIT", sam.id);
update_feed_producers(bitusd, {sam.id});
price_feed current_feed;
current_feed.settlement_price = bitusd.amount(100) / asset(100);
publish_feed(bitusd, sam, current_feed);
FC_ASSERT( bitusd.bitasset_data_id->instance == 0 );
FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
try {
auto ses = db._undo_db.start_undo_session();
const auto& obj1 = db.create<asset_bitasset_data_object>( [&]( asset_bitasset_data_object& obj ){
obj.settlement_fund = 17;
});
FC_ASSERT( obj1.settlement_fund == 17 );
throw std::string("Expected");
// With flat_index, obj1 will not really be removed from the index
} catch ( const std::string& e )
{ // ignore
}
// force maintenance
const auto& dynamic_global_props = db.get<dynamic_global_property_object>(dynamic_global_property_id_type());
generate_blocks(dynamic_global_props.next_maintenance_time, true);
FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Added test case for broken merge on empty undo_db<commit_after>/*
* Copyright (c) 2017 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <boost/test/unit_test.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/account_object.hpp>
#include <fc/crypto/digest.hpp>
#include "../common/database_fixture.hpp"
using namespace graphene::chain;
BOOST_FIXTURE_TEST_SUITE( database_tests, database_fixture )
BOOST_AUTO_TEST_CASE( undo_test )
{
try {
database db;
auto ses = db._undo_db.start_undo_session();
const auto& bal_obj1 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
/* no balances right now */
});
auto id1 = bal_obj1.id;
// abandon changes
ses.undo();
// start a new session
ses = db._undo_db.start_undo_session();
const auto& bal_obj2 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
/* no balances right now */
});
auto id2 = bal_obj2.id;
BOOST_CHECK( id1 == id2 );
} catch ( const fc::exception& e )
{
edump( (e.to_detail_string()) );
throw;
}
}
BOOST_AUTO_TEST_CASE( flat_index_test )
{
ACTORS((sam));
const auto& bitusd = create_bitasset("USDBIT", sam.id);
update_feed_producers(bitusd, {sam.id});
price_feed current_feed;
current_feed.settlement_price = bitusd.amount(100) / asset(100);
publish_feed(bitusd, sam, current_feed);
FC_ASSERT( bitusd.bitasset_data_id->instance == 0 );
FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
try {
auto ses = db._undo_db.start_undo_session();
const auto& obj1 = db.create<asset_bitasset_data_object>( [&]( asset_bitasset_data_object& obj ){
obj.settlement_fund = 17;
});
FC_ASSERT( obj1.settlement_fund == 17 );
throw std::string("Expected");
// With flat_index, obj1 will not really be removed from the index
} catch ( const std::string& e )
{ // ignore
}
// force maintenance
const auto& dynamic_global_props = db.get<dynamic_global_property_object>(dynamic_global_property_id_type());
generate_blocks(dynamic_global_props.next_maintenance_time, true);
FC_ASSERT( !(*bitusd.bitasset_data_id)(db).current_feed.settlement_price.is_null() );
}
BOOST_AUTO_TEST_CASE( merge_test )
{
try {
database db;
auto ses = db._undo_db.start_undo_session();
const auto& bal_obj1 = db.create<account_balance_object>( [&]( account_balance_object& obj ){
obj.balance = 42;
});
ses.merge();
auto balance = db.get_balance( account_id_type(), asset_id_type() );
BOOST_CHECK_EQUAL( 42, balance.amount.value );
} catch ( const fc::exception& e )
{
edump( (e.to_detail_string()) );
throw;
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/projection.hpp>
#include <mapnik/utils.hpp>
// proj4
#include <proj_api.h>
namespace mapnik {
#ifdef MAPNIK_THREADSAFE
boost::mutex projection::mutex_;
#endif
projection::projection(std::string params)
: params_(params)
{
init(); //
}
projection::projection(projection const& rhs)
: params_(rhs.params_)
{
init(); //
}
projection& projection::operator=(projection const& rhs)
{
projection tmp(rhs);
swap(tmp);
return *this;
}
bool projection::is_initialized() const
{
return proj_ ? true : false;
}
bool projection::is_geographic() const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
return pj_is_latlong(proj_);
}
std::string const& projection::params() const
{
return params_;
}
void projection::forward(double & x, double &y ) const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
projUV p;
p.u = x * DEG_TO_RAD;
p.v = y * DEG_TO_RAD;
p = pj_fwd(p,proj_);
x = p.u;
y = p.v;
}
void projection::inverse(double & x,double & y) const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
projUV p;
p.u = x;
p.v = y;
p = pj_inv(p,proj_);
x = RAD_TO_DEG * p.u;
y = RAD_TO_DEG * p.v;
}
projection::~projection()
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
if (proj_) pj_free(proj_);
}
void projection::init()
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
proj_=pj_init_plus(params_.c_str());
if (!proj_) throw proj_init_error(params_);
}
void projection::swap (projection& rhs)
{
std::swap(params_,rhs.params_);
init ();
}
}
<commit_msg>convert to degrees if projection is geographic<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/projection.hpp>
#include <mapnik/utils.hpp>
// proj4
#include <proj_api.h>
namespace mapnik {
#ifdef MAPNIK_THREADSAFE
boost::mutex projection::mutex_;
#endif
projection::projection(std::string params)
: params_(params)
{
init(); //
}
projection::projection(projection const& rhs)
: params_(rhs.params_)
{
init(); //
}
projection& projection::operator=(projection const& rhs)
{
projection tmp(rhs);
swap(tmp);
return *this;
}
bool projection::is_initialized() const
{
return proj_ ? true : false;
}
bool projection::is_geographic() const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
return pj_is_latlong(proj_);
}
std::string const& projection::params() const
{
return params_;
}
void projection::forward(double & x, double &y ) const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
projUV p;
p.u = x * DEG_TO_RAD;
p.v = y * DEG_TO_RAD;
p = pj_fwd(p,proj_);
x = p.u;
y = p.v;
if (pj_is_latlong(proj_))
{
x *=RAD_TO_DEG;
y *=RAD_TO_DEG;
}
}
void projection::inverse(double & x,double & y) const
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
if (pj_is_latlong(proj_))
{
x *=DEG_TO_RAD;
y *=DEG_TO_RAD;
}
projUV p;
p.u = x;
p.v = y;
p = pj_inv(p,proj_);
x = RAD_TO_DEG * p.u;
y = RAD_TO_DEG * p.v;
}
projection::~projection()
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
if (proj_) pj_free(proj_);
}
void projection::init()
{
#ifdef MAPNIK_THREADSAFE
mutex::scoped_lock lock(mutex_);
#endif
proj_=pj_init_plus(params_.c_str());
if (!proj_) throw proj_init_error(params_);
}
void projection::swap (projection& rhs)
{
std::swap(params_,rhs.params_);
init ();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "spectregui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "messagemodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "paymentserver.h"
#include "init.h"
#include "ui_interface.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <QTimer>
// Need a global reference for the notifications to find the GUI
static SpectreGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
} else
{
LogPrintf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(200,0,0));
QApplication::instance()->processEvents();
}
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", SpectreGUI::tr("A fatal error occurred. Spectre can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef SPECTRE_QT_TEST
int main(int argc, char *argv[])
{
fHaveGUI = true;
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then spectrecoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Spectre",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("The Spectre Project");
app.setOrganizationDomain("spectre.cash");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Spectre-testnet");
else
app.setApplicationName("Spectre");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
// Under no circumstances should any browser plugins be loaded.
QWebSettings::globalSettings()->setPluginSearchPaths(QStringList());
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, false);
QWebSettings::globalSettings()->setAttribute(QWebSettings::JavaEnabled, false);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
//uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
boost::thread_group threadGroup;
SpectreGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if (AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
paymentServer->setOptionsModel(&optionsModel);
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
MessageModel messageModel(pwalletMain, &walletModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
window.setMessageModel(&messageModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
} else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// spectre: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
window.setMessageModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Qt here
LogPrintf("SpectreCoin shutdown.\n\n");
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
} else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
};
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // SPECTRE_QT_TEST
<commit_msg>Remove plugin search path setting, to preserve compatibility with earlier Qt5WebKit<commit_after>// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "spectregui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "messagemodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "paymentserver.h"
#include "init.h"
#include "ui_interface.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <QTimer>
// Need a global reference for the notifications to find the GUI
static SpectreGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
} else
{
LogPrintf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(200,0,0));
QApplication::instance()->processEvents();
}
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", SpectreGUI::tr("A fatal error occurred. Spectre can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef SPECTRE_QT_TEST
int main(int argc, char *argv[])
{
fHaveGUI = true;
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then spectrecoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Spectre",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("The Spectre Project");
app.setOrganizationDomain("spectre.cash");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Spectre-testnet");
else
app.setApplicationName("Spectre");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
// Under no circumstances should any browser plugins be loaded.
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, false);
QWebSettings::globalSettings()->setAttribute(QWebSettings::JavaEnabled, false);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
//uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
boost::thread_group threadGroup;
SpectreGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if (AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
paymentServer->setOptionsModel(&optionsModel);
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
MessageModel messageModel(pwalletMain, &walletModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
window.setMessageModel(&messageModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
} else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// spectre: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
window.setMessageModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Qt here
LogPrintf("SpectreCoin shutdown.\n\n");
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
} else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
};
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // SPECTRE_QT_TEST
<|endoftext|> |
<commit_before>#include "lexer.h"
#include "parser.h"
#include "binary.h"
#include "constants.h"
#include "semantics.h"
#include "options.h"
#include "trace.h"
#include <iostream>
#include <fstream>
#include <llvm/PassManager.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Support/CommandLine.h>
static std::string ErrStr;
llvm::FunctionPassManager* fpm;
llvm::PassManager* mpm;
llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext());
int verbosity;
bool timetrace;
bool disableMemcpyOpt;
OptLevel optimization;
// Command line option definitions.
static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional, llvm::cl::Required,
llvm::cl::desc("<input file>"));
static llvm::cl::opt<int, true> Verbose("v", llvm::cl::desc("Enable verbose output"),
llvm::cl::location(verbosity));
static llvm::cl::opt<OptLevel, true> OptimizationLevel(llvm::cl::desc("Choose optimization level:"),
llvm::cl::values(
clEnumVal(O0, "No optimizations"),
clEnumVal(O1, "Enable trivial optimizations"),
clEnumVal(O2, "Enable more optimizations"),
clEnumValEnd),
llvm::cl::location(optimization));
static llvm::cl::opt<EmitType> EmitSelection("emit", llvm::cl::desc("Choose output:"),
llvm::cl::values(
clEnumValN(Exe, "exe", "Executable file"),
clEnumValN(LlvmIr, "llvm", "LLVM IR file"),
clEnumValEnd));
static llvm::cl::opt<bool, true> TimetraceEnable("tt", llvm::cl::desc("Enable timetrace"),
llvm::cl::location(timetrace));
static llvm::cl::opt<bool, true> DisableMemCpyGen("no-memcpy",
llvm::cl::desc("Disable use of memcpy for large data structs"),
llvm::cl::location(disableMemcpyOpt));
void DumpModule(llvm::Module* module)
{
module->dump();
}
bool CodeGen(std::vector<ExprAST*> ast)
{
TIME_TRACE();
for(auto a : ast)
{
llvm::Value* v = a->CodeGen();
if (!v)
{
std::cerr << "Sorry, something went wrong here..." << std::endl;
a->dump(std::cerr);
return false;
}
}
return true;
}
void OptimizerInit()
{
fpm = new llvm::FunctionPassManager(theModule);
mpm = new llvm::PassManager();
llvm::InitializeNativeTarget();
if (OptimizationLevel > O0)
{
// Promote allocas to registers.
fpm->add(llvm::createPromoteMemoryToRegisterPass());
// Provide basic AliasAnalysis support for GVN.
fpm->add(llvm::createBasicAliasAnalysisPass());
// Do simple "peephole" optimizations and bit-twiddling optzns.
fpm->add(llvm::createInstructionCombiningPass());
// Reassociate expressions.
fpm->add(llvm::createReassociatePass());
// Eliminate Common SubExpressions.
fpm->add(llvm::createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
fpm->add(llvm::createCFGSimplificationPass());
// Memory copying opts.
fpm->add(llvm::createMemCpyOptPass());
// Merge constants.
mpm->add(llvm::createConstantMergePass());
// dead code removal:
fpm->add(llvm::createDeadCodeEliminationPass());
if (OptimizationLevel > O1)
{
// Inline functions.
mpm->add(llvm::createFunctionInliningPass());
// Thread jumps.
fpm->add(llvm::createJumpThreadingPass());
// Loop strength reduce.
fpm->add(llvm::createLoopStrengthReducePass());
}
}
}
static int Compile(const std::string& filename)
{
TIME_TRACE();
std::vector<ExprAST*> ast;
Lexer lex(filename);
if (!lex.Good())
{
return 1;
}
Parser p(lex);
OptimizerInit();
ast = p.Parse();
int e = p.GetErrors();
if (e > 0)
{
std::cerr << "Errors in parsing: " << e << ". Exiting..." << std::endl;
return 1;
}
Semantics sema;
sema.Analyse(ast);
e = sema.GetErrors();
if (e > 0)
{
std::cerr << "Errors in analysis: " << e << ". Exiting..." << std::endl;
return 1;
}
if (!CodeGen(ast))
{
std::cerr << "Code generation failed..." << std::endl;
return 1;
}
mpm->run(*theModule);
if (verbosity)
{
DumpModule(theModule);
}
CreateBinary(theModule, filename, EmitSelection);
return 0;
}
int main(int argc, char** argv)
{
llvm::cl::ParseCommandLineOptions(argc, argv);
int res = Compile(InputFilename);
return res;
}
<commit_msg>Fix minor tidy up before starting range checking<commit_after>#include "lexer.h"
#include "parser.h"
#include "binary.h"
#include "constants.h"
#include "semantics.h"
#include "options.h"
#include "trace.h"
#include <iostream>
#include <fstream>
#include <llvm/PassManager.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Support/CommandLine.h>
llvm::FunctionPassManager* fpm;
llvm::PassManager* mpm;
llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext());
int verbosity;
bool timetrace;
bool disableMemcpyOpt;
OptLevel optimization;
// Command line option definitions.
static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional, llvm::cl::Required,
llvm::cl::desc("<input file>"));
static llvm::cl::opt<int, true> Verbose("v", llvm::cl::desc("Enable verbose output"),
llvm::cl::location(verbosity));
static llvm::cl::opt<OptLevel, true> OptimizationLevel(llvm::cl::desc("Choose optimization level:"),
llvm::cl::values(
clEnumVal(O0, "No optimizations"),
clEnumVal(O1, "Enable trivial optimizations"),
clEnumVal(O2, "Enable more optimizations"),
clEnumValEnd),
llvm::cl::location(optimization));
static llvm::cl::opt<EmitType> EmitSelection("emit", llvm::cl::desc("Choose output:"),
llvm::cl::values(
clEnumValN(Exe, "exe", "Executable file"),
clEnumValN(LlvmIr, "llvm", "LLVM IR file"),
clEnumValEnd));
static llvm::cl::opt<bool, true> TimetraceEnable("tt", llvm::cl::desc("Enable timetrace"),
llvm::cl::location(timetrace));
static llvm::cl::opt<bool, true> DisableMemCpyGen("no-memcpy",
llvm::cl::desc("Disable use of memcpy for large data structs"),
llvm::cl::location(disableMemcpyOpt));
void DumpModule(llvm::Module* module)
{
module->dump();
}
bool CodeGen(std::vector<ExprAST*> ast)
{
TIME_TRACE();
for(auto a : ast)
{
llvm::Value* v = a->CodeGen();
if (!v)
{
std::cerr << "Sorry, something went wrong here..." << std::endl;
a->dump(std::cerr);
return false;
}
}
return true;
}
void OptimizerInit()
{
fpm = new llvm::FunctionPassManager(theModule);
mpm = new llvm::PassManager();
llvm::InitializeNativeTarget();
if (OptimizationLevel > O0)
{
// Promote allocas to registers.
fpm->add(llvm::createPromoteMemoryToRegisterPass());
// Provide basic AliasAnalysis support for GVN.
fpm->add(llvm::createBasicAliasAnalysisPass());
// Do simple "peephole" optimizations and bit-twiddling optzns.
fpm->add(llvm::createInstructionCombiningPass());
// Reassociate expressions.
fpm->add(llvm::createReassociatePass());
// Eliminate Common SubExpressions.
fpm->add(llvm::createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
fpm->add(llvm::createCFGSimplificationPass());
// Memory copying opts.
fpm->add(llvm::createMemCpyOptPass());
// Merge constants.
mpm->add(llvm::createConstantMergePass());
// dead code removal:
fpm->add(llvm::createDeadCodeEliminationPass());
if (OptimizationLevel > O1)
{
// Inline functions.
mpm->add(llvm::createFunctionInliningPass());
// Thread jumps.
fpm->add(llvm::createJumpThreadingPass());
// Loop strength reduce.
fpm->add(llvm::createLoopStrengthReducePass());
}
}
}
static int Compile(const std::string& filename)
{
TIME_TRACE();
std::vector<ExprAST*> ast;
Lexer lex(filename);
if (!lex.Good())
{
return 1;
}
Parser p(lex);
OptimizerInit();
ast = p.Parse();
int e = p.GetErrors();
if (e > 0)
{
std::cerr << "Errors in parsing: " << e << ". Exiting..." << std::endl;
return 1;
}
Semantics sema;
sema.Analyse(ast);
e = sema.GetErrors();
if (e > 0)
{
std::cerr << "Errors in analysis: " << e << ". Exiting..." << std::endl;
return 1;
}
if (!CodeGen(ast))
{
std::cerr << "Code generation failed..." << std::endl;
return 1;
}
mpm->run(*theModule);
if (verbosity)
{
DumpModule(theModule);
}
CreateBinary(theModule, filename, EmitSelection);
return 0;
}
int main(int argc, char** argv)
{
llvm::cl::ParseCommandLineOptions(argc, argv);
int res = Compile(InputFilename);
return res;
}
<|endoftext|> |
<commit_before>#include "kwm.h"
extern std::vector<spaces_info> SpacesLst;
extern std::vector<screen_info> DisplayLst;
extern std::vector<window_info> WindowLst;
extern std::vector<screen_layout> ScreenLayoutLst;
extern std::vector<window_layout> LayoutLst;
extern uint32_t MaxDisplayCount;
extern ProcessSerialNumber FocusedPSN;
extern AXUIElementRef FocusedWindowRef;
extern window_info FocusedWindow;
void ApplyLayoutForDisplay(int ScreenIndex)
{
RefreshActiveSpacesInfo();
DetectWindowBelowCursor();
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].NextLayoutIndex;
SpacesLst[SpaceIndex].ActiveLayoutIndex = ActiveLayoutIndex;
if(ActiveLayoutIndex + 1 < LayoutMaster->NumberOfLayouts)
SpacesLst[SpaceIndex].NextLayoutIndex = ActiveLayoutIndex + 1;
else
SpacesLst[SpaceIndex].NextLayoutIndex = 0;
for(int WindowIndex = 0; WindowIndex < ScreenWindowLst.size(); ++WindowIndex)
{
window_info *Window = ScreenWindowLst[WindowIndex];
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
if(WindowIndex < LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size())
{
window_layout *Layout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[WindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[WindowIndex] = Window->WID;
SetWindowDimensions(WindowRef, Window, Layout->X, Layout->Y, Layout->Width, Layout->Height);
}
if(!WindowsAreEqual(&FocusedWindow, Window))
CFRelease(WindowRef);
}
}
DetectWindowBelowCursor();
}
void CycleFocusedWindowLayout(int ScreenIndex, int Shift)
{
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutTiles = LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size();
int FocusedWindowIndex = GetLayoutIndexOfWindow(&FocusedWindow);
int SwapWithWindowIndex = FocusedWindowIndex + Shift;
if(SwapWithWindowIndex < 0 || SwapWithWindowIndex >= MaxLayoutTiles)
return;
window_info *Window = NULL;
for(int WindowIndex = 0; WindowIndex < ScreenWindowLst.size(); ++WindowIndex)
{
Window = ScreenWindowLst[WindowIndex];
if(GetLayoutIndexOfWindow(Window) == SwapWithWindowIndex)
break;
}
if (Window == NULL)
return;
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
window_layout *FocusedWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[FocusedWindowIndex];
window_layout *SwapWithWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[SwapWithWindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[SwapWithWindowIndex] = FocusedWindow.WID;
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[FocusedWindowIndex] = Window->WID;
SetWindowDimensions(WindowRef,
Window,
FocusedWindowLayout->X,
FocusedWindowLayout->Y,
FocusedWindowLayout->Width,
FocusedWindowLayout->Height);
SetWindowDimensions(FocusedWindowRef,
&FocusedWindow,
SwapWithWindowLayout->X,
SwapWithWindowLayout->Y,
SwapWithWindowLayout->Width,
SwapWithWindowLayout->Height);
CFRelease(WindowRef);
}
}
void CycleWindowInsideLayout(int ScreenIndex)
{
DetectWindowBelowCursor();
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutTiles = LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size();
if(ScreenWindowLst.size() <= MaxLayoutTiles)
return;
int FocusedWindowIndex = GetLayoutIndexOfWindow(&FocusedWindow);
if(FocusedWindowIndex == -1)
return;
bool Found = false;
window_info *Window = NULL;
for(int WindowIndex = ScreenWindowLst.size()-1; WindowIndex >= 0; --WindowIndex)
{
Window = ScreenWindowLst[WindowIndex];
if(GetLayoutIndexOfWindow(Window) == -1)
{
Found = true;
break;
}
}
if(!Found)
return;
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
window_layout *FocusedWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[FocusedWindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[FocusedWindowIndex] = Window->WID;
SetWindowDimensions(WindowRef,
Window,
FocusedWindowLayout->X,
FocusedWindowLayout->Y,
FocusedWindowLayout->Width,
FocusedWindowLayout->Height);
ProcessSerialNumber NewPSN;
GetProcessForPID(Window->PID, &NewPSN);
AXUIElementSetAttributeValue(WindowRef, kAXMainAttribute, kCFBooleanTrue);
AXUIElementSetAttributeValue(WindowRef, kAXFocusedAttribute, kCFBooleanTrue);
AXUIElementPerformAction (WindowRef, kAXRaiseAction);
SetFrontProcessWithOptions(&NewPSN, kSetFrontProcessFrontWindowOnly);
if(FocusedWindowRef != NULL)
CFRelease(FocusedWindowRef);
FocusedWindowRef = WindowRef;
FocusedWindow = *Window;
FocusedPSN = NewPSN;
}
}
int GetLayoutIndexOfWindow(window_info *Window)
{
int ScreenID = GetDisplayOfWindow(Window)->ID;
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return -1;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutSize = ScreenLayoutLst[ScreenID].Layouts[ActiveLayoutIndex].Layouts.size();
for(int LayoutIndex = 0; LayoutIndex < MaxLayoutSize; ++LayoutIndex)
{
if(Window->WID == ScreenLayoutLst[ScreenID].Layouts[ActiveLayoutIndex].TileWID[LayoutIndex])
return LayoutIndex;
}
return -1;
}
bool WindowHasLayout(window_info *Window, window_layout *Layout)
{
if((Window->X >= Layout->X - 15 && Window->X <= Layout->X + 15) &&
(Window->Y >= Layout->Y - 15 && Window->Y <= Layout->Y + 15 ) &&
(Window->Width >= Layout->Width - 15 && Window->Width <= Layout->Width + 15) &&
(Window->Height >= Layout->Height - 15 && Window->Height <= Layout->Height + 15))
return true;
return false;
}
void SetWindowLayoutValues(window_layout *Layout, int X, int Y, int Width, int Height)
{
Layout->X = X;
Layout->Y = Y;
Layout->Width = Width;
Layout->Height = Height;
}
window_layout GetWindowLayoutForScreen(int ScreenIndex, const std::string &Name)
{
window_layout Layout;
Layout.Name = "invalid";
screen_info *Screen = &DisplayLst[ScreenIndex];
if(Screen)
{
for(int LayoutIndex = 0; LayoutIndex < LayoutLst.size(); ++LayoutIndex)
{
if(LayoutLst[LayoutIndex].Name == Name)
{
Layout = LayoutLst[LayoutIndex];
break;
}
}
if(Name == "fullscreen")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
(Screen->Width - (Layout.GapVertical * 2)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "left vertical split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "right vertical split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "upper horizontal split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
(Screen->Width - (Layout.GapVertical * 2)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower horizontal split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
(Screen->Width - (Layout.GapVertical * 2)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "upper left split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower left split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "upper right split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower right split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
}
return Layout;
}
void InitWindowLayouts()
{
window_layout ScreenVerticalSplit;
ScreenVerticalSplit.GapX = 30;
ScreenVerticalSplit.GapY = 40;
ScreenVerticalSplit.GapVertical = 30;
ScreenVerticalSplit.GapHorizontal = 30;
ScreenVerticalSplit.Name = "fullscreen";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "left vertical split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "right vertical split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper horizontal split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower horizontal split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper left split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower left split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper right split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower right split";
LayoutLst.push_back(ScreenVerticalSplit);
// Screen Layouts
for(int ScreenIndex = 0; ScreenIndex < MaxDisplayCount; ++ScreenIndex)
{
screen_layout LayoutMaster;
window_group_layout LayoutTallLeft;
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "left vertical split"));
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper right split"));
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower right split"));
LayoutTallLeft.TileWID = std::vector<int>(3, 0);
LayoutMaster.Layouts.push_back(LayoutTallLeft);
window_group_layout LayoutTallRight;
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper left split"));
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower left split"));
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "right vertical split"));
LayoutTallRight.TileWID = std::vector<int>(3, 0);
LayoutMaster.Layouts.push_back(LayoutTallRight);
window_group_layout LayoutVerticalSplit;
LayoutVerticalSplit.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "left vertical split"));
LayoutVerticalSplit.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "right vertical split"));
LayoutVerticalSplit.TileWID = std::vector<int>(2, 0);;
LayoutMaster.Layouts.push_back(LayoutVerticalSplit);
window_group_layout LayoutQuarters;
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper left split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower left split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper right split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower right split"));
LayoutQuarters.TileWID = std::vector<int>(4, 0);
LayoutMaster.Layouts.push_back(LayoutQuarters);
window_group_layout LayoutFullscreen;
LayoutFullscreen.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "fullscreen"));
LayoutFullscreen.TileWID = std::vector<int>(1, 0);
LayoutMaster.Layouts.push_back(LayoutFullscreen);
LayoutMaster.NumberOfLayouts = LayoutMaster.Layouts.size();;
ScreenLayoutLst.push_back(LayoutMaster);
}
}
<commit_msg>WindowHasLayout removed, added function ApplyLayoutForWindow<commit_after>#include "kwm.h"
extern std::vector<spaces_info> SpacesLst;
extern std::vector<screen_info> DisplayLst;
extern std::vector<window_info> WindowLst;
extern std::vector<screen_layout> ScreenLayoutLst;
extern std::vector<window_layout> LayoutLst;
extern uint32_t MaxDisplayCount;
extern ProcessSerialNumber FocusedPSN;
extern AXUIElementRef FocusedWindowRef;
extern window_info FocusedWindow;
void ApplyLayoutForDisplay(int ScreenIndex)
{
RefreshActiveSpacesInfo();
DetectWindowBelowCursor();
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].NextLayoutIndex;
SpacesLst[SpaceIndex].ActiveLayoutIndex = ActiveLayoutIndex;
if(ActiveLayoutIndex + 1 < LayoutMaster->NumberOfLayouts)
SpacesLst[SpaceIndex].NextLayoutIndex = ActiveLayoutIndex + 1;
else
SpacesLst[SpaceIndex].NextLayoutIndex = 0;
for(int WindowIndex = 0; WindowIndex < ScreenWindowLst.size(); ++WindowIndex)
{
window_info *Window = ScreenWindowLst[WindowIndex];
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
if(WindowIndex < LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size())
{
window_layout *Layout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[WindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[WindowIndex] = Window->WID;
SetWindowDimensions(WindowRef, Window, Layout->X, Layout->Y, Layout->Width, Layout->Height);
}
if(!WindowsAreEqual(&FocusedWindow, Window))
CFRelease(WindowRef);
}
}
DetectWindowBelowCursor();
}
void ApplyLayoutForWindow(AXUIElementRef WindowRef, window_info *Window, window_layout *Layout)
{
SetWindowDimensions(WindowRef, Window, Layout->X, Layout->Y, Layout->Width, Layout->Height);
}
void CycleFocusedWindowLayout(int ScreenIndex, int Shift)
{
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutTiles = LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size();
int FocusedWindowIndex = GetLayoutIndexOfWindow(&FocusedWindow);
int SwapWithWindowIndex = FocusedWindowIndex + Shift;
if(SwapWithWindowIndex < 0 || SwapWithWindowIndex >= MaxLayoutTiles)
return;
window_info *Window = NULL;
for(int WindowIndex = 0; WindowIndex < ScreenWindowLst.size(); ++WindowIndex)
{
Window = ScreenWindowLst[WindowIndex];
if(GetLayoutIndexOfWindow(Window) == SwapWithWindowIndex)
break;
}
if (Window == NULL)
return;
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
window_layout *FocusedWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[FocusedWindowIndex];
window_layout *SwapWithWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[SwapWithWindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[SwapWithWindowIndex] = FocusedWindow.WID;
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[FocusedWindowIndex] = Window->WID;
ApplyLayoutForWindow(WindowRef, Window, FocusedWindowLayout);
ApplyLayoutForWindow(FocusedWindowRef, &FocusedWindow, SwapWithWindowLayout);
CFRelease(WindowRef);
}
}
void CycleWindowInsideLayout(int ScreenIndex)
{
DetectWindowBelowCursor();
std::vector<window_info*> ScreenWindowLst = GetAllWindowsOnDisplay(ScreenIndex);
screen_layout *LayoutMaster = &ScreenLayoutLst[ScreenIndex];
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutTiles = LayoutMaster->Layouts[ActiveLayoutIndex].Layouts.size();
if(ScreenWindowLst.size() <= MaxLayoutTiles)
return;
int FocusedWindowIndex = GetLayoutIndexOfWindow(&FocusedWindow);
if(FocusedWindowIndex == -1)
return;
bool Found = false;
window_info *Window = NULL;
for(int WindowIndex = ScreenWindowLst.size()-1; WindowIndex >= 0; --WindowIndex)
{
Window = ScreenWindowLst[WindowIndex];
if(GetLayoutIndexOfWindow(Window) == -1)
{
Found = true;
break;
}
}
if(!Found)
return;
AXUIElementRef WindowRef;
if(GetWindowRef(Window, &WindowRef))
{
window_layout *FocusedWindowLayout = &LayoutMaster->Layouts[ActiveLayoutIndex].Layouts[FocusedWindowIndex];
LayoutMaster->Layouts[ActiveLayoutIndex].TileWID[FocusedWindowIndex] = Window->WID;
ApplyLayoutForWindow(WindowRef, Window, FocusedWindowLayout);
ProcessSerialNumber NewPSN;
GetProcessForPID(Window->PID, &NewPSN);
AXUIElementSetAttributeValue(WindowRef, kAXMainAttribute, kCFBooleanTrue);
AXUIElementSetAttributeValue(WindowRef, kAXFocusedAttribute, kCFBooleanTrue);
AXUIElementPerformAction (WindowRef, kAXRaiseAction);
SetFrontProcessWithOptions(&NewPSN, kSetFrontProcessFrontWindowOnly);
if(FocusedWindowRef != NULL)
CFRelease(FocusedWindowRef);
FocusedWindowRef = WindowRef;
FocusedWindow = *Window;
FocusedPSN = NewPSN;
}
}
int GetLayoutIndexOfWindow(window_info *Window)
{
int ScreenID = GetDisplayOfWindow(Window)->ID;
int SpaceIndex = GetSpaceOfWindow(&FocusedWindow);
if(SpaceIndex == -1)
return -1;
int ActiveLayoutIndex = SpacesLst[SpaceIndex].ActiveLayoutIndex;
int MaxLayoutSize = ScreenLayoutLst[ScreenID].Layouts[ActiveLayoutIndex].Layouts.size();
for(int LayoutIndex = 0; LayoutIndex < MaxLayoutSize; ++LayoutIndex)
{
if(Window->WID == ScreenLayoutLst[ScreenID].Layouts[ActiveLayoutIndex].TileWID[LayoutIndex])
return LayoutIndex;
}
return -1;
}
void SetWindowLayoutValues(window_layout *Layout, int X, int Y, int Width, int Height)
{
Layout->X = X;
Layout->Y = Y;
Layout->Width = Width;
Layout->Height = Height;
}
window_layout GetWindowLayoutForScreen(int ScreenIndex, const std::string &Name)
{
window_layout Layout;
Layout.Name = "invalid";
screen_info *Screen = &DisplayLst[ScreenIndex];
if(Screen)
{
for(int LayoutIndex = 0; LayoutIndex < LayoutLst.size(); ++LayoutIndex)
{
if(LayoutLst[LayoutIndex].Name == Name)
{
Layout = LayoutLst[LayoutIndex];
break;
}
}
if(Name == "fullscreen")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
(Screen->Width - (Layout.GapVertical * 2)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "left vertical split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "right vertical split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
(Screen->Height - (Layout.GapY * 1.5f)));
else if(Name == "upper horizontal split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
(Screen->Width - (Layout.GapVertical * 2)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower horizontal split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
(Screen->Width - (Layout.GapVertical * 2)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "upper left split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower left split")
SetWindowLayoutValues(&Layout,
Screen->X + Layout.GapX,
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "upper right split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + Layout.GapY,
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
else if(Name == "lower right split")
SetWindowLayoutValues(&Layout,
Screen->X + ((Screen->Width / 2) + (Layout.GapVertical * 0.5f)),
Screen->Y + ((Screen->Height / 2) + (Layout.GapHorizontal * 0.5f) + (Layout.GapY / 8)),
((Screen->Width / 2) - (Layout.GapVertical * 1.5f)),
((Screen->Height / 2) - (Layout.GapHorizontal * 1.0f)));
}
return Layout;
}
void InitWindowLayouts()
{
window_layout ScreenVerticalSplit;
ScreenVerticalSplit.GapX = 30;
ScreenVerticalSplit.GapY = 40;
ScreenVerticalSplit.GapVertical = 30;
ScreenVerticalSplit.GapHorizontal = 30;
ScreenVerticalSplit.Name = "fullscreen";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "left vertical split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "right vertical split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper horizontal split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower horizontal split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper left split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower left split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "upper right split";
LayoutLst.push_back(ScreenVerticalSplit);
ScreenVerticalSplit.Name = "lower right split";
LayoutLst.push_back(ScreenVerticalSplit);
// Screen Layouts
for(int ScreenIndex = 0; ScreenIndex < MaxDisplayCount; ++ScreenIndex)
{
screen_layout LayoutMaster;
window_group_layout LayoutTallLeft;
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "left vertical split"));
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper right split"));
LayoutTallLeft.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower right split"));
LayoutTallLeft.TileWID = std::vector<int>(3, 0);
LayoutMaster.Layouts.push_back(LayoutTallLeft);
window_group_layout LayoutTallRight;
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper left split"));
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower left split"));
LayoutTallRight.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "right vertical split"));
LayoutTallRight.TileWID = std::vector<int>(3, 0);
LayoutMaster.Layouts.push_back(LayoutTallRight);
window_group_layout LayoutVerticalSplit;
LayoutVerticalSplit.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "left vertical split"));
LayoutVerticalSplit.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "right vertical split"));
LayoutVerticalSplit.TileWID = std::vector<int>(2, 0);;
LayoutMaster.Layouts.push_back(LayoutVerticalSplit);
window_group_layout LayoutQuarters;
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper left split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower left split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "upper right split"));
LayoutQuarters.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "lower right split"));
LayoutQuarters.TileWID = std::vector<int>(4, 0);
LayoutMaster.Layouts.push_back(LayoutQuarters);
window_group_layout LayoutFullscreen;
LayoutFullscreen.Layouts.push_back(GetWindowLayoutForScreen(ScreenIndex, "fullscreen"));
LayoutFullscreen.TileWID = std::vector<int>(1, 0);
LayoutMaster.Layouts.push_back(LayoutFullscreen);
LayoutMaster.NumberOfLayouts = LayoutMaster.Layouts.size();;
ScreenLayoutLst.push_back(LayoutMaster);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Rémi Bazin <bazin.remi@gmail.com>
* All rights reserved.
* See LICENSE for licensing details.
*/
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <qglobal.h>
#include "simplifier.h"
#include "qsimplefuse.h"
lString toLString(const char *str)
{
lString result;
result.str_value = str;
result.str_len = strlen(str);
return result;
}
#define dispLog(...) fprintf(stderr, __VA_ARGS__);
int s_getattr(const char *path, struct stat *statbuf)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
sAttr result;
int ret_value;
if ((ret_value = (QSimpleFuse::_instance)->sGetAttr(lPath, result)) < 0)
return ret_value;
PersistentData *data = PERSDATA;
*statbuf = data->def_stat;
statbuf->st_mode = result.mst_mode;
statbuf->st_nlink = result.mst_nlink;
statbuf->st_size = (result.mst_mode & 0x4000) ? 0x1000 : result.mst_size;
statbuf->st_blocks = (statbuf->st_size + 0x01FF) >> 9; // really useful ???
statbuf->st_atim.tv_sec = result.mst_atime;
statbuf->st_mtim.tv_sec = result.mst_mtime;
statbuf->st_ctim.tv_sec = result.mst_mtime;
return 0;
}
int s_mknod(const char *path, mode_t mode, dev_t dev)
{
Q_UNUSED(dev);
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x8000)
{
dispLog("Warning: s_mknod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
return (QSimpleFuse::_instance)->sMkFile(lPath, mode);
}
int s_mkdir(const char *path, mode_t mode)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x4000)
{
dispLog("Warning: s_mkdir on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
return (QSimpleFuse::_instance)->sMkFile(lPath, mode);
}
int s_unlink(const char *path)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sRmFile(lPath, false);
}
int s_rmdir(const char *path)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sRmFile(lPath, true);
}
int s_rename(const char *path, const char *newpath)
{
lString lPathFrom = toLString(path);
if (lPathFrom.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
lString lPathTo = toLString(newpath);
if (lPathTo.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sMvFile(lPathFrom, lPathTo);
}
int s_link(const char *path, const char *newpath)
{
lString lPathFrom = toLString(newpath);
if (lPathFrom.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
lString lPathTo = toLString(path);
if (lPathTo.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sLink(lPathFrom, lPathTo);
}
int s_chmod(const char *path, mode_t mode)
{
if (mode & 0xE00)
{
dispLog("Warning: s_chmod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sChMod(lPath, mode);
}
int s_chown(const char *path, uid_t uid, gid_t gid)
{
dispLog("Warning: Entered s_chown with \"%s\" --> %d:%d\n", path, uid, gid);
return -EPERM;
}
int s_truncate(const char *path, off_t newsize)
{
if (newsize < 0)
return -EINVAL;
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sTruncate(lPath, newsize);
}
int s_utime(const char *path, utimbuf *ubuf)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
time_t mst_atime, mst_mtime;
if (ubuf)
{
mst_atime = ubuf->actime;
mst_mtime = ubuf->modtime;
} else {
time(&mst_atime);
mst_mtime = mst_atime;
}
return (QSimpleFuse::_instance)->sUTime(lPath, mst_atime, mst_mtime);
}
int s_open(const char *path, fuse_file_info *fi)
{
if (fi->flags & (O_ASYNC | O_DIRECTORY | O_TMPFILE | O_CREAT | O_EXCL | O_TRUNC | O_PATH))
{
dispLog("Warning: s_open on \"%s\" with flags 0x%08x\n", path, fi->flags);
return -EOPNOTSUPP;
}
// O_NONBLOCK and O_NDELAY simply ignored.
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
int fhv = 0;
int ret_value = (QSimpleFuse::_instance)->sOpen(lPath, fi->flags, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_read(const char *path, char *buf, size_t size, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
if (size > INT_MAX)
return -EINVAL;
return (QSimpleFuse::_instance)->sRead(fi->fh, buf, (int) size, offset);
}
int s_write(const char *path, const char *buf, size_t size, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
if (size > INT_MAX)
return -EINVAL;
return (QSimpleFuse::_instance)->sWrite(fi->fh, buf, (int) size, offset);
}
int s_flush(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
// I did not really get the difference with a normal sync, but let's do the same action.
return (QSimpleFuse::_instance)->sSync(fi->fh);
}
int s_release(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sClose(fi->fh);
}
int s_fsync(const char *path, int datasync, fuse_file_info *fi)
{
Q_UNUSED(path);
// We do not care about meta data being flushed here.
Q_UNUSED(datasync);
return (QSimpleFuse::_instance)->sSync(fi->fh);
}
int s_opendir(const char *path, fuse_file_info *fi)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
int fhv = 0;
int ret_value = (QSimpleFuse::_instance)->sOpenDir(lPath, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset,
fuse_file_info *fi)
{
Q_UNUSED(path);
Q_UNUSED(offset);
int ret_value;
char *name;
while (((ret_value = (QSimpleFuse::_instance)->sReadDir(fi->fh, name)) == 0) && name)
{
if (filler(buf, name, NULL, 0) != 0)
{
dispLog("Warning: readdir filler: buffer full\n");
return -ENOMEM;
}
}
return ret_value;
}
int s_releasedir(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sCloseDir(fi->fh);
}
int s_fsyncdir(const char *path, int datasync, fuse_file_info *fi)
{
Q_UNUSED(path);
Q_UNUSED(datasync);
Q_UNUSED(fi);
return 0; // Directories should always be directly synchronized.
}
void *s_init(fuse_conn_info *conn)
{
Q_UNUSED(conn);
(QSimpleFuse::_instance)->sInit();
return PERSDATA;
}
void s_destroy(void *userdata)
{
Q_UNUSED(userdata);
(QSimpleFuse::_instance)->sDestroy();
}
int s_access(const char *path, int mask)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sAccess(lPath, mask);
}
int s_create(const char *path, mode_t mode, fuse_file_info *fi)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x8000)
{
dispLog("Warning: s_mknod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
int ret_value = (QSimpleFuse::_instance)->sMkFile(lPath, (mode & 0x1FF) | 0x8000), fhv = 0;
if (ret_value == -EEXIST)
{
ret_value = (QSimpleFuse::_instance)->sOpen(lPath, O_WRONLY | O_TRUNC, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
if (ret_value < 0)
return ret_value;
ret_value = (QSimpleFuse::_instance)->sOpen(lPath, O_WRONLY, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_ftruncate(const char *path, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sFTruncate(fi->fh, offset);
}
int s_fgetattr(const char *path, struct stat *statbuf, fuse_file_info *fi)
{
Q_UNUSED(path);
sAttr result;
int ret_value;
if ((ret_value = (QSimpleFuse::_instance)->sFGetAttr(fi->fh, result)) < 0)
return ret_value;
PersistentData *data = PERSDATA;
*statbuf = data->def_stat;
statbuf->st_mode = result.mst_mode;
statbuf->st_nlink = result.mst_nlink;
statbuf->st_size = (result.mst_mode & 0x4000) ? 0x1000 : result.mst_size;
statbuf->st_blocks = (statbuf->st_size + 0x01FF) >> 9; // really useful ???
statbuf->st_atim.tv_sec = result.mst_atime;
statbuf->st_mtim.tv_sec = result.mst_mtime;
statbuf->st_ctim.tv_sec = result.mst_mtime;
return 0;
}
fuse_operations s_oper;
void makeSimplifiedFuseOperations()
{
memset(&s_oper, 0, sizeof(s_oper));
s_oper.getattr = s_getattr;
s_oper.mknod = s_mknod;
s_oper.mkdir = s_mkdir;
s_oper.unlink = s_unlink;
s_oper.rmdir = s_rmdir;
s_oper.rename = s_rename;
s_oper.link = s_link;
s_oper.chmod = s_chmod;
s_oper.chown = s_chown;
s_oper.truncate = s_truncate;
s_oper.utime = s_utime;
s_oper.open = s_open;
s_oper.read = s_read;
s_oper.write = s_write;
s_oper.flush = s_flush;
s_oper.release = s_release;
s_oper.fsync = s_fsync;
s_oper.opendir = s_opendir;
s_oper.readdir = s_readdir;
s_oper.releasedir = s_releasedir;
s_oper.fsyncdir = s_fsyncdir;
s_oper.init = s_init;
s_oper.destroy = s_destroy;
s_oper.access = s_access;
s_oper.create = s_create;
s_oper.ftruncate = s_ftruncate;
s_oper.fgetattr = s_fgetattr;
}
fuse_operations *getSimplifiedFuseOperations()
{
return &s_oper;
}
<commit_msg>Minimal log in release versions.<commit_after>/*
* Copyright (c) 2015, Rémi Bazin <bazin.remi@gmail.com>
* All rights reserved.
* See LICENSE for licensing details.
*/
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <qglobal.h>
#include "simplifier.h"
#include "qsimplefuse.h"
lString toLString(const char *str)
{
lString result;
result.str_value = str;
result.str_len = strlen(str);
return result;
}
#ifndef QT_NO_DEBUG
#define dispLog(...) fprintf(stderr, __VA_ARGS__);
#else
#define dispLog(...) /* NOP */
#endif
int s_getattr(const char *path, struct stat *statbuf)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
sAttr result;
int ret_value;
if ((ret_value = (QSimpleFuse::_instance)->sGetAttr(lPath, result)) < 0)
return ret_value;
PersistentData *data = PERSDATA;
*statbuf = data->def_stat;
statbuf->st_mode = result.mst_mode;
statbuf->st_nlink = result.mst_nlink;
statbuf->st_size = (result.mst_mode & 0x4000) ? 0x1000 : result.mst_size;
statbuf->st_blocks = (statbuf->st_size + 0x01FF) >> 9; // really useful ???
statbuf->st_atim.tv_sec = result.mst_atime;
statbuf->st_mtim.tv_sec = result.mst_mtime;
statbuf->st_ctim.tv_sec = result.mst_mtime;
return 0;
}
int s_mknod(const char *path, mode_t mode, dev_t dev)
{
Q_UNUSED(dev);
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x8000)
{
dispLog("Warning: s_mknod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
return (QSimpleFuse::_instance)->sMkFile(lPath, mode);
}
int s_mkdir(const char *path, mode_t mode)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x4000)
{
dispLog("Warning: s_mkdir on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
return (QSimpleFuse::_instance)->sMkFile(lPath, mode);
}
int s_unlink(const char *path)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sRmFile(lPath, false);
}
int s_rmdir(const char *path)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sRmFile(lPath, true);
}
int s_rename(const char *path, const char *newpath)
{
lString lPathFrom = toLString(path);
if (lPathFrom.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
lString lPathTo = toLString(newpath);
if (lPathTo.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sMvFile(lPathFrom, lPathTo);
}
int s_link(const char *path, const char *newpath)
{
lString lPathFrom = toLString(newpath);
if (lPathFrom.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
lString lPathTo = toLString(path);
if (lPathTo.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sLink(lPathFrom, lPathTo);
}
int s_chmod(const char *path, mode_t mode)
{
if (mode & 0xE00)
{
dispLog("Warning: s_chmod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sChMod(lPath, mode);
}
int s_chown(const char *path, uid_t uid, gid_t gid)
{
dispLog("Warning: Entered s_chown with \"%s\" --> %d:%d\n", path, uid, gid);
return -EPERM;
}
int s_truncate(const char *path, off_t newsize)
{
if (newsize < 0)
return -EINVAL;
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sTruncate(lPath, newsize);
}
int s_utime(const char *path, utimbuf *ubuf)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
time_t mst_atime, mst_mtime;
if (ubuf)
{
mst_atime = ubuf->actime;
mst_mtime = ubuf->modtime;
} else {
time(&mst_atime);
mst_mtime = mst_atime;
}
return (QSimpleFuse::_instance)->sUTime(lPath, mst_atime, mst_mtime);
}
int s_open(const char *path, fuse_file_info *fi)
{
if (fi->flags & (O_ASYNC | O_DIRECTORY | O_TMPFILE | O_CREAT | O_EXCL | O_TRUNC | O_PATH))
{
dispLog("Warning: s_open on \"%s\" with flags 0x%08x\n", path, fi->flags);
return -EOPNOTSUPP;
}
// O_NONBLOCK and O_NDELAY simply ignored.
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
int fhv = 0;
int ret_value = (QSimpleFuse::_instance)->sOpen(lPath, fi->flags, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_read(const char *path, char *buf, size_t size, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
if (size > INT_MAX)
return -EINVAL;
return (QSimpleFuse::_instance)->sRead(fi->fh, buf, (int) size, offset);
}
int s_write(const char *path, const char *buf, size_t size, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
if (size > INT_MAX)
return -EINVAL;
return (QSimpleFuse::_instance)->sWrite(fi->fh, buf, (int) size, offset);
}
int s_flush(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
// I did not really get the difference with a normal sync, but let's do the same action.
return (QSimpleFuse::_instance)->sSync(fi->fh);
}
int s_release(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sClose(fi->fh);
}
int s_fsync(const char *path, int datasync, fuse_file_info *fi)
{
Q_UNUSED(path);
// We do not care about meta data being flushed here.
Q_UNUSED(datasync);
return (QSimpleFuse::_instance)->sSync(fi->fh);
}
int s_opendir(const char *path, fuse_file_info *fi)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
int fhv = 0;
int ret_value = (QSimpleFuse::_instance)->sOpenDir(lPath, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset,
fuse_file_info *fi)
{
Q_UNUSED(path);
Q_UNUSED(offset);
int ret_value;
char *name;
while (((ret_value = (QSimpleFuse::_instance)->sReadDir(fi->fh, name)) == 0) && name)
{
if (filler(buf, name, NULL, 0) != 0)
{
dispLog("Warning: readdir filler: buffer full\n");
return -ENOMEM;
}
}
return ret_value;
}
int s_releasedir(const char *path, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sCloseDir(fi->fh);
}
int s_fsyncdir(const char *path, int datasync, fuse_file_info *fi)
{
Q_UNUSED(path);
Q_UNUSED(datasync);
Q_UNUSED(fi);
return 0; // Directories should always be directly synchronized.
}
void *s_init(fuse_conn_info *conn)
{
Q_UNUSED(conn);
(QSimpleFuse::_instance)->sInit();
return PERSDATA;
}
void s_destroy(void *userdata)
{
Q_UNUSED(userdata);
(QSimpleFuse::_instance)->sDestroy();
}
int s_access(const char *path, int mask)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
return (QSimpleFuse::_instance)->sAccess(lPath, mask);
}
int s_create(const char *path, mode_t mode, fuse_file_info *fi)
{
lString lPath = toLString(path);
if (lPath.str_len > STR_LEN_MAX)
return -ENAMETOOLONG;
if ((mode & 0xFE00) != 0x8000)
{
dispLog("Warning: s_mknod on \"%s\" with mode 0%o\n", path, mode);
return -EPERM;
}
int ret_value = (QSimpleFuse::_instance)->sMkFile(lPath, (mode & 0x1FF) | 0x8000), fhv = 0;
if (ret_value == -EEXIST)
{
ret_value = (QSimpleFuse::_instance)->sOpen(lPath, O_WRONLY | O_TRUNC, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
if (ret_value < 0)
return ret_value;
ret_value = (QSimpleFuse::_instance)->sOpen(lPath, O_WRONLY, fhv);
fi->fh = (uint64_t) fhv;
return ret_value;
}
int s_ftruncate(const char *path, off_t offset, fuse_file_info *fi)
{
Q_UNUSED(path);
return (QSimpleFuse::_instance)->sFTruncate(fi->fh, offset);
}
int s_fgetattr(const char *path, struct stat *statbuf, fuse_file_info *fi)
{
Q_UNUSED(path);
sAttr result;
int ret_value;
if ((ret_value = (QSimpleFuse::_instance)->sFGetAttr(fi->fh, result)) < 0)
return ret_value;
PersistentData *data = PERSDATA;
*statbuf = data->def_stat;
statbuf->st_mode = result.mst_mode;
statbuf->st_nlink = result.mst_nlink;
statbuf->st_size = (result.mst_mode & 0x4000) ? 0x1000 : result.mst_size;
statbuf->st_blocks = (statbuf->st_size + 0x01FF) >> 9; // really useful ???
statbuf->st_atim.tv_sec = result.mst_atime;
statbuf->st_mtim.tv_sec = result.mst_mtime;
statbuf->st_ctim.tv_sec = result.mst_mtime;
return 0;
}
fuse_operations s_oper;
void makeSimplifiedFuseOperations()
{
memset(&s_oper, 0, sizeof(s_oper));
s_oper.getattr = s_getattr;
s_oper.mknod = s_mknod;
s_oper.mkdir = s_mkdir;
s_oper.unlink = s_unlink;
s_oper.rmdir = s_rmdir;
s_oper.rename = s_rename;
s_oper.link = s_link;
s_oper.chmod = s_chmod;
s_oper.chown = s_chown;
s_oper.truncate = s_truncate;
s_oper.utime = s_utime;
s_oper.open = s_open;
s_oper.read = s_read;
s_oper.write = s_write;
s_oper.flush = s_flush;
s_oper.release = s_release;
s_oper.fsync = s_fsync;
s_oper.opendir = s_opendir;
s_oper.readdir = s_readdir;
s_oper.releasedir = s_releasedir;
s_oper.fsyncdir = s_fsyncdir;
s_oper.init = s_init;
s_oper.destroy = s_destroy;
s_oper.access = s_access;
s_oper.create = s_create;
s_oper.ftruncate = s_ftruncate;
s_oper.fgetattr = s_fgetattr;
}
fuse_operations *getSimplifiedFuseOperations()
{
return &s_oper;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BENG_PROXY_STOCK_ITEM_HXX
#define BENG_PROXY_STOCK_ITEM_HXX
#include "util/Compiler.h"
#include <boost/intrusive/list_hook.hpp>
#include <exception>
struct pool;
class Stock;
class StockGetHandler;
struct CreateStockItem {
Stock &stock;
StockGetHandler &handler;
/**
* Wrapper for Stock::GetName()
*/
gcc_pure
const char *GetStockName() const noexcept;
/**
* Announce that the creation of this item has failed.
*/
void InvokeCreateError(std::exception_ptr ep) noexcept;
/**
* Announce that the creation of this item has been aborted by the
* caller.
*/
void InvokeCreateAborted() noexcept;
};
struct StockItem
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
Stock &stock;
StockGetHandler &handler;
/**
* If true, then this object will never be reused.
*/
bool fade = false;
/**
* Kludge: this flag is true if this item is idle and is not yet
* in a "clean" state (e.g. a WAS process after STOP), and cannot
* yet be reused. It will be postponed until this flag is false
* again. TODO: replace this kludge.
*/
bool unclean = false;
#ifndef NDEBUG
bool is_idle = false;
#endif
explicit StockItem(CreateStockItem c) noexcept
:stock(c.stock), handler(c.handler) {}
StockItem(const StockItem &) = delete;
StockItem &operator=(const StockItem &) = delete;
virtual ~StockItem() noexcept;
/**
* Wrapper for Stock::GetName()
*/
gcc_pure
const char *GetStockName() const noexcept;
/**
* Return a busy item to the stock. This is a wrapper for
* Stock::Put().
*/
void Put(bool destroy) noexcept;
/**
* Prepare this item to be borrowed by a client.
*
* @return false when this item is defunct and shall be destroyed
*/
virtual bool Borrow() noexcept = 0;
/**
* Return this borrowed item into the "idle" list.
*
* @return false when this item is defunct and shall not be reused
* again; it will be destroyed by the caller
*/
virtual bool Release() noexcept = 0;
/**
* Announce that the creation of this item has finished
* successfully, and it is ready to be used.
*/
void InvokeCreateSuccess() noexcept;
/**
* Announce that the creation of this item has failed.
*/
void InvokeCreateError(std::exception_ptr ep) noexcept;
/**
* Announce that the creation of this item has been aborted by the
* caller.
*/
void InvokeCreateAborted() noexcept;
/**
* Announce that the item has been disconnected by the peer while
* it was idle.
*/
void InvokeIdleDisconnect() noexcept;
};
#endif
<commit_msg>stock/Item: use LeakDetector<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BENG_PROXY_STOCK_ITEM_HXX
#define BENG_PROXY_STOCK_ITEM_HXX
#include "util/LeakDetector.hxx"
#include "util/Compiler.h"
#include <boost/intrusive/list_hook.hpp>
#include <exception>
struct pool;
class Stock;
class StockGetHandler;
struct CreateStockItem {
Stock &stock;
StockGetHandler &handler;
/**
* Wrapper for Stock::GetName()
*/
gcc_pure
const char *GetStockName() const noexcept;
/**
* Announce that the creation of this item has failed.
*/
void InvokeCreateError(std::exception_ptr ep) noexcept;
/**
* Announce that the creation of this item has been aborted by the
* caller.
*/
void InvokeCreateAborted() noexcept;
};
struct StockItem
: boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>,
private LeakDetector {
Stock &stock;
StockGetHandler &handler;
/**
* If true, then this object will never be reused.
*/
bool fade = false;
/**
* Kludge: this flag is true if this item is idle and is not yet
* in a "clean" state (e.g. a WAS process after STOP), and cannot
* yet be reused. It will be postponed until this flag is false
* again. TODO: replace this kludge.
*/
bool unclean = false;
#ifndef NDEBUG
bool is_idle = false;
#endif
explicit StockItem(CreateStockItem c) noexcept
:stock(c.stock), handler(c.handler) {}
StockItem(const StockItem &) = delete;
StockItem &operator=(const StockItem &) = delete;
virtual ~StockItem() noexcept;
/**
* Wrapper for Stock::GetName()
*/
gcc_pure
const char *GetStockName() const noexcept;
/**
* Return a busy item to the stock. This is a wrapper for
* Stock::Put().
*/
void Put(bool destroy) noexcept;
/**
* Prepare this item to be borrowed by a client.
*
* @return false when this item is defunct and shall be destroyed
*/
virtual bool Borrow() noexcept = 0;
/**
* Return this borrowed item into the "idle" list.
*
* @return false when this item is defunct and shall not be reused
* again; it will be destroyed by the caller
*/
virtual bool Release() noexcept = 0;
/**
* Announce that the creation of this item has finished
* successfully, and it is ready to be used.
*/
void InvokeCreateSuccess() noexcept;
/**
* Announce that the creation of this item has failed.
*/
void InvokeCreateError(std::exception_ptr ep) noexcept;
/**
* Announce that the creation of this item has been aborted by the
* caller.
*/
void InvokeCreateAborted() noexcept;
/**
* Announce that the item has been disconnected by the peer while
* it was idle.
*/
void InvokeIdleDisconnect() noexcept;
};
#endif
<|endoftext|> |
<commit_before>#include "dom.hpp"
#include <pugixml.hpp>
#include <map>
using namespace svgdom;
namespace{
enum class EXmlNamespace{
UNKNOWN,
SVG,
XLINK
};
const char* DSvgNamespace = "http://www.w3.org/2000/svg";
const char* DXlinkNamespace = "http://www.w3.org/1999/xlink";
struct Parser{
std::map<std::string, EXmlNamespace> namespaces;
EXmlNamespace defaultNamespace = EXmlNamespace::UNKNOWN;
std::unique_ptr<svgdom::Element> parseNode(const pugi::xml_node& n);
std::unique_ptr<SvgElement> parseSvgElement(const pugi::xml_node& n){
//TODO:
return nullptr;
}
};//~class
std::unique_ptr<svgdom::Element> Parser::parseNode(const pugi::xml_node& n){
//parse default namespace
{
pugi::xml_attribute dn = n.attribute("xmlns");
if(!dn.empty()){
if(std::string(dn.value()) == DSvgNamespace){
this->defaultNamespace = EXmlNamespace::SVG;
}else{
this->defaultNamespace = EXmlNamespace::UNKNOWN;
}
}
}
//parse other namespaces
{
std::string xmlns = "xmlns:";
for(auto a = n.first_attribute(); !a.empty(); a = a.next_attribute()){
auto attr = std::string(a.name());
if(attr.substr(0, xmlns.length()) != xmlns){
continue;
}
ASSERT(attr.length() >= xmlns.length())
auto ns = attr.substr(xmlns.length(), attr.length() - xmlns.length());
if(ns == DSvgNamespace){
this->namespaces[ns] = EXmlNamespace::SVG;
}else if (ns == DXlinkNamespace){
this->namespaces[ns] = EXmlNamespace::XLINK;
}else{
this->namespaces.erase(ns);
}
}
}
//TODO: check namespace
if(std::string("svg") == n.value()){
return parseSvgElement(n);
}
return nullptr;
}
}//~namespace
std::unique_ptr<SvgElement> svgdom::load(const papki::File& f){
auto fileContents = f.loadWholeFileIntoMemory();
pugi::xml_document doc;
doc.load_buffer(&*fileContents.begin(), fileContents.size());
Parser parser;
auto ret = parser.parseNode(doc.first_child());
return std::unique_ptr<SvgElement>(dynamic_cast<SvgElement*>(ret.release()));
}
<commit_msg>namespaces stack<commit_after>#include "dom.hpp"
#include <pugixml.hpp>
#include <map>
using namespace svgdom;
namespace{
enum class EXmlNamespace{
UNKNOWN,
SVG,
XLINK
};
const char* DSvgNamespace = "http://www.w3.org/2000/svg";
const char* DXlinkNamespace = "http://www.w3.org/1999/xlink";
struct Parser{
typedef std::map<std::string, EXmlNamespace> T_NamespaceMap;
std::vector<T_NamespaceMap> namespaces;
std::vector<EXmlNamespace> defaultNamespace;
std::unique_ptr<svgdom::Element> parseNode(const pugi::xml_node& n);
std::unique_ptr<SvgElement> parseSvgElement(const pugi::xml_node& n){
//TODO:
return nullptr;
}
};//~class
std::unique_ptr<svgdom::Element> Parser::parseNode(const pugi::xml_node& n){
//parse default namespace
{
pugi::xml_attribute dn = n.attribute("xmlns");
if(!dn.empty()){
if(std::string(dn.value()) == DSvgNamespace){
this->defaultNamespace.push_back(EXmlNamespace::SVG);
}else{
this->defaultNamespace.push_back(EXmlNamespace::UNKNOWN);
}
}else{
this->defaultNamespace.push_back(EXmlNamespace::UNKNOWN);
}
}
//parse other namespaces
{
std::string xmlns = "xmlns:";
this->namespaces.push_back(T_NamespaceMap());
for(auto a = n.first_attribute(); !a.empty(); a = a.next_attribute()){
auto attr = std::string(a.name());
if(attr.substr(0, xmlns.length()) != xmlns){
continue;
}
ASSERT(attr.length() >= xmlns.length())
auto ns = attr.substr(xmlns.length(), attr.length() - xmlns.length());
if(ns == DSvgNamespace){
this->namespaces.back()[ns] = EXmlNamespace::SVG;
}else if (ns == DXlinkNamespace){
this->namespaces.back()[ns] = EXmlNamespace::XLINK;
}else{
this->namespaces.back().erase(ns);
}
}
}
//TODO: check namespace
if(std::string("svg") == n.value()){
return parseSvgElement(n);
}
ASSERT(this->namespaces.size() > 0)
this->namespaces.pop_back();
ASSERT(this->defaultNamespace.size() > 0)
this->defaultNamespace.pop_back();
return nullptr;
}
}//~namespace
std::unique_ptr<SvgElement> svgdom::load(const papki::File& f){
auto fileContents = f.loadWholeFileIntoMemory();
pugi::xml_document doc;
doc.load_buffer(&*fileContents.begin(), fileContents.size());
Parser parser;
auto ret = parser.parseNode(doc.first_child());
return std::unique_ptr<SvgElement>(dynamic_cast<SvgElement*>(ret.release()));
}
<|endoftext|> |
<commit_before>#ifndef SYS_BUFFER_HPP
#define SYS_BUFFER_HPP
#include <stdlib.h>
#include <memory>
class Buffer;
/* Ignore the "BufferRef" class. */
class BufferRef {
public:
BufferRef(Buffer *b) throw() : p_(b) { }
Buffer &ref() throw() { return *p_; }
private:
Buffer *p_;
};
/* Memory buffer. Like auto_ptr, when copied, the buffer being copied
will be set to NULL. */
class Buffer {
public:
Buffer() throw() : ptr_(0), len_(0) { }
Buffer(size_t sz) : ptr_(0), len_(0) { resize(sz); }
Buffer(void *ptr, size_t len) throw() : ptr_(ptr), len_(len) { }
Buffer(Buffer &b) throw() : ptr_(b.ptr_), len_(b.len_) { b.release(); }
Buffer(BufferRef r) throw()
{
void *p = r.ref().ptr_;
size_t l = r.ref().len_;
r.ref().release();
ptr_ = p;
len_ = l;
}
~Buffer() throw() { if (ptr_) free(ptr_); }
Buffer& operator=(Buffer &b) throw()
{
if (this != &b) {
clear();
ptr_ = b.ptr_;
len_ = b.len_;
b.release();
}
return *this;
}
void clear() throw()
{
if (ptr_) {
free(ptr_);
ptr_ = 0;
len_ = 0;
}
}
void resize(size_t sz)
{
void *p = realloc(ptr_, sz);
if (sz && !p)
throw std::bad_alloc();
ptr_ = p;
len_ = sz;
}
void release() throw()
{
ptr_ = 0;
len_ = 0;
}
void *get() const throw() { return ptr_; }
unsigned char *getUC() const throw()
{ return reinterpret_cast<unsigned char *>(ptr_); }
size_t size() { return len_; }
operator BufferRef() throw() { return BufferRef(this); }
private:
void *ptr_;
size_t len_;
};
#endif
<commit_msg>Fixed assignment operator for Buffer class.<commit_after>#ifndef SYS_BUFFER_HPP
#define SYS_BUFFER_HPP
#include <stdlib.h>
#include <memory>
class Buffer;
/* Ignore the "BufferRef" class. */
class BufferRef {
public:
explicit BufferRef(Buffer *b) throw() : p_(b) { }
Buffer &ref() throw() { return *p_; }
private:
Buffer *p_;
};
/* Memory buffer. Like auto_ptr, when copied, the buffer being copied
will be set to NULL. */
class Buffer {
public:
Buffer() throw() : ptr_(0), len_(0) { }
Buffer(size_t sz) : ptr_(0), len_(0) { resize(sz); }
Buffer(void *ptr, size_t len) throw() : ptr_(ptr), len_(len) { }
Buffer(Buffer &b) throw() : ptr_(b.ptr_), len_(b.len_) { b.release(); }
Buffer(BufferRef r) throw()
{
void *p = r.ref().ptr_;
size_t l = r.ref().len_;
r.ref().release();
ptr_ = p;
len_ = l;
}
~Buffer() throw() { if (ptr_) free(ptr_); }
Buffer &operator=(Buffer &b) throw()
{
if (this != &b) {
clear();
ptr_ = b.ptr_;
len_ = b.len_;
b.release();
}
return *this;
}
Buffer &operator=(BufferRef r) throw()
{
if (this != &r.ref()) {
void *p = r.ref().ptr_;
size_t l = r.ref().len_;
r.ref().release();
clear();
ptr_ = p;
len_ = l;
}
return *this;
}
void clear() throw()
{
if (ptr_) {
free(ptr_);
ptr_ = 0;
len_ = 0;
}
}
void resize(size_t sz)
{
void *p = realloc(ptr_, sz);
if (sz && !p)
throw std::bad_alloc();
ptr_ = p;
len_ = sz;
}
void release() throw()
{
ptr_ = 0;
len_ = 0;
}
void *get() const throw() { return ptr_; }
unsigned char *getUC() const throw()
{ return reinterpret_cast<unsigned char *>(ptr_); }
size_t size() const { return len_; }
operator BufferRef() throw() { return BufferRef(this); }
private:
void *ptr_;
size_t len_;
};
#endif
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include "service.h"
// Test 1: starting a service starts dependencies; stopping the service releases and
// stops dependencies.
void test1()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// s3 depends on s2, which depends on s1. So starting s3 should start all three services:
sset.start_service(s3);
assert(s1->getState() == service_state_t::STARTED);
assert(s2->getState() == service_state_t::STARTED);
assert(s3->getState() == service_state_t::STARTED);
// stopping s3 should release the other two services:
sset.stop_service(s3);
assert(s3->getState() == service_state_t::STOPPED);
assert(s2->getState() == service_state_t::STOPPED);
assert(s1->getState() == service_state_t::STOPPED);
}
// Test 2: Multiple dependents will hold a dependency active if one of the dependents is
// stopped/released.
void test2()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
service_record *s4 = new service_record(&sset, "test-service-4", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
sset.add_service(s4);
// s3 depends on s2, which depends on s1. Similarly with s4. After starting both, all services
// should be started:
sset.start_service(s3);
sset.start_service(s4);
assert(s1->getState() == service_state_t::STARTED);
assert(s2->getState() == service_state_t::STARTED);
assert(s3->getState() == service_state_t::STARTED);
assert(s4->getState() == service_state_t::STARTED);
// after stopping s3, s4 should hold the other two services:
sset.stop_service(s3);
assert(s4->getState() == service_state_t::STARTED);
assert(s3->getState() == service_state_t::STOPPED);
assert(s2->getState() == service_state_t::STARTED);
assert(s1->getState() == service_state_t::STARTED);
// Now if we stop s4, s2 and s1 should also be released:
sset.stop_service(s4);
assert(s4->getState() == service_state_t::STOPPED);
assert(s3->getState() == service_state_t::STOPPED);
assert(s2->getState() == service_state_t::STOPPED);
assert(s1->getState() == service_state_t::STOPPED);
}
// Test 3: stopping a dependency causes its dependents to stop.
void test3()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// Start all three services:
sset.start_service(s3);
// Now stop s1, which should also force s2 and s3 to stop:
sset.stop_service(s1);
assert(s3->getState() == service_state_t::STOPPED);
assert(s2->getState() == service_state_t::STOPPED);
assert(s1->getState() == service_state_t::STOPPED);
}
// Test 4: an explicitly activated service with automatic restart will restart if it
// stops due to a dependency stopping, therefore also causing the dependency to restart.
void test4()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
s2->setAutoRestart(true);
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// Start all three services:
sset.start_service(s3);
// Also explicitly activate s2:
sset.start_service(s2);
// Now stop s1, which should also force s2 and s3 to stop.
// s2 (and therefore s1) should restart:
sset.stop_service(s1);
assert(s3->getState() == service_state_t::STOPPED);
assert(s2->getState() == service_state_t::STARTED);
assert(s1->getState() == service_state_t::STARTED);
}
int main(int argc, char **argv)
{
std::cout << "test1... ";
test1();
std::cout << "PASSED" << std::endl;
std::cout << "test2... ";
test2();
std::cout << "PASSED" << std::endl;
std::cout << "test3... ";
test3();
std::cout << "PASSED" << std::endl;
std::cout << "test4... ";
test4();
std::cout << "PASSED" << std::endl;
}
<commit_msg>tests: correct get_state call (after rename from getState).<commit_after>#include <cassert>
#include <iostream>
#include "service.h"
// Test 1: starting a service starts dependencies; stopping the service releases and
// stops dependencies.
void test1()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// s3 depends on s2, which depends on s1. So starting s3 should start all three services:
sset.start_service(s3);
assert(s1->get_state() == service_state_t::STARTED);
assert(s2->get_state() == service_state_t::STARTED);
assert(s3->get_state() == service_state_t::STARTED);
// stopping s3 should release the other two services:
sset.stop_service(s3);
assert(s3->get_state() == service_state_t::STOPPED);
assert(s2->get_state() == service_state_t::STOPPED);
assert(s1->get_state() == service_state_t::STOPPED);
}
// Test 2: Multiple dependents will hold a dependency active if one of the dependents is
// stopped/released.
void test2()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
service_record *s4 = new service_record(&sset, "test-service-4", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
sset.add_service(s4);
// s3 depends on s2, which depends on s1. Similarly with s4. After starting both, all services
// should be started:
sset.start_service(s3);
sset.start_service(s4);
assert(s1->get_state() == service_state_t::STARTED);
assert(s2->get_state() == service_state_t::STARTED);
assert(s3->get_state() == service_state_t::STARTED);
assert(s4->get_state() == service_state_t::STARTED);
// after stopping s3, s4 should hold the other two services:
sset.stop_service(s3);
assert(s4->get_state() == service_state_t::STARTED);
assert(s3->get_state() == service_state_t::STOPPED);
assert(s2->get_state() == service_state_t::STARTED);
assert(s1->get_state() == service_state_t::STARTED);
// Now if we stop s4, s2 and s1 should also be released:
sset.stop_service(s4);
assert(s4->get_state() == service_state_t::STOPPED);
assert(s3->get_state() == service_state_t::STOPPED);
assert(s2->get_state() == service_state_t::STOPPED);
assert(s1->get_state() == service_state_t::STOPPED);
}
// Test 3: stopping a dependency causes its dependents to stop.
void test3()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// Start all three services:
sset.start_service(s3);
// Now stop s1, which should also force s2 and s3 to stop:
sset.stop_service(s1);
assert(s3->get_state() == service_state_t::STOPPED);
assert(s2->get_state() == service_state_t::STOPPED);
assert(s1->get_state() == service_state_t::STOPPED);
}
// Test 4: an explicitly activated service with automatic restart will restart if it
// stops due to a dependency stopping, therefore also causing the dependency to restart.
void test4()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type::INTERNAL, {}, {});
service_record *s2 = new service_record(&sset, "test-service-2", service_type::INTERNAL, {s1}, {});
service_record *s3 = new service_record(&sset, "test-service-3", service_type::INTERNAL, {s2}, {});
s2->set_auto_restart(true);
sset.add_service(s1);
sset.add_service(s2);
sset.add_service(s3);
assert(sset.find_service("test-service-1") == s1);
assert(sset.find_service("test-service-2") == s2);
assert(sset.find_service("test-service-3") == s3);
// Start all three services:
sset.start_service(s3);
// Also explicitly activate s2:
sset.start_service(s2);
// Now stop s1, which should also force s2 and s3 to stop.
// s2 (and therefore s1) should restart:
sset.stop_service(s1);
assert(s3->get_state() == service_state_t::STOPPED);
assert(s2->get_state() == service_state_t::STARTED);
assert(s1->get_state() == service_state_t::STARTED);
}
int main(int argc, char **argv)
{
std::cout << "test1... ";
test1();
std::cout << "PASSED" << std::endl;
std::cout << "test2... ";
test2();
std::cout << "PASSED" << std::endl;
std::cout << "test3... ";
test3();
std::cout << "PASSED" << std::endl;
std::cout << "test4... ";
test4();
std::cout << "PASSED" << std::endl;
}
<|endoftext|> |
<commit_before>#ifndef UTF8_TYPES_HPP_INCLUDED
#define UTF8_TYPES_HPP_INCLUDED
typedef unsigned char byte_t;
typedef size_t utf8_len_t;
#endif // UTF8_TYPES_HPP_INCLUDED
<commit_msg>Fixed clang warning<commit_after>#ifndef UTF8_TYPES_HPP_INCLUDED
#define UTF8_TYPES_HPP_INCLUDED
typedef char byte_t;
typedef size_t utf8_len_t;
#endif // UTF8_TYPES_HPP_INCLUDED
<|endoftext|> |
<commit_before>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <set>
#include <memory>
#include <typeinfo>
#include <functional>
#include <cxxabi.h>
#include "suppressWarnings.hpp"
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
typedef std::set<std::string> TypeList;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> vec {};
std::stringstream ss(str);
std::string item;
while (getline(ss, item, delim)) vec.push_back(item);
return vec;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::unique_ptr<T> U;
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static U unique(Args... args) {
return std::make_unique<T>(args...);
}
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<std::uintptr_t>(ptr);
return ss.str();
}
std::string demangle(std::string name) {
int status;
return abi::__cxa_demangle(name.c_str(), 0, 0, &status);
}
#define COLLATE_TYPE const typename Container::value_type&
template<typename Container>
std::string collate(Container c,
std::function<std::string(COLLATE_TYPE)> objToString,
std::function<std::string(std::string, std::string)> combine = [](std::string prev, std::string current) {return prev + ", " + current;}
) {
if (c.size() == 0) return "";
if (c.size() == 1) return objToString(*c.begin());
if (c.size() >= 2) {
std::string str = objToString(*c.begin());
std::for_each(++c.begin(), c.end(), [&str, &objToString, &combine](COLLATE_TYPE object) {
str = combine(str, objToString(object));
});
return str;
}
throw std::logic_error("Size of container must be a positive integer");
}
#undef COLLATE_TYPE
std::string collateTypeList(TypeList typeList) {
return collate<TypeList>(typeList, [](std::string s) {return s;});
}
#endif
<commit_msg>Fixed link error when collate was used multiple times<commit_after>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <set>
#include <memory>
#include <typeinfo>
#include <functional>
#include <cxxabi.h>
#include "suppressWarnings.hpp"
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
typedef std::set<std::string> TypeList;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> vec {};
std::stringstream ss(str);
std::string item;
while (getline(ss, item, delim)) vec.push_back(item);
return vec;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::unique_ptr<T> U;
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static U unique(Args... args) {
return std::make_unique<T>(args...);
}
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<std::uintptr_t>(ptr);
return ss.str();
}
std::string demangle(std::string name) {
int status;
return abi::__cxa_demangle(name.c_str(), 0, 0, &status);
}
#define COLLATE_TYPE const typename Container::value_type&
static const auto defaultCollateCombine = [](std::string prev, std::string current) {return prev + ", " + current;};
template<typename Container>
std::string collate(Container c,
std::function<std::string(COLLATE_TYPE)> objToString,
std::function<std::string(std::string, std::string)> combine = defaultCollateCombine
) {
if (c.size() == 0) return "";
if (c.size() == 1) return objToString(*c.begin());
if (c.size() >= 2) {
std::string str = objToString(*c.begin());
std::for_each(++c.begin(), c.end(), [&str, &objToString, &combine](COLLATE_TYPE object) {
str = combine(str, objToString(object));
});
return str;
}
throw std::logic_error("Size of container must be a positive integer");
}
#undef COLLATE_TYPE
std::string collateTypeList(TypeList typeList) {
return collate<TypeList>(typeList, [](std::string s) {return s;});
}
#endif
<|endoftext|> |
<commit_before>#include "ghost/densemat_cm.h"
#include "ghost/util.h"
#include "ghost/locality.h"
#include <complex>
template<typename T>
static ghost_error ghost_densemat_cm_averagehalo_tmpl(ghost_densemat *vec)
{
#ifdef GHOST_HAVE_MPI
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_COMMUNICATION);
ghost_error ret = GHOST_SUCCESS;
int rank, nrank, i, acc_dues = 0;
T *work = NULL, *curwork = NULL;
MPI_Request *req = NULL;
ghost_lidx *curdue = NULL;
T *sum = NULL;
int *nrankspresent = NULL;
if (vec->traits.ncols > 1) {
ERROR_LOG("Multi-vec case not yet implemented");
ret = GHOST_ERR_NOT_IMPLEMENTED;
goto err;
}
if (vec->context == NULL) {
WARNING_LOG("Trying to average the halos of a densemat which has no context!");
goto out;
}
GHOST_CALL_GOTO(ghost_rank(&rank,vec->context->mpicomm),err,ret);
GHOST_CALL_GOTO(ghost_nrank(&nrank,vec->context->mpicomm),err,ret);
for (i=0; i<nrank; i++) {
acc_dues += vec->context->dues[i];
}
GHOST_CALL_GOTO(ghost_malloc((void **)&work, acc_dues*sizeof(T)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&req, 2*nrank*sizeof(MPI_Request)),err,ret);
for (i=0; i<2*nrank; i++) {
req[i] = MPI_REQUEST_NULL;
}
for (i=0; i<nrank; i++) {
MPI_CALL_GOTO(MPI_Isend(&((T *)vec->val)[vec->context->hput_pos[i]],vec->context->wishes[i]*vec->traits.ncols,vec->mpidt,i,rank,vec->context->mpicomm,&req[i]),err,ret);
}
curwork = work;
for (i=0; i<nrank; i++) {
MPI_CALL_GOTO(MPI_Irecv(curwork,vec->context->dues[i]*vec->traits.ncols,vec->mpidt,i,i,vec->context->mpicomm,&req[nrank+i]),err,ret);
curwork += vec->context->dues[i];
}
MPI_CALL_GOTO(MPI_Waitall(2*nrank,req,MPI_STATUSES_IGNORE),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&curdue, nrank*sizeof(ghost_lidx)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&sum, vec->context->lnrows[rank]*sizeof(T)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&nrankspresent, vec->context->lnrows[rank]*sizeof(int)),err,ret);
for (i=0; i<nrank; i++) {
curdue[i] = 0;
}
for (i=0; i<vec->context->lnrows[rank]; i++) {
sum[i] = vec->context->entsInCol[i]*((T *)vec->val)[i];
nrankspresent[i] = vec->context->entsInCol[i];
}
ghost_lidx currow;
curwork = work;
for (i=0; i<nrank; i++) {
if (i == rank) {
continue;
}
for (currow=0; currow<vec->context->lnrows[rank] && curdue[i] < vec->context->dues[i]; currow++) {
if (vec->context->duelist[i][curdue[i]] == currow) {
sum[currow] += curwork[curdue[i]];
curdue[i]++;
nrankspresent[currow]++;
}
}
curwork += vec->context->dues[i];
}
for (currow=0; currow<vec->context->lnrows[rank]; currow++) {
((T *)vec->val)[currow] = sum[currow]/(T)nrankspresent[currow];
}
goto out;
err:
out:
free(curdue);
free(sum);
free(nrankspresent);
free(work);
free(req);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_COMMUNICATION);
return ret;
#else
UNUSED(vec);
ERROR_LOG("MPI is required!");
return GHOST_ERR_MPI;
#endif
}
ghost_error ghost_densemat_cm_averagehalo_selector(ghost_densemat *vec)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_COMMUNICATION);
ghost_error ret = GHOST_SUCCESS;
SELECT_TMPL_1DATATYPE(vec->traits.datatype,std::complex,ret,ghost_densemat_cm_averagehalo_tmpl,vec);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_COMMUNICATION);
return ret;
}
<commit_msg>cast value to fix compiler error (GCC)<commit_after>#include "ghost/densemat_cm.h"
#include "ghost/util.h"
#include "ghost/locality.h"
#include <complex>
template<typename T>
static ghost_error ghost_densemat_cm_averagehalo_tmpl(ghost_densemat *vec)
{
#ifdef GHOST_HAVE_MPI
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_COMMUNICATION);
ghost_error ret = GHOST_SUCCESS;
int rank, nrank, i, acc_dues = 0;
T *work = NULL, *curwork = NULL;
MPI_Request *req = NULL;
ghost_lidx *curdue = NULL;
T *sum = NULL;
int *nrankspresent = NULL;
if (vec->traits.ncols > 1) {
ERROR_LOG("Multi-vec case not yet implemented");
ret = GHOST_ERR_NOT_IMPLEMENTED;
goto err;
}
if (vec->context == NULL) {
WARNING_LOG("Trying to average the halos of a densemat which has no context!");
goto out;
}
GHOST_CALL_GOTO(ghost_rank(&rank,vec->context->mpicomm),err,ret);
GHOST_CALL_GOTO(ghost_nrank(&nrank,vec->context->mpicomm),err,ret);
for (i=0; i<nrank; i++) {
acc_dues += vec->context->dues[i];
}
GHOST_CALL_GOTO(ghost_malloc((void **)&work, acc_dues*sizeof(T)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&req, 2*nrank*sizeof(MPI_Request)),err,ret);
for (i=0; i<2*nrank; i++) {
req[i] = MPI_REQUEST_NULL;
}
for (i=0; i<nrank; i++) {
MPI_CALL_GOTO(MPI_Isend(&((T *)vec->val)[vec->context->hput_pos[i]],vec->context->wishes[i]*vec->traits.ncols,vec->mpidt,i,rank,vec->context->mpicomm,&req[i]),err,ret);
}
curwork = work;
for (i=0; i<nrank; i++) {
MPI_CALL_GOTO(MPI_Irecv(curwork,vec->context->dues[i]*vec->traits.ncols,vec->mpidt,i,i,vec->context->mpicomm,&req[nrank+i]),err,ret);
curwork += vec->context->dues[i];
}
MPI_CALL_GOTO(MPI_Waitall(2*nrank,req,MPI_STATUSES_IGNORE),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&curdue, nrank*sizeof(ghost_lidx)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&sum, vec->context->lnrows[rank]*sizeof(T)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&nrankspresent, vec->context->lnrows[rank]*sizeof(int)),err,ret);
for (i=0; i<nrank; i++) {
curdue[i] = 0;
}
for (i=0; i<vec->context->lnrows[rank]; i++) {
sum[i] = (T)(vec->context->entsInCol[i]) * ((T *)vec->val)[i];
nrankspresent[i] = vec->context->entsInCol[i];
}
ghost_lidx currow;
curwork = work;
for (i=0; i<nrank; i++) {
if (i == rank) {
continue;
}
for (currow=0; currow<vec->context->lnrows[rank] && curdue[i] < vec->context->dues[i]; currow++) {
if (vec->context->duelist[i][curdue[i]] == currow) {
sum[currow] += curwork[curdue[i]];
curdue[i]++;
nrankspresent[currow]++;
}
}
curwork += vec->context->dues[i];
}
for (currow=0; currow<vec->context->lnrows[rank]; currow++) {
((T *)vec->val)[currow] = sum[currow]/(T)nrankspresent[currow];
}
goto out;
err:
out:
free(curdue);
free(sum);
free(nrankspresent);
free(work);
free(req);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_COMMUNICATION);
return ret;
#else
UNUSED(vec);
ERROR_LOG("MPI is required!");
return GHOST_ERR_MPI;
#endif
}
ghost_error ghost_densemat_cm_averagehalo_selector(ghost_densemat *vec)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_COMMUNICATION);
ghost_error ret = GHOST_SUCCESS;
SELECT_TMPL_1DATATYPE(vec->traits.datatype,std::complex,ret,ghost_densemat_cm_averagehalo_tmpl,vec);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_COMMUNICATION);
return ret;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2007-2012, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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 view_curses.cc
*/
#include "config.h"
#include <string>
#include <algorithm>
#include "view_curses.hh"
using namespace std;
void view_curses::mvwattrline(WINDOW *window,
int y,
int x,
attr_line_t &al,
struct line_range &lr,
view_colors::role_t base_role)
{
int text_attrs, attrs, line_width;
string_attrs_t & sa = al.get_attrs();
string & line = al.get_string();
string_attrs_t::iterator iter;
std::map<size_t, size_t, std::greater<size_t> > tab_list;
int tab_count = 0;
char * buffer, *expanded_line;
size_t exp_index = 0;
string full_line;
assert(lr.lr_end >= 0);
line_width = lr.length();
buffer = (char *)alloca(line_width + 1);
tab_count = count(line.begin(), line.end(), '\t');
expanded_line = (char *)alloca(line.size() + tab_count * 8 + 1);
for (size_t lpc = 0; lpc < line.size(); lpc++) {
switch (line[lpc]) {
case '\t':
do {
expanded_line[exp_index] = ' ';
exp_index += 1;
} while (exp_index % 8);
tab_list[lpc] = exp_index;
break;
case '\r':
/* exp_index = -1; */
break;
case '\n':
expanded_line[exp_index] = ' ';
exp_index += 1;
break;
default:
expanded_line[exp_index] = line[lpc];
exp_index += 1;
break;
}
}
expanded_line[exp_index] = '\0';
full_line = string(expanded_line);
text_attrs = view_colors::singleton().attrs_for_role(base_role);
attrs = text_attrs;
wmove(window, y, x);
wattron(window, attrs);
if (lr.lr_start < (int)full_line.size()) {
waddnstr(window, &full_line.c_str()[lr.lr_start], line_width);
}
if (lr.lr_end > (int)full_line.size()) {
whline(window, ' ', lr.lr_end - full_line.size());
}
wattroff(window, attrs);
std::vector<line_range> graphic_range;
std::vector<int> graphic_in;
for (iter = sa.begin(); iter != sa.end(); ++iter) {
struct line_range attr_range = iter->first;
std::map<size_t, size_t>::iterator tab_iter;
assert(attr_range.lr_start >= 0);
assert(attr_range.lr_end >= -1);
tab_iter = tab_list.lower_bound(attr_range.lr_start);
if (tab_iter != tab_list.end()) {
attr_range.lr_start += (tab_iter->second - tab_iter->first) - 1;
}
if (attr_range.lr_end != -1) {
tab_iter = tab_list.lower_bound(attr_range.lr_end);
if (tab_iter != tab_list.end()) {
attr_range.lr_end += (tab_iter->second - tab_iter->first) - 1;
}
}
attr_range.lr_start = max(0, attr_range.lr_start - lr.lr_start);
if (attr_range.lr_end == -1) {
attr_range.lr_end = line_width;
}
else {
attr_range.lr_end = min((int)line_width,
attr_range.lr_end - lr.lr_start);
}
if (attr_range.lr_end > 0) {
int awidth = attr_range.length();
attrs_map_t & am = iter->second;
attrs_map_t::iterator am_iter;
attrs = 0;
for (am_iter = am.begin(); am_iter != am.end(); ++am_iter) {
if (am_iter->first == "style") {
attrs |= am_iter->second.sa_int;
}
}
if (attrs != 0) {
/* This silliness is brought to you by a buggy old curses lib. */
mvwinnstr(window, y, x + attr_range.lr_start, buffer, awidth);
wattron(window, attrs);
mvwaddnstr(window, y, x + attr_range.lr_start, buffer, awidth);
wattroff(window, attrs);
}
for (am_iter = am.begin(); am_iter != am.end(); ++am_iter) {
if (am_iter->first == "graphic") {
graphic_range.push_back(attr_range);
graphic_in.push_back(am_iter->second.sa_int | attrs);
}
}
}
attrs = text_attrs; /* Reset attrs to regular text. */
}
for (size_t lpc = 0; lpc < graphic_range.size(); lpc++) {
for (int lpc2 = graphic_range[lpc].lr_start;
lpc2 < graphic_range[lpc].lr_end;
lpc2++) {
mvwaddch(window, y, lpc2, graphic_in[lpc]);
}
}
}
view_colors &view_colors::singleton(void)
{
static view_colors s_vc;
return s_vc;
}
view_colors::view_colors()
: vc_next_highlight(0)
{
int lpc;
/* Setup the mappings from roles to actual colors. */
this->vc_role_colors[VCR_TEXT] = COLOR_PAIR(VC_WHITE) | A_DIM;
this->vc_role_colors[VCR_SEARCH] =
this->vc_role_colors[VCR_TEXT] | A_REVERSE;
this->vc_role_colors[VCR_OK] = COLOR_PAIR(VC_GREEN) | A_BOLD;
this->vc_role_colors[VCR_ERROR] = COLOR_PAIR(VC_RED) | A_BOLD;
this->vc_role_colors[VCR_WARNING] = COLOR_PAIR(VC_YELLOW) | A_BOLD;
this->vc_role_colors[VCR_ALT_ROW] = COLOR_PAIR(VC_WHITE) | A_BOLD;
this->vc_role_colors[VCR_STATUS] =
COLOR_PAIR(VC_BLACK_ON_WHITE);
this->vc_role_colors[VCR_WARN_STATUS] =
COLOR_PAIR(VC_YELLOW_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_ALERT_STATUS] =
COLOR_PAIR(VC_RED_ON_WHITE);
this->vc_role_colors[VCR_ACTIVE_STATUS] =
COLOR_PAIR(VC_GREEN_ON_WHITE);
this->vc_role_colors[VCR_ACTIVE_STATUS2] =
COLOR_PAIR(VC_GREEN_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_BOLD_STATUS] =
COLOR_PAIR(VC_BLACK_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_DIFF_DELETE] = COLOR_PAIR(VC_RED);
this->vc_role_colors[VCR_DIFF_ADD] = COLOR_PAIR(VC_GREEN);
this->vc_role_colors[VCR_DIFF_SECTION] = COLOR_PAIR(VC_MAGENTA);
this->vc_role_colors[VCR_SHADOW] = COLOR_PAIR(VC_GRAY);
for (lpc = 0; lpc < VCR__MAX; lpc++) {
this->vc_role_reverse_colors[lpc] =
this->vc_role_colors[lpc] | A_REVERSE;
}
/*
* Prime the highlight vector. The first HL_COLOR_COUNT color pairs are
* assumed to be the highlight colors.
*/
for (lpc = 1; lpc <= HL_COLOR_COUNT; lpc++) {
this->vc_role_colors[VCR__MAX + (lpc - 1) * 2] = COLOR_PAIR(lpc);
this->vc_role_colors[VCR__MAX + (lpc - 1) * 2 + 1] =
COLOR_PAIR(lpc) | A_BOLD;
this->vc_role_reverse_colors[VCR__MAX + (lpc - 1) * 2] =
COLOR_PAIR(lpc + HL_COLOR_COUNT) | A_REVERSE;
this->vc_role_reverse_colors[VCR__MAX + (lpc - 1) * 2 + 1] =
COLOR_PAIR(lpc + HL_COLOR_COUNT) | A_BOLD | A_REVERSE;
}
}
void view_colors::init(void)
{
if (has_colors()) {
static int ansi_colors_to_curses[] = {
COLOR_BLACK,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW,
COLOR_BLUE,
COLOR_MAGENTA,
COLOR_CYAN,
COLOR_WHITE,
};
start_color();
/* use_default_colors(); */
init_pair(VC_BLUE, COLOR_BLUE, COLOR_BLACK);
init_pair(VC_CYAN, COLOR_CYAN, COLOR_BLACK);
init_pair(VC_GREEN, COLOR_GREEN, COLOR_BLACK);
init_pair(VC_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
init_pair(VC_BLUE_ON_WHITE, COLOR_BLUE, COLOR_WHITE);
init_pair(VC_CYAN_ON_BLACK, COLOR_CYAN, COLOR_BLACK);
init_pair(VC_CYAN_ON_WHITE, COLOR_CYAN, COLOR_WHITE);
init_pair(VC_GREEN_ON_WHITE, COLOR_GREEN, COLOR_WHITE);
init_pair(VC_MAGENTA_ON_WHITE, COLOR_MAGENTA, COLOR_WHITE);
init_pair(VC_RED, COLOR_RED, COLOR_BLACK);
init_pair(VC_YELLOW, COLOR_YELLOW, COLOR_BLACK);
init_pair(VC_WHITE, COLOR_WHITE, COLOR_BLACK);
init_pair(VC_BLACK_ON_WHITE, COLOR_BLACK, COLOR_WHITE);
init_pair(VC_RED_ON_WHITE, COLOR_RED, COLOR_WHITE);
init_pair(VC_YELLOW_ON_WHITE, COLOR_YELLOW, COLOR_WHITE);
init_pair(VC_CYAN_ON_BLUE, COLOR_CYAN, COLOR_BLUE);
init_pair(VC_WHITE_ON_GREEN, COLOR_WHITE, COLOR_GREEN);
init_pair(VC_WHITE_ON_CYAN, COLOR_WHITE, COLOR_CYAN);
init_pair(VC_GRAY, COLOR_BLACK, COLOR_BLACK);
for (int fg = 0; fg < 8; fg++) {
for (int bg = 0; bg < 8; bg++) {
init_pair(ansi_color_pair_index(fg, bg),
ansi_colors_to_curses[fg],
ansi_colors_to_curses[bg]);
}
}
for (int lpc = 0; lpc < 8; lpc++) {
short gradient_value = (1000 / 8) * lpc;
init_color(lpc + 16, gradient_value, gradient_value,
gradient_value);
init_pair(VC_GRADIENT_START + lpc, lpc + 16, COLOR_BLACK);
}
}
}
view_colors::role_t view_colors::next_highlight()
{
role_t retval = (role_t)(VCR__MAX + this->vc_next_highlight);
this->vc_next_highlight = (this->vc_next_highlight + 1) %
(HL_COLOR_COUNT * 2);
return retval;
}
view_colors::role_t view_colors::next_plain_highlight()
{
role_t retval = (role_t)(VCR__MAX + this->vc_next_plain_highlight);
this->vc_next_plain_highlight = (this->vc_next_plain_highlight + 2) %
(HL_COLOR_COUNT * 2);
return retval;
}
<commit_msg>[view_curses] use mvchgat in mvwattrline since it seems to work fine now and is much faster<commit_after>/**
* Copyright (c) 2007-2012, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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 view_curses.cc
*/
#include "config.h"
#include <string>
#include <algorithm>
#include "view_curses.hh"
using namespace std;
void view_curses::mvwattrline(WINDOW *window,
int y,
int x,
attr_line_t &al,
struct line_range &lr,
view_colors::role_t base_role)
{
int text_attrs, attrs, line_width;
string_attrs_t & sa = al.get_attrs();
string & line = al.get_string();
string_attrs_t::iterator iter;
std::map<size_t, size_t, std::greater<size_t> > tab_list;
int tab_count = 0;
char * buffer, *expanded_line;
size_t exp_index = 0;
string full_line;
assert(lr.lr_end >= 0);
line_width = lr.length();
buffer = (char *)alloca(line_width + 1);
tab_count = count(line.begin(), line.end(), '\t');
expanded_line = (char *)alloca(line.size() + tab_count * 8 + 1);
for (size_t lpc = 0; lpc < line.size(); lpc++) {
switch (line[lpc]) {
case '\t':
do {
expanded_line[exp_index] = ' ';
exp_index += 1;
} while (exp_index % 8);
tab_list[lpc] = exp_index;
break;
case '\r':
/* exp_index = -1; */
break;
case '\n':
expanded_line[exp_index] = ' ';
exp_index += 1;
break;
default:
expanded_line[exp_index] = line[lpc];
exp_index += 1;
break;
}
}
expanded_line[exp_index] = '\0';
full_line = string(expanded_line);
text_attrs = view_colors::singleton().attrs_for_role(base_role);
attrs = text_attrs;
wmove(window, y, x);
wattron(window, attrs);
if (lr.lr_start < (int)full_line.size()) {
waddnstr(window, &full_line.c_str()[lr.lr_start], line_width);
}
if (lr.lr_end > (int)full_line.size()) {
whline(window, ' ', lr.lr_end - full_line.size());
}
wattroff(window, attrs);
std::vector<line_range> graphic_range;
std::vector<int> graphic_in;
for (iter = sa.begin(); iter != sa.end(); ++iter) {
struct line_range attr_range = iter->first;
std::map<size_t, size_t>::iterator tab_iter;
assert(attr_range.lr_start >= 0);
assert(attr_range.lr_end >= -1);
tab_iter = tab_list.lower_bound(attr_range.lr_start);
if (tab_iter != tab_list.end()) {
attr_range.lr_start += (tab_iter->second - tab_iter->first) - 1;
}
if (attr_range.lr_end != -1) {
tab_iter = tab_list.lower_bound(attr_range.lr_end);
if (tab_iter != tab_list.end()) {
attr_range.lr_end += (tab_iter->second - tab_iter->first) - 1;
}
}
attr_range.lr_start = max(0, attr_range.lr_start - lr.lr_start);
if (attr_range.lr_end == -1) {
attr_range.lr_end = line_width;
}
else {
attr_range.lr_end = min((int)line_width,
attr_range.lr_end - lr.lr_start);
}
if (attr_range.lr_end > 0) {
int awidth = attr_range.length();
attrs_map_t & am = iter->second;
attrs_map_t::iterator am_iter;
attrs = 0;
for (am_iter = am.begin(); am_iter != am.end(); ++am_iter) {
if (am_iter->first == "style") {
attrs |= am_iter->second.sa_int;
}
}
if (attrs != 0) {
mvwchgat(window, y, x + attr_range.lr_start, awidth, attrs, PAIR_NUMBER(attrs), NULL);
}
for (am_iter = am.begin(); am_iter != am.end(); ++am_iter) {
if (am_iter->first == "graphic") {
graphic_range.push_back(attr_range);
graphic_in.push_back(am_iter->second.sa_int | attrs);
}
}
}
attrs = text_attrs; /* Reset attrs to regular text. */
}
for (size_t lpc = 0; lpc < graphic_range.size(); lpc++) {
for (int lpc2 = graphic_range[lpc].lr_start;
lpc2 < graphic_range[lpc].lr_end;
lpc2++) {
mvwaddch(window, y, lpc2, graphic_in[lpc]);
}
}
}
view_colors &view_colors::singleton(void)
{
static view_colors s_vc;
return s_vc;
}
view_colors::view_colors()
: vc_next_highlight(0)
{
int lpc;
/* Setup the mappings from roles to actual colors. */
this->vc_role_colors[VCR_TEXT] = COLOR_PAIR(VC_WHITE) | A_DIM;
this->vc_role_colors[VCR_SEARCH] =
this->vc_role_colors[VCR_TEXT] | A_REVERSE;
this->vc_role_colors[VCR_OK] = COLOR_PAIR(VC_GREEN) | A_BOLD;
this->vc_role_colors[VCR_ERROR] = COLOR_PAIR(VC_RED) | A_BOLD;
this->vc_role_colors[VCR_WARNING] = COLOR_PAIR(VC_YELLOW) | A_BOLD;
this->vc_role_colors[VCR_ALT_ROW] = COLOR_PAIR(VC_WHITE) | A_BOLD;
this->vc_role_colors[VCR_STATUS] =
COLOR_PAIR(VC_BLACK_ON_WHITE);
this->vc_role_colors[VCR_WARN_STATUS] =
COLOR_PAIR(VC_YELLOW_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_ALERT_STATUS] =
COLOR_PAIR(VC_RED_ON_WHITE);
this->vc_role_colors[VCR_ACTIVE_STATUS] =
COLOR_PAIR(VC_GREEN_ON_WHITE);
this->vc_role_colors[VCR_ACTIVE_STATUS2] =
COLOR_PAIR(VC_GREEN_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_BOLD_STATUS] =
COLOR_PAIR(VC_BLACK_ON_WHITE) | A_BOLD;
this->vc_role_colors[VCR_DIFF_DELETE] = COLOR_PAIR(VC_RED);
this->vc_role_colors[VCR_DIFF_ADD] = COLOR_PAIR(VC_GREEN);
this->vc_role_colors[VCR_DIFF_SECTION] = COLOR_PAIR(VC_MAGENTA);
this->vc_role_colors[VCR_SHADOW] = COLOR_PAIR(VC_GRAY);
for (lpc = 0; lpc < VCR__MAX; lpc++) {
this->vc_role_reverse_colors[lpc] =
this->vc_role_colors[lpc] | A_REVERSE;
}
/*
* Prime the highlight vector. The first HL_COLOR_COUNT color pairs are
* assumed to be the highlight colors.
*/
for (lpc = 1; lpc <= HL_COLOR_COUNT; lpc++) {
this->vc_role_colors[VCR__MAX + (lpc - 1) * 2] = COLOR_PAIR(lpc);
this->vc_role_colors[VCR__MAX + (lpc - 1) * 2 + 1] =
COLOR_PAIR(lpc) | A_BOLD;
this->vc_role_reverse_colors[VCR__MAX + (lpc - 1) * 2] =
COLOR_PAIR(lpc + HL_COLOR_COUNT) | A_REVERSE;
this->vc_role_reverse_colors[VCR__MAX + (lpc - 1) * 2 + 1] =
COLOR_PAIR(lpc + HL_COLOR_COUNT) | A_BOLD | A_REVERSE;
}
}
void view_colors::init(void)
{
if (has_colors()) {
static int ansi_colors_to_curses[] = {
COLOR_BLACK,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW,
COLOR_BLUE,
COLOR_MAGENTA,
COLOR_CYAN,
COLOR_WHITE,
};
start_color();
/* use_default_colors(); */
init_pair(VC_BLUE, COLOR_BLUE, COLOR_BLACK);
init_pair(VC_CYAN, COLOR_CYAN, COLOR_BLACK);
init_pair(VC_GREEN, COLOR_GREEN, COLOR_BLACK);
init_pair(VC_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
init_pair(VC_BLUE_ON_WHITE, COLOR_BLUE, COLOR_WHITE);
init_pair(VC_CYAN_ON_BLACK, COLOR_CYAN, COLOR_BLACK);
init_pair(VC_CYAN_ON_WHITE, COLOR_CYAN, COLOR_WHITE);
init_pair(VC_GREEN_ON_WHITE, COLOR_GREEN, COLOR_WHITE);
init_pair(VC_MAGENTA_ON_WHITE, COLOR_MAGENTA, COLOR_WHITE);
init_pair(VC_RED, COLOR_RED, COLOR_BLACK);
init_pair(VC_YELLOW, COLOR_YELLOW, COLOR_BLACK);
init_pair(VC_WHITE, COLOR_WHITE, COLOR_BLACK);
init_pair(VC_BLACK_ON_WHITE, COLOR_BLACK, COLOR_WHITE);
init_pair(VC_RED_ON_WHITE, COLOR_RED, COLOR_WHITE);
init_pair(VC_YELLOW_ON_WHITE, COLOR_YELLOW, COLOR_WHITE);
init_pair(VC_CYAN_ON_BLUE, COLOR_CYAN, COLOR_BLUE);
init_pair(VC_WHITE_ON_GREEN, COLOR_WHITE, COLOR_GREEN);
init_pair(VC_WHITE_ON_CYAN, COLOR_WHITE, COLOR_CYAN);
init_pair(VC_GRAY, COLOR_BLACK, COLOR_BLACK);
for (int fg = 0; fg < 8; fg++) {
for (int bg = 0; bg < 8; bg++) {
init_pair(ansi_color_pair_index(fg, bg),
ansi_colors_to_curses[fg],
ansi_colors_to_curses[bg]);
}
}
for (int lpc = 0; lpc < 8; lpc++) {
short gradient_value = (1000 / 8) * lpc;
init_color(lpc + 16, gradient_value, gradient_value,
gradient_value);
init_pair(VC_GRADIENT_START + lpc, lpc + 16, COLOR_BLACK);
}
}
}
view_colors::role_t view_colors::next_highlight()
{
role_t retval = (role_t)(VCR__MAX + this->vc_next_highlight);
this->vc_next_highlight = (this->vc_next_highlight + 1) %
(HL_COLOR_COUNT * 2);
return retval;
}
view_colors::role_t view_colors::next_plain_highlight()
{
role_t retval = (role_t)(VCR__MAX + this->vc_next_plain_highlight);
this->vc_next_plain_highlight = (this->vc_next_plain_highlight + 2) %
(HL_COLOR_COUNT * 2);
return retval;
}
<|endoftext|> |
<commit_before>//*********************
// Divers
//*********************
void notifyServQuit(JsonValue * json, UserHandler * thread){
char * reponse;
}
void checkChallenge(JsonValue * json, UserHandler * thread){
char * reponse;
} //bool
void getChallengerInfo(JsonValue * json, UserHandler * thread){
char * reponse;
} //string name
void answerToChallenge(JsonValue * json, UserHandler * thread){
char * reponse;
} //code
//*********************
// Menu
//*********************
void getInfo(JsonValue * json, UserHandler * thread){
char * reponse;
} //string name int level
void getMoney(JsonValue * json, UserHandler * thread){
char * reponse;
} //int
//*********************
// ManagerPlayers
//*********************
void getInTeamPlayerList(JsonValue * json, UserHandler * thread){
char * reponse;
} // struct
void getOutOfTeamPlayerList(JsonValue * json, UserHandler * thread){
char * reponse;
} // struct
void getDataOnPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // player
void healPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // bool
void swapPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // code
//*********************
// ManageInfrastructure
//*********************
void getInfrastructureList(JsonValue * json, UserHandler * thread){
char * reponse;
}
void updateInfrastructure(JsonValue * json, UserHandler * thread){
char * reponse;
} //bool
//*********************
// AuctionHouse
//*********************
void getSellingPlayers()(JsonValue * json, UserHandler * thread){
char * reponse;
}// struct
void sell(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
void bid(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
void getRoundOnBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getRemainingTimeOnRound(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getCurrentBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getBidderCount(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void checkEndOfBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// bool
void endBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
//*********************
// ConnectedList
//*********************
void getConnectedList(JsonValue * json, UserHandler * thread){
char * reponse;
}
void challenge(JsonValue * json, UserHandler * thread){
char * reponse;
} // code<commit_msg>[code/views] Added getInfo end getMoney code<commit_after>//*********************
// Divers
//*********************
void notifyServQuit(JsonValue * json, UserHandler * thread){
char * reponse;
}
void checkChallenge(JsonValue * json, UserHandler * thread){
char * reponse;
} //bool
void getChallengerInfo(JsonValue * json, UserHandler * thread){
char * reponse;
} //string name
void answerToChallenge(JsonValue * json, UserHandler * thread){
char * reponse;
} //code
//*********************
// Menu
//*********************
void getInfo(JsonValue * json, UserHandler * thread){
std::string values = "{";
Manager * user = thread->getManager();
values += "name : " + (std::string) user->getUserName() + ", ";
values += "level : " + (std::string) user->getClub()->getLevel();
values += "}";
writeToClient(values);
} //string name int level
void getMoney(JsonValue * json, UserHandler * thread){
std::string value = "{money : ";
value += thread->getManager()->getClub()->getMoney();
writeToClient(value);
} //int
//*********************
// ManagerPlayers
//*********************
void getInTeamPlayerList(JsonValue * json, UserHandler * thread){
char * reponse;
} // struct
void getOutOfTeamPlayerList(JsonValue * json, UserHandler * thread){
char * reponse;
} // struct
void getDataOnPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // player
void healPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // bool
void swapPlayer(JsonValue * json, UserHandler * thread){
char * reponse;
} // code
//*********************
// ManageInfrastructure
//*********************
void getInfrastructureList(JsonValue * json, UserHandler * thread){
char * reponse;
}
void updateInfrastructure(JsonValue * json, UserHandler * thread){
char * reponse;
} //bool
//*********************
// AuctionHouse
//*********************
void getSellingPlayers()(JsonValue * json, UserHandler * thread){
char * reponse;
}// struct
void sell(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
void bid(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
void getRoundOnBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getRemainingTimeOnRound(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getCurrentBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void getBidderCount(JsonValue * json, UserHandler * thread){
char * reponse;
}// int
void checkEndOfBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// bool
void endBid(JsonValue * json, UserHandler * thread){
char * reponse;
}// code
//*********************
// ConnectedList
//*********************
void getConnectedList(JsonValue * json, UserHandler * thread){
char * reponse;
}
void challenge(JsonValue * json, UserHandler * thread){
char * reponse;
} // code<|endoftext|> |
<commit_before>#ifndef QTL_ESTIMATOR_CONFIG_HPP_
#define QTL_ESTIMATOR_CONFIG_HPP_
#include <boost/mpl/aux_/na.hpp>
#ifdef USE_VECTOR_SUBSET
#include "clotho/powerset/vector_subset.hpp"
#define SUBSETTYPE clotho::powersets::vector_subset
#include "clotho/recombination/inspect_methods.hpp"
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::copy_matching_classify_mismatch
#define BIT_WALK_METHOD boost::mpl::na
#else // ! USE_VECTOR_SUBSET
#include "clotho/powerset/variable_subset.hpp"
#define SUBSETTYPE clotho::powersets::variable_subset
#if defined( USE_SCAN_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::scan_and_classify
#elif defined( USE_SCAN_AND_CLASSIFY_SWITCH )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::scan_and_classify_switch
#elif defined( USE_INLINE_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::inline_classify
#elif defined( USE_INLINE_DYNAMIC_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::inline_dynamic_classify
#else // default is to perform classification inline
#define BIT_WALK_METHOD clotho::recombine::walker::tag::iterate_and_classify
#endif // classification procedure
#if defined( USE_INSPECT_ALL )
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::classify_all
#else
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::copy_matching_classify_mismatch
#endif // USE_INSPECT_ALL
#endif // USE_VECTOR_SUBSET
#include "clotho/utility/random_generator.hpp"
#ifdef USE_BERNOULLI_RECOMB
#include "clotho/classifiers/bernoulli_classifier_generator.hpp"
#define RECOMBTYPE clotho::classifiers::bernoulli_classifier< rng_type, double, bool>
#else
#include "clotho/classifiers/region_classifier.hpp"
#define RECOMBTYPE clotho::classifiers::region_classifier< allele_type >
#endif // USE_BERNOULLI_RECOMB
#ifdef USE_BLOCK_SIZE_32
#define BLOCK_UNIT_TYPE unsigned int
#define BLOCK_UNIT_SIZE 32
#else
#define BLOCK_UNIT_TYPE unsigned long
#define BLOCK_UNIT_SIZE 64
#endif // USE_BLOCK_SIZE_32
#endif // QTL_ESTIMATOR_CONFIG_HPP_
<commit_msg>Added preprocessor define to control which reproduction method to follow<commit_after>#ifndef QTL_ESTIMATOR_CONFIG_HPP_
#define QTL_ESTIMATOR_CONFIG_HPP_
#include <boost/mpl/aux_/na.hpp>
#ifdef USE_VECTOR_SUBSET
#include "clotho/powerset/vector_subset.hpp"
#define SUBSETTYPE clotho::powersets::vector_subset
#include "clotho/recombination/inspect_methods.hpp"
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::copy_matching_classify_mismatch
#define BIT_WALK_METHOD boost::mpl::na
#else // ! USE_VECTOR_SUBSET
#include "clotho/powerset/variable_subset.hpp"
#define SUBSETTYPE clotho::powersets::variable_subset
#if defined( USE_SCAN_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::scan_and_classify
#elif defined( USE_SCAN_AND_CLASSIFY_SWITCH )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::scan_and_classify_switch
#elif defined( USE_INLINE_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::inline_classify
#elif defined( USE_INLINE_DYNAMIC_AND_CLASSIFY )
#define BIT_WALK_METHOD clotho::recombine::walker::tag::inline_dynamic_classify
#else // default is to perform classification inline
#define BIT_WALK_METHOD clotho::recombine::walker::tag::iterate_and_classify
#endif // classification procedure
#if defined( USE_INSPECT_ALL )
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::classify_all
#else
#define RECOMBINE_INSPECT_METHOD clotho::recombine::inspection::tag::copy_matching_classify_mismatch
#endif // USE_INSPECT_ALL
#endif // USE_VECTOR_SUBSET
#include "clotho/utility/random_generator.hpp"
#ifdef USE_BERNOULLI_RECOMB
#include "clotho/classifiers/bernoulli_classifier_generator.hpp"
#define RECOMBTYPE clotho::classifiers::bernoulli_classifier< rng_type, double, bool>
#else
#include "clotho/classifiers/region_classifier.hpp"
#define RECOMBTYPE clotho::classifiers::region_classifier< allele_type >
#endif // USE_BERNOULLI_RECOMB
#ifdef USE_MUTATE_AND_RECOMBINE
#define REPRODUCTION_METHOD_TAG mutate_recombine_tag
#else
#define REPRODUCTION_METHOD_TAG recombine_mutate_tag
#endif //MUTATE_AND_RECOMBINE
#ifdef USE_BLOCK_SIZE_32
#define BLOCK_UNIT_TYPE unsigned int
#define BLOCK_UNIT_SIZE 32
#else
#define BLOCK_UNIT_TYPE unsigned long
#define BLOCK_UNIT_SIZE 64
#endif // USE_BLOCK_SIZE_32
#endif // QTL_ESTIMATOR_CONFIG_HPP_
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/queue.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-eventdb/TableRepository.h"
#include "fnord-eventdb/LogTableTail.h"
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessagePrinter.h"
#include "logjoin/LogJoinBackfill.h"
#include "IndexReader.h"
#include "common.h"
#include "schemas.h"
using namespace cm;
using namespace fnord;
fnord::thread::EventLoop ev;
std::atomic<bool> cm_logjoin_shutdown;
void quit(int n) {
cm_logjoin_shutdown = true;
}
struct BackfillData {
Option<String> shop_name;
Option<String> shop_id;
Option<uint64_t> category1;
Option<uint64_t> category2;
Option<uint64_t> category3;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
cm_logjoin_shutdown = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"datadir",
"<path>");
flags.defineFlag(
"feedserver_addr",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"http://localhost:8000",
"feedserver addr",
"<addr>");
flags.defineFlag(
"batch_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"2048",
"batch_size",
"<num>");
flags.defineFlag(
"worker_threads",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"4",
"threads",
"<num>");
flags.defineFlag(
"upload_threads",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"1",
"threads",
"<num>");
flags.defineFlag(
"no_dryrun",
fnord::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"no_dryrun",
fnord::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* args */
auto index_path = flags.getString("index");
auto batch_size = flags.getInt("batch_size");
auto datadir = flags.getString("datadir");
auto dry_run = !flags.isSet("no_dryrun");
if (!FileUtil::isDirectory(datadir)) {
RAISEF(kIOError, "no such directory: $0", datadir);
}
URI target_uri("http://localhost:8000/eventdb/insert?table=joined_sessions-dawanda");
/* event loop, http */
http::HTTPConnectionPool http(&ev);
auto evloop_thread = std::thread([] {
ev.run();
});
/* open index */
auto index = cm::IndexReader::openIndex(index_path);
/* open table */
auto schema = joinedSessionsSchema();
auto table = eventdb::TableReader::open(
"dawanda_joined_sessions",
flags.getString("replica"),
datadir,
schema);
auto queries_fid = schema.id("queries");
auto queryitems_fid = schema.id("queries.items");
auto qi_id_fid = schema.id("queries.items.item_id");
auto qi_sid_fid = schema.id("queries.items.shop_id");
auto qi_sname_fid = schema.id("queries.items.shop_name");
auto qi_c1_fid = schema.id("queries.items.category1");
auto qi_c2_fid = schema.id("queries.items.category2");
auto qi_c3_fid = schema.id("queries.items.category3");
HashMap<String, BackfillData> cache;
/* backfill fn */
auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {
auto cached = cache.find(item_id);
if (!(cached == cache.end())) {
return cached->second;
}
BackfillData data;
DocID docid { .docid = item_id };
data.shop_id = index->docIndex()->getField(docid, "shop_id");
data.shop_name = index->docIndex()->getField(docid, "shop_name");
auto category1 = index->docIndex()->getField(docid, "category1");
if (!category1.isEmpty()) {
data.category1 = Some((uint64_t) std::stoull(category1.get()));
}
auto category2 = index->docIndex()->getField(docid, "category2");
if (!category2.isEmpty()) {
data.category2 = Some((uint64_t) std::stoull(category2.get()));
}
auto category3 = index->docIndex()->getField(docid, "category3");
if (!category3.isEmpty()) {
data.category3 = Some((uint64_t) std::stoull(category3.get()));
}
cache[item_id] = data;
return data;
};
auto backfill_fn = [
&schema,
&queries_fid,
&queryitems_fid,
&qi_id_fid,
&qi_sid_fid,
&qi_sname_fid,
&qi_c1_fid,
&qi_c2_fid,
&qi_c3_fid,
&get_backfill_data
] (msg::MessageObject* record) {
auto msg = msg::MessagePrinter::print(*record, schema);
for (auto& q : record->asObject()) {
if (q.id != queries_fid) {
continue;
}
for (auto& qi : q.asObject()) {
if (qi.id != queryitems_fid) {
continue;
}
String item_id;
for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {
auto id = cur->id;
if (id == qi_id_fid) {
item_id = cur->asString();
++cur;
} else if (
id == qi_sid_fid ||
id == qi_sname_fid ||
id == qi_c1_fid ||
id == qi_c2_fid ||
id == qi_c3_fid) {
cur = qi.asObject().erase(cur);
} else {
++cur;
}
}
auto bdata = get_backfill_data(item_id);
if (!bdata.shop_id.isEmpty()) {
qi.addChild(qi_sid_fid, bdata.shop_id.get());
}
if (!bdata.shop_name.isEmpty()) {
qi.addChild(qi_sname_fid, bdata.shop_name.get());
}
if (!bdata.category1.isEmpty()) {
qi.addChild(qi_c1_fid, bdata.category1.get());
}
if (!bdata.category2.isEmpty()) {
qi.addChild(qi_c2_fid, bdata.category2.get());
}
if (!bdata.category3.isEmpty()) {
qi.addChild(qi_c3_fid, bdata.category3.get());
}
}
}
fnord::iputs("backfill: $0", msg);
};
/* run backfill */
cm::LogJoinBackfill backfill(
table,
backfill_fn,
"/tmp/logjoin-backfill-state",
dry_run,
target_uri,
&http);
backfill.start();
while (backfill.process(batch_size)) {
if (cm_logjoin_shutdown.load()) {
break;
}
}
backfill.shutdown();
ev.shutdown();
evloop_thread.join();
return 0;
}
<commit_msg>print backfilled record<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/thread/queue.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-eventdb/TableRepository.h"
#include "fnord-eventdb/LogTableTail.h"
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessagePrinter.h"
#include "logjoin/LogJoinBackfill.h"
#include "IndexReader.h"
#include "common.h"
#include "schemas.h"
using namespace cm;
using namespace fnord;
fnord::thread::EventLoop ev;
std::atomic<bool> cm_logjoin_shutdown;
void quit(int n) {
cm_logjoin_shutdown = true;
}
struct BackfillData {
Option<String> shop_name;
Option<String> shop_id;
Option<uint64_t> category1;
Option<uint64_t> category2;
Option<uint64_t> category3;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
cm_logjoin_shutdown = false;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
fnord::cli::FlagParser flags;
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"datadir",
"<path>");
flags.defineFlag(
"feedserver_addr",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"http://localhost:8000",
"feedserver addr",
"<addr>");
flags.defineFlag(
"batch_size",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"2048",
"batch_size",
"<num>");
flags.defineFlag(
"worker_threads",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"4",
"threads",
"<num>");
flags.defineFlag(
"upload_threads",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"1",
"threads",
"<num>");
flags.defineFlag(
"no_dryrun",
fnord::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"no_dryrun",
fnord::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
/* args */
auto index_path = flags.getString("index");
auto batch_size = flags.getInt("batch_size");
auto datadir = flags.getString("datadir");
auto dry_run = !flags.isSet("no_dryrun");
if (!FileUtil::isDirectory(datadir)) {
RAISEF(kIOError, "no such directory: $0", datadir);
}
URI target_uri("http://localhost:8000/eventdb/insert?table=joined_sessions-dawanda");
/* event loop, http */
http::HTTPConnectionPool http(&ev);
auto evloop_thread = std::thread([] {
ev.run();
});
/* open index */
auto index = cm::IndexReader::openIndex(index_path);
/* open table */
auto schema = joinedSessionsSchema();
auto table = eventdb::TableReader::open(
"dawanda_joined_sessions",
flags.getString("replica"),
datadir,
schema);
auto queries_fid = schema.id("queries");
auto queryitems_fid = schema.id("queries.items");
auto qi_id_fid = schema.id("queries.items.item_id");
auto qi_sid_fid = schema.id("queries.items.shop_id");
auto qi_sname_fid = schema.id("queries.items.shop_name");
auto qi_c1_fid = schema.id("queries.items.category1");
auto qi_c2_fid = schema.id("queries.items.category2");
auto qi_c3_fid = schema.id("queries.items.category3");
HashMap<String, BackfillData> cache;
/* backfill fn */
auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {
auto cached = cache.find(item_id);
if (!(cached == cache.end())) {
return cached->second;
}
BackfillData data;
DocID docid { .docid = item_id };
data.shop_id = index->docIndex()->getField(docid, "shop_id");
data.shop_name = index->docIndex()->getField(docid, "shop_name");
auto category1 = index->docIndex()->getField(docid, "category1");
if (!category1.isEmpty()) {
data.category1 = Some((uint64_t) std::stoull(category1.get()));
}
auto category2 = index->docIndex()->getField(docid, "category2");
if (!category2.isEmpty()) {
data.category2 = Some((uint64_t) std::stoull(category2.get()));
}
auto category3 = index->docIndex()->getField(docid, "category3");
if (!category3.isEmpty()) {
data.category3 = Some((uint64_t) std::stoull(category3.get()));
}
cache[item_id] = data;
return data;
};
auto backfill_fn = [
&schema,
&queries_fid,
&queryitems_fid,
&qi_id_fid,
&qi_sid_fid,
&qi_sname_fid,
&qi_c1_fid,
&qi_c2_fid,
&qi_c3_fid,
&get_backfill_data
] (msg::MessageObject* record) {
for (auto& q : record->asObject()) {
if (q.id != queries_fid) {
continue;
}
for (auto& qi : q.asObject()) {
if (qi.id != queryitems_fid) {
continue;
}
String item_id;
for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {
auto id = cur->id;
if (id == qi_id_fid) {
item_id = cur->asString();
++cur;
} else if (
id == qi_sid_fid ||
id == qi_sname_fid ||
id == qi_c1_fid ||
id == qi_c2_fid ||
id == qi_c3_fid) {
cur = qi.asObject().erase(cur);
} else {
++cur;
}
}
auto bdata = get_backfill_data(item_id);
if (!bdata.shop_id.isEmpty()) {
qi.addChild(qi_sid_fid, bdata.shop_id.get());
}
if (!bdata.shop_name.isEmpty()) {
qi.addChild(qi_sname_fid, bdata.shop_name.get());
}
if (!bdata.category1.isEmpty()) {
qi.addChild(qi_c1_fid, bdata.category1.get());
}
if (!bdata.category2.isEmpty()) {
qi.addChild(qi_c2_fid, bdata.category2.get());
}
if (!bdata.category3.isEmpty()) {
qi.addChild(qi_c3_fid, bdata.category3.get());
}
}
}
auto msg = msg::MessagePrinter::print(*record, schema);
fnord::iputs("backfill: $0", msg);
};
/* run backfill */
cm::LogJoinBackfill backfill(
table,
backfill_fn,
"/tmp/logjoin-backfill-state",
dry_run,
target_uri,
&http);
backfill.start();
while (backfill.process(batch_size)) {
if (cm_logjoin_shutdown.load()) {
break;
}
}
backfill.shutdown();
ev.shutdown();
evloop_thread.join();
return 0;
}
<|endoftext|> |
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* 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: geom/IntersectionMatrix.java rev. 1.18
*
**********************************************************************/
#include <geos/geom/IntersectionMatrix.h>
#include <geos/geom/Dimension.h>
#include <geos/geom/Location.h>
#include <geos/util/IllegalArgumentException.h>
#include <sstream>
#include <cassert>
using namespace std;
namespace geos {
namespace geom { // geos::geom
const int IntersectionMatrix::firstDim = 3;
const int IntersectionMatrix::secondDim = 3;
/*public*/
IntersectionMatrix::IntersectionMatrix()
{
//matrix = new int[3][3];
setAll(Dimension::False);
}
/*public*/
IntersectionMatrix::IntersectionMatrix(const string& elements)
{
setAll(Dimension::False);
set(elements);
}
/*public*/
IntersectionMatrix::IntersectionMatrix(const IntersectionMatrix& other)
{
matrix[Location::INTERIOR][Location::INTERIOR] = other.matrix[Location::INTERIOR][Location::INTERIOR];
matrix[Location::INTERIOR][Location::BOUNDARY] = other.matrix[Location::INTERIOR][Location::BOUNDARY];
matrix[Location::INTERIOR][Location::EXTERIOR] = other.matrix[Location::INTERIOR][Location::EXTERIOR];
matrix[Location::BOUNDARY][Location::INTERIOR] = other.matrix[Location::BOUNDARY][Location::INTERIOR];
matrix[Location::BOUNDARY][Location::BOUNDARY] = other.matrix[Location::BOUNDARY][Location::BOUNDARY];
matrix[Location::BOUNDARY][Location::EXTERIOR] = other.matrix[Location::BOUNDARY][Location::EXTERIOR];
matrix[Location::EXTERIOR][Location::INTERIOR] = other.matrix[Location::EXTERIOR][Location::INTERIOR];
matrix[Location::EXTERIOR][Location::BOUNDARY] = other.matrix[Location::EXTERIOR][Location::BOUNDARY];
matrix[Location::EXTERIOR][Location::EXTERIOR] = other.matrix[Location::EXTERIOR][Location::EXTERIOR];
}
/*public*/
void
IntersectionMatrix::add(IntersectionMatrix* other)
{
for(int i = 0; i < firstDim; i++) {
for(int j = 0; j < secondDim; j++) {
setAtLeast(i, j, other->get(i, j));
}
}
}
/*public*/
bool
IntersectionMatrix::matches(const string& requiredDimensionSymbols) const
{
if (requiredDimensionSymbols.length() != 9) {
ostringstream s;
s << "IllegalArgumentException: Should be length 9, is "
<< "[" << requiredDimensionSymbols << "] instead" << endl;
throw util::IllegalArgumentException(s.str());
}
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
if (!matches(matrix[ai][bi],requiredDimensionSymbols[3*ai+bi])) {
return false;
}
}
}
return true;
}
/*public static*/
bool
IntersectionMatrix::matches(int actualDimensionValue,
char requiredDimensionSymbol)
{
if (requiredDimensionSymbol=='*') return true;
if (requiredDimensionSymbol=='T' && (actualDimensionValue >= 0 ||
actualDimensionValue==Dimension::True))
{
return true;
}
if (requiredDimensionSymbol=='F' &&
actualDimensionValue==Dimension::False)
{
return true;
}
if (requiredDimensionSymbol=='0' &&
actualDimensionValue==Dimension::P)
{
return true;
}
if (requiredDimensionSymbol=='1' &&
actualDimensionValue==Dimension::L)
{
return true;
}
if (requiredDimensionSymbol=='2' &&
actualDimensionValue==Dimension::A)
{
return true;
}
return false;
}
/*public static*/
bool
IntersectionMatrix::matches(const string& actualDimensionSymbols,
const string& requiredDimensionSymbols)
{
IntersectionMatrix m(actualDimensionSymbols);
bool result=m.matches(requiredDimensionSymbols);
return result;
}
/*public*/
void
IntersectionMatrix::set(int row, int col, int dimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
matrix[row][col] = dimensionValue;
}
/*public*/
void
IntersectionMatrix::set(const string& dimensionSymbols)
{
size_t limit = dimensionSymbols.length();
for (size_t i = 0; i < limit; i++)
{
int row = i / firstDim;
int col = i % secondDim;
matrix[row][col] = Dimension::toDimensionValue(dimensionSymbols[i]);
}
}
/*public*/
void
IntersectionMatrix::setAtLeast(int row, int col, int minimumDimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
if (matrix[row][col] < minimumDimensionValue)
{
matrix[row][col] = minimumDimensionValue;
}
}
/*public*/
void
IntersectionMatrix::setAtLeastIfValid(int row, int col, int minimumDimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
if (row >= 0 && col >= 0)
{
setAtLeast(row, col, minimumDimensionValue);
}
}
/*public*/
void
IntersectionMatrix::setAtLeast(string minimumDimensionSymbols)
{
size_t limit = minimumDimensionSymbols.length();
for (size_t i = 0; i < limit; i++)
{
int row = i / firstDim;
int col = i % secondDim;
setAtLeast(row, col, Dimension::toDimensionValue(minimumDimensionSymbols[i]));
}
}
/*public*/
void
IntersectionMatrix::setAll(int dimensionValue)
{
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
matrix[ai][bi] = dimensionValue;
}
}
}
/*public*/
int
IntersectionMatrix::get(int row, int col) const
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
return matrix[row][col];
}
/*public*/
bool
IntersectionMatrix::isDisjoint() const
{
return
matrix[Location::INTERIOR][Location::INTERIOR]==Dimension::False
&&
matrix[Location::INTERIOR][Location::BOUNDARY]==Dimension::False
&&
matrix[Location::BOUNDARY][Location::INTERIOR]==Dimension::False
&&
matrix[Location::BOUNDARY][Location::BOUNDARY]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isIntersects() const
{
return !isDisjoint();
}
/*public*/
bool
IntersectionMatrix::isTouches(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if (dimensionOfGeometryA > dimensionOfGeometryB)
{
//no need to get transpose because pattern matrix is symmetrical
return isTouches(dimensionOfGeometryB, dimensionOfGeometryA);
}
if ((dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L)
||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::L))
{
return matrix[Location::INTERIOR][Location::INTERIOR]==Dimension::False &&
(matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T') ||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T') ||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T'));
}
return false;
}
/*public*/
bool
IntersectionMatrix::isCrosses(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if ((dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::L) ||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::A) ||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::A)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T');
}
if ((dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::L)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR], 'T');
}
if (dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L) {
return matrix[Location::INTERIOR][Location::INTERIOR]==0;
}
return false;
}
/*public*/
bool
IntersectionMatrix::isWithin() const
{
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::INTERIOR][Location::EXTERIOR]==Dimension::False &&
matrix[Location::BOUNDARY][Location::EXTERIOR]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isContains() const
{
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::EXTERIOR][Location::INTERIOR]==Dimension::False &&
matrix[Location::EXTERIOR][Location::BOUNDARY]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isEquals(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if (dimensionOfGeometryA != dimensionOfGeometryB) {
return false;
}
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::EXTERIOR][Location::INTERIOR]==Dimension::False &&
matrix[Location::INTERIOR][Location::EXTERIOR]==Dimension::False &&
matrix[Location::EXTERIOR][Location::BOUNDARY]==Dimension::False &&
matrix[Location::BOUNDARY][Location::EXTERIOR]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isOverlaps(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if ((dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::A)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR],'T');
}
if (dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L) {
return matrix[Location::INTERIOR][Location::INTERIOR]==1 &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR], 'T');
}
return false;
}
/*public*/
bool
IntersectionMatrix::isCovers() const
{
bool hasPointInCommon =
matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T')
||
matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T')
||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T')
||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T');
return hasPointInCommon
&&
matrix[Location::EXTERIOR][Location::INTERIOR] ==
Dimension::False
&&
matrix[Location::EXTERIOR][Location::BOUNDARY] ==
Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isCoveredBy() const
{
bool hasPointInCommon =
matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T')
||
matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T')
||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T')
||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T');
return
hasPointInCommon
&&
matrix[Location::INTERIOR][Location::EXTERIOR] ==
Dimension::False
&&
matrix[Location::BOUNDARY][Location::EXTERIOR] ==
Dimension::False;
}
//Not sure
IntersectionMatrix*
IntersectionMatrix::transpose()
{
int temp = matrix[1][0];
matrix[1][0] = matrix[0][1];
matrix[0][1] = temp;
temp = matrix[2][0];
matrix[2][0] = matrix[0][2];
matrix[0][2] = temp;
temp = matrix[2][1];
matrix[2][1] = matrix[1][2];
matrix[1][2] = temp;
return this;
}
/*public*/
string
IntersectionMatrix::toString() const
{
string result("");
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
result += Dimension::toDimensionSymbol(matrix[ai][bi]);
}
}
return result;
}
std::ostream&
operator<< (std::ostream&os, const IntersectionMatrix& im)
{
return os << im.toString();
}
} // namespace geos::geom
} // namespace geos
<commit_msg>Fix warning: conversion from size_t to int<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* 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: geom/IntersectionMatrix.java rev. 1.18
*
**********************************************************************/
#include <geos/geom/IntersectionMatrix.h>
#include <geos/geom/Dimension.h>
#include <geos/geom/Location.h>
#include <geos/util/IllegalArgumentException.h>
#include <sstream>
#include <cassert>
using namespace std;
namespace geos {
namespace geom { // geos::geom
const int IntersectionMatrix::firstDim = 3;
const int IntersectionMatrix::secondDim = 3;
/*public*/
IntersectionMatrix::IntersectionMatrix()
{
//matrix = new int[3][3];
setAll(Dimension::False);
}
/*public*/
IntersectionMatrix::IntersectionMatrix(const string& elements)
{
setAll(Dimension::False);
set(elements);
}
/*public*/
IntersectionMatrix::IntersectionMatrix(const IntersectionMatrix& other)
{
matrix[Location::INTERIOR][Location::INTERIOR] = other.matrix[Location::INTERIOR][Location::INTERIOR];
matrix[Location::INTERIOR][Location::BOUNDARY] = other.matrix[Location::INTERIOR][Location::BOUNDARY];
matrix[Location::INTERIOR][Location::EXTERIOR] = other.matrix[Location::INTERIOR][Location::EXTERIOR];
matrix[Location::BOUNDARY][Location::INTERIOR] = other.matrix[Location::BOUNDARY][Location::INTERIOR];
matrix[Location::BOUNDARY][Location::BOUNDARY] = other.matrix[Location::BOUNDARY][Location::BOUNDARY];
matrix[Location::BOUNDARY][Location::EXTERIOR] = other.matrix[Location::BOUNDARY][Location::EXTERIOR];
matrix[Location::EXTERIOR][Location::INTERIOR] = other.matrix[Location::EXTERIOR][Location::INTERIOR];
matrix[Location::EXTERIOR][Location::BOUNDARY] = other.matrix[Location::EXTERIOR][Location::BOUNDARY];
matrix[Location::EXTERIOR][Location::EXTERIOR] = other.matrix[Location::EXTERIOR][Location::EXTERIOR];
}
/*public*/
void
IntersectionMatrix::add(IntersectionMatrix* other)
{
for(int i = 0; i < firstDim; i++) {
for(int j = 0; j < secondDim; j++) {
setAtLeast(i, j, other->get(i, j));
}
}
}
/*public*/
bool
IntersectionMatrix::matches(const string& requiredDimensionSymbols) const
{
if (requiredDimensionSymbols.length() != 9) {
ostringstream s;
s << "IllegalArgumentException: Should be length 9, is "
<< "[" << requiredDimensionSymbols << "] instead" << endl;
throw util::IllegalArgumentException(s.str());
}
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
if (!matches(matrix[ai][bi],requiredDimensionSymbols[3*ai+bi])) {
return false;
}
}
}
return true;
}
/*public static*/
bool
IntersectionMatrix::matches(int actualDimensionValue,
char requiredDimensionSymbol)
{
if (requiredDimensionSymbol=='*') return true;
if (requiredDimensionSymbol=='T' && (actualDimensionValue >= 0 ||
actualDimensionValue==Dimension::True))
{
return true;
}
if (requiredDimensionSymbol=='F' &&
actualDimensionValue==Dimension::False)
{
return true;
}
if (requiredDimensionSymbol=='0' &&
actualDimensionValue==Dimension::P)
{
return true;
}
if (requiredDimensionSymbol=='1' &&
actualDimensionValue==Dimension::L)
{
return true;
}
if (requiredDimensionSymbol=='2' &&
actualDimensionValue==Dimension::A)
{
return true;
}
return false;
}
/*public static*/
bool
IntersectionMatrix::matches(const string& actualDimensionSymbols,
const string& requiredDimensionSymbols)
{
IntersectionMatrix m(actualDimensionSymbols);
bool result=m.matches(requiredDimensionSymbols);
return result;
}
/*public*/
void
IntersectionMatrix::set(int row, int col, int dimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
matrix[row][col] = dimensionValue;
}
/*public*/
void
IntersectionMatrix::set(const string& dimensionSymbols)
{
size_t limit = dimensionSymbols.length();
for (int i = 0; i < static_cast<int>(limit); i++)
{
int row = i / firstDim;
int col = i % secondDim;
matrix[row][col] = Dimension::toDimensionValue(dimensionSymbols[i]);
}
}
/*public*/
void
IntersectionMatrix::setAtLeast(int row, int col, int minimumDimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
if (matrix[row][col] < minimumDimensionValue)
{
matrix[row][col] = minimumDimensionValue;
}
}
/*public*/
void
IntersectionMatrix::setAtLeastIfValid(int row, int col, int minimumDimensionValue)
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
if (row >= 0 && col >= 0)
{
setAtLeast(row, col, minimumDimensionValue);
}
}
/*public*/
void
IntersectionMatrix::setAtLeast(string minimumDimensionSymbols)
{
size_t limit = minimumDimensionSymbols.length();
for (int i = 0; i < static_cast<int>(limit); i++)
{
int row = i / firstDim;
int col = i % secondDim;
setAtLeast(row, col, Dimension::toDimensionValue(minimumDimensionSymbols[i]));
}
}
/*public*/
void
IntersectionMatrix::setAll(int dimensionValue)
{
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
matrix[ai][bi] = dimensionValue;
}
}
}
/*public*/
int
IntersectionMatrix::get(int row, int col) const
{
assert( row >= 0 && row < firstDim );
assert( col >= 0 && col < secondDim );
return matrix[row][col];
}
/*public*/
bool
IntersectionMatrix::isDisjoint() const
{
return
matrix[Location::INTERIOR][Location::INTERIOR]==Dimension::False
&&
matrix[Location::INTERIOR][Location::BOUNDARY]==Dimension::False
&&
matrix[Location::BOUNDARY][Location::INTERIOR]==Dimension::False
&&
matrix[Location::BOUNDARY][Location::BOUNDARY]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isIntersects() const
{
return !isDisjoint();
}
/*public*/
bool
IntersectionMatrix::isTouches(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if (dimensionOfGeometryA > dimensionOfGeometryB)
{
//no need to get transpose because pattern matrix is symmetrical
return isTouches(dimensionOfGeometryB, dimensionOfGeometryA);
}
if ((dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L)
||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::A)
||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::L))
{
return matrix[Location::INTERIOR][Location::INTERIOR]==Dimension::False &&
(matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T') ||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T') ||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T'));
}
return false;
}
/*public*/
bool
IntersectionMatrix::isCrosses(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if ((dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::L) ||
(dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::A) ||
(dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::A)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T');
}
if ((dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::L)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR], 'T');
}
if (dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L) {
return matrix[Location::INTERIOR][Location::INTERIOR]==0;
}
return false;
}
/*public*/
bool
IntersectionMatrix::isWithin() const
{
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::INTERIOR][Location::EXTERIOR]==Dimension::False &&
matrix[Location::BOUNDARY][Location::EXTERIOR]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isContains() const
{
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::EXTERIOR][Location::INTERIOR]==Dimension::False &&
matrix[Location::EXTERIOR][Location::BOUNDARY]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isEquals(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if (dimensionOfGeometryA != dimensionOfGeometryB) {
return false;
}
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matrix[Location::EXTERIOR][Location::INTERIOR]==Dimension::False &&
matrix[Location::INTERIOR][Location::EXTERIOR]==Dimension::False &&
matrix[Location::EXTERIOR][Location::BOUNDARY]==Dimension::False &&
matrix[Location::BOUNDARY][Location::EXTERIOR]==Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isOverlaps(int dimensionOfGeometryA,
int dimensionOfGeometryB) const
{
if ((dimensionOfGeometryA==Dimension::P && dimensionOfGeometryB==Dimension::P) ||
(dimensionOfGeometryA==Dimension::A && dimensionOfGeometryB==Dimension::A)) {
return matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T') &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR],'T');
}
if (dimensionOfGeometryA==Dimension::L && dimensionOfGeometryB==Dimension::L) {
return matrix[Location::INTERIOR][Location::INTERIOR]==1 &&
matches(matrix[Location::INTERIOR][Location::EXTERIOR], 'T') &&
matches(matrix[Location::EXTERIOR][Location::INTERIOR], 'T');
}
return false;
}
/*public*/
bool
IntersectionMatrix::isCovers() const
{
bool hasPointInCommon =
matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T')
||
matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T')
||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T')
||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T');
return hasPointInCommon
&&
matrix[Location::EXTERIOR][Location::INTERIOR] ==
Dimension::False
&&
matrix[Location::EXTERIOR][Location::BOUNDARY] ==
Dimension::False;
}
/*public*/
bool
IntersectionMatrix::isCoveredBy() const
{
bool hasPointInCommon =
matches(matrix[Location::INTERIOR][Location::INTERIOR], 'T')
||
matches(matrix[Location::INTERIOR][Location::BOUNDARY], 'T')
||
matches(matrix[Location::BOUNDARY][Location::INTERIOR], 'T')
||
matches(matrix[Location::BOUNDARY][Location::BOUNDARY], 'T');
return
hasPointInCommon
&&
matrix[Location::INTERIOR][Location::EXTERIOR] ==
Dimension::False
&&
matrix[Location::BOUNDARY][Location::EXTERIOR] ==
Dimension::False;
}
//Not sure
IntersectionMatrix*
IntersectionMatrix::transpose()
{
int temp = matrix[1][0];
matrix[1][0] = matrix[0][1];
matrix[0][1] = temp;
temp = matrix[2][0];
matrix[2][0] = matrix[0][2];
matrix[0][2] = temp;
temp = matrix[2][1];
matrix[2][1] = matrix[1][2];
matrix[1][2] = temp;
return this;
}
/*public*/
string
IntersectionMatrix::toString() const
{
string result("");
for (int ai = 0; ai < firstDim; ai++) {
for (int bi = 0; bi < secondDim; bi++) {
result += Dimension::toDimensionSymbol(matrix[ai][bi]);
}
}
return result;
}
std::ostream&
operator<< (std::ostream&os, const IntersectionMatrix& im)
{
return os << im.toString();
}
} // namespace geos::geom
} // namespace geos
<|endoftext|> |
<commit_before>/*
* Copyright 2017 resin.io
*
* 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 "src/windows/com.h"
#include "src/log.h"
HRESULT drivelist::com::Initialize() {
HRESULT result;
drivelist::Debug("Initializing COM");
result = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(result))
return result;
drivelist::Debug("Initializing COM security levels");
result = CoInitializeSecurity(
NULL, // Security descriptor
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL); // Reserved
if (FAILED(result)) {
drivelist::com::Uninitialize();
}
return result;
}
void drivelist::com::Uninitialize() { CoUninitialize(); }
drivelist::com::Connection::Connection() {
this->locator = NULL;
this->proxy = NULL;
}
drivelist::com::Connection::~Connection() {
if (this->proxy != NULL)
this->proxy->Release();
if (this->locator != NULL)
this->locator->Release();
}
HRESULT drivelist::com::Connection::Connect(const LPCWSTR server) {
drivelist::Debug("Connecting to server");
const HRESULT result = this->locator->ConnectServer(
_bstr_t(server), // Path to server
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&this->proxy); // pointer to IWbemServices proxy
if (FAILED(result)) {
return result;
}
drivelist::Debug("Setting proxy security levels");
return CoSetProxyBlanket(
this->proxy, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE); // proxy capabilities
}
HRESULT drivelist::com::Connection::CreateInstance() {
drivelist::Debug("Creating connection instance");
return CoCreateInstance(
CLSID_WbemLocator,
NULL, // Not being created as part of an aggregate
// The COM instance context
//
// From https://msdn.microsoft.com/en-us/library/windows/desktop/ms693716(v=vs.85).aspx
//
// > The code that creates and manages objects of this class
// > is a DLL that runs in the same process as the caller of
// > the function specifying the class context.
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
reinterpret_cast<LPVOID *>(&this->locator));
}
HRESULT
drivelist::com::Connection::ExecuteWQLQuery(const BSTR query,
IEnumWbemClassObject **enumerator) {
return this->proxy->ExecQuery(
bstr_t("WQL"),
query,
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
enumerator);
}
<commit_msg>fix(windows): don't attempt to initialize COM security levels twice<commit_after>/*
* Copyright 2017 resin.io
*
* 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 "src/windows/com.h"
#include "src/log.h"
HRESULT drivelist::com::Initialize() {
HRESULT result;
drivelist::Debug("Initializing COM");
result = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(result))
return result;
drivelist::Debug("Initializing COM security levels");
result = CoInitializeSecurity(
NULL, // Security descriptor
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL); // Reserved
// This error can be thrown when COM was already initialized,
// which can be the case if the user runs various scans at
// the same time on the same process.
// TODO(jviotti): This workaround assumes that if RPC_E_TOO_LATE
// is returned, COM was already initialized for the current process,
// however the right solution is to get rid of COM altogether.
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms693736(v=vs.85).aspx
if (result == RPC_E_TOO_LATE) {
drivelist::Debug("COM is already initialized, continuing...");
return S_OK;
}
if (FAILED(result)) {
drivelist::com::Uninitialize();
}
return result;
}
void drivelist::com::Uninitialize() { CoUninitialize(); }
drivelist::com::Connection::Connection() {
this->locator = NULL;
this->proxy = NULL;
}
drivelist::com::Connection::~Connection() {
if (this->proxy != NULL)
this->proxy->Release();
if (this->locator != NULL)
this->locator->Release();
}
HRESULT drivelist::com::Connection::Connect(const LPCWSTR server) {
drivelist::Debug("Connecting to server");
const HRESULT result = this->locator->ConnectServer(
_bstr_t(server), // Path to server
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&this->proxy); // pointer to IWbemServices proxy
if (FAILED(result)) {
return result;
}
drivelist::Debug("Setting proxy security levels");
return CoSetProxyBlanket(
this->proxy, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE); // proxy capabilities
}
HRESULT drivelist::com::Connection::CreateInstance() {
drivelist::Debug("Creating connection instance");
return CoCreateInstance(
CLSID_WbemLocator,
NULL, // Not being created as part of an aggregate
// The COM instance context
//
// From https://msdn.microsoft.com/en-us/library/windows/desktop/ms693716(v=vs.85).aspx
//
// > The code that creates and manages objects of this class
// > is a DLL that runs in the same process as the caller of
// > the function specifying the class context.
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
reinterpret_cast<LPVOID *>(&this->locator));
}
HRESULT
drivelist::com::Connection::ExecuteWQLQuery(const BSTR query,
IEnumWbemClassObject **enumerator) {
return this->proxy->ExecQuery(
bstr_t("WQL"),
query,
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
enumerator);
}
<|endoftext|> |
<commit_before>/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file is part of zmqpp.
* Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file.
*/
/**
* \file
*
* \date 10 Aug 2011
* \author Ben Gray (\@benjamg)
*/
#ifndef ZMQPP_INET_HPP_
#define ZMQPP_INET_HPP_
/** \todo cross-platform version of including headers. */
// We get htons and htonl from here
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <netinet/in.h>
#endif
#include "compatibility.hpp"
namespace zmqpp
{
/*!
* \brief Possible byte order types.
*
* An enumeration of all the known order types, all two of them.
* There is also an entry for unknown which is just used as a default.
*/
ZMQPP_COMPARABLE_ENUM order {
big_endian, /*!< byte order is big endian */
little_endian /*!< byte order is little endian */
};
/*!
* Common code for the 64bit versions of htons/htons and ntohs/ntohl
*
* As htons and ntohs (or htonl and ntohs) always just do the same thing, ie
* swap bytes if the host order differs from network order or otherwise don't
* do anything, it seemed silly to type the code twice.
*
* \note This code assumes network order is always big endian. Which it is.
* \note The host endian is only checked once and afterwards assumed to remain
* the same.
*
* \param value_to_check unsigned 64 bit integer to swap
* \return swapped (or not) unsigned 64 bit integer
*/
inline uint64_t swap_if_needed(uint64_t const value_to_check)
{
static order host_order = (htonl(42) == 42) ? order::big_endian : order::little_endian;
if (order::big_endian == host_order)
{
return value_to_check;
}
union {
uint64_t integer;
uint8_t bytes[8];
} value { value_to_check };
std::swap(value.bytes[0], value.bytes[7]);
std::swap(value.bytes[1], value.bytes[6]);
std::swap(value.bytes[2], value.bytes[5]);
std::swap(value.bytes[3], value.bytes[4]);
return value.integer;
}
/*!
* 64 bit version of the htons/htonl
*
* I've used the name htonll to try and keep with the htonl naming scheme.
* We do not define this function if the macro `htonll` exists.
*
* \param hostlonglong unsigned 64 bit host order integer
* \return unsigned 64 bit network order integer
*/
#ifndef htonll
inline uint64_t htonll(uint64_t const hostlonglong)
{
return zmqpp::swap_if_needed(hostlonglong);
}
#endif
/*!
* 64 bit version of the ntohs/ntohl
*
* I've used the name htonll to try and keep with the htonl naming scheme.
* We do not define this function if the macro `ntohll` exists.
*
* \param networklonglong unsigned 64 bit network order integer
* \return unsigned 64 bit host order integer
*/
#ifndef ntohll
inline uint64_t ntohll(uint64_t const networklonglong)
{
return zmqpp::swap_if_needed(networklonglong);
}
#endif
/*!
* floating point version of the htons/htonl
*
* \param value host order floating point
* \returns network order floating point
*/
inline float htonf(float value)
{
assert(sizeof(float) == sizeof(uint32_t));
uint32_t temp;
memcpy(&temp, &value, sizeof(uint32_t));
temp = htonl( temp );
memcpy(&value, &temp, sizeof(uint32_t));
return value;
}
/*!
* floating point version of the ntohs/ntohl
*
* \param value network order float
* \returns host order float
*/
inline float ntohf(float value)
{
assert(sizeof(float) == sizeof(uint32_t));
uint32_t temp;
memcpy(&temp, &value, sizeof(uint32_t));
temp = ntohl( temp );
memcpy(&value, &temp, sizeof(uint32_t));
return value;
}
/*!
* double precision floating point version of the htons/htonl
*
* \param value host order double precision floating point
* \returns network order double precision floating point
*/
inline double htond(double value)
{
assert(sizeof(double) == sizeof(uint64_t));
uint64_t temp;
memcpy(&temp, &value, sizeof(uint64_t));
temp = htonll(temp);
memcpy(&value, &temp, sizeof(uint64_t));
return value;
}
/*!
* double precision floating point version of the ntohs/ntohl
*
* \param value network order double precision floating point
* \returns host order double precision floating point
*/
inline double ntohd(double value)
{
assert(sizeof(double) == sizeof(uint64_t));
uint64_t temp;
memcpy(&temp, &value, sizeof(uint64_t));
temp = ntohll(temp);
memcpy(&value, &temp, sizeof(uint64_t));
return value;
}
}
#endif /* INET_HPP_ */
<commit_msg>Fixes #119 (VS build problem)<commit_after>/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file is part of zmqpp.
* Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file.
*/
/**
* \file
*
* \date 10 Aug 2011
* \author Ben Gray (\@benjamg)
*/
#ifndef ZMQPP_INET_HPP_
#define ZMQPP_INET_HPP_
#include <cstdint>
/** \todo cross-platform version of including headers. */
// We get htons and htonl from here
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <netinet/in.h>
#endif
#include "compatibility.hpp"
namespace zmqpp
{
/*!
* \brief Possible byte order types.
*
* An enumeration of all the known order types, all two of them.
* There is also an entry for unknown which is just used as a default.
*/
ZMQPP_COMPARABLE_ENUM order {
big_endian, /*!< byte order is big endian */
little_endian /*!< byte order is little endian */
};
/*!
* Common code for the 64bit versions of htons/htons and ntohs/ntohl
*
* As htons and ntohs (or htonl and ntohs) always just do the same thing, ie
* swap bytes if the host order differs from network order or otherwise don't
* do anything, it seemed silly to type the code twice.
*
* \note This code assumes network order is always big endian. Which it is.
* \note The host endian is only checked once and afterwards assumed to remain
* the same.
*
* \param value_to_check unsigned 64 bit integer to swap
* \return swapped (or not) unsigned 64 bit integer
*/
inline uint64_t swap_if_needed(uint64_t const value_to_check)
{
static order host_order = (htonl(42) == 42) ? order::big_endian : order::little_endian;
if (order::big_endian == host_order)
{
return value_to_check;
}
union {
uint64_t integer;
uint8_t bytes[8];
} value { value_to_check };
std::swap(value.bytes[0], value.bytes[7]);
std::swap(value.bytes[1], value.bytes[6]);
std::swap(value.bytes[2], value.bytes[5]);
std::swap(value.bytes[3], value.bytes[4]);
return value.integer;
}
/*!
* 64 bit version of the htons/htonl
*
* I've used the name htonll to try and keep with the htonl naming scheme.
* We do not define this function if the macro `htonll` exists.
*
* \param hostlonglong unsigned 64 bit host order integer
* \return unsigned 64 bit network order integer
*/
#ifndef htonll
inline uint64_t htonll(uint64_t const hostlonglong)
{
return zmqpp::swap_if_needed(hostlonglong);
}
#endif
/*!
* 64 bit version of the ntohs/ntohl
*
* I've used the name htonll to try and keep with the htonl naming scheme.
* We do not define this function if the macro `ntohll` exists.
*
* \param networklonglong unsigned 64 bit network order integer
* \return unsigned 64 bit host order integer
*/
#ifndef ntohll
inline uint64_t ntohll(uint64_t const networklonglong)
{
return zmqpp::swap_if_needed(networklonglong);
}
#endif
/*!
* floating point version of the htons/htonl
*
* \param value host order floating point
* \returns network order floating point
*/
inline float htonf(float value)
{
assert(sizeof(float) == sizeof(uint32_t));
uint32_t temp;
memcpy(&temp, &value, sizeof(uint32_t));
temp = htonl( temp );
memcpy(&value, &temp, sizeof(uint32_t));
return value;
}
/*!
* floating point version of the ntohs/ntohl
*
* \param value network order float
* \returns host order float
*/
inline float ntohf(float value)
{
assert(sizeof(float) == sizeof(uint32_t));
uint32_t temp;
memcpy(&temp, &value, sizeof(uint32_t));
temp = ntohl( temp );
memcpy(&value, &temp, sizeof(uint32_t));
return value;
}
/*!
* double precision floating point version of the htons/htonl
*
* \param value host order double precision floating point
* \returns network order double precision floating point
*/
inline double htond(double value)
{
assert(sizeof(double) == sizeof(uint64_t));
uint64_t temp;
memcpy(&temp, &value, sizeof(uint64_t));
temp = htonll(temp);
memcpy(&value, &temp, sizeof(uint64_t));
return value;
}
/*!
* double precision floating point version of the ntohs/ntohl
*
* \param value network order double precision floating point
* \returns host order double precision floating point
*/
inline double ntohd(double value)
{
assert(sizeof(double) == sizeof(uint64_t));
uint64_t temp;
memcpy(&temp, &value, sizeof(uint64_t));
temp = ntohll(temp);
memcpy(&value, &temp, sizeof(uint64_t));
return value;
}
}
#endif /* INET_HPP_ */
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of gepetto-viewer.
// gepetto-viewer 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.
//
// gepetto-viewer is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#include <gepetto/gui/dialog/configuration.hh>
#include <QtGlobal>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <gepetto/viewer/node-property.h>
namespace gepetto {
namespace gui {
using viewer::Configuration;
void setSpinBoxRange(const viewer::Property* prop, QDoubleSpinBox* sb)
{
const viewer::Range<float>* range = dynamic_cast<const viewer::Range<float>*>(prop);
if (range) {
if (range->hasMin()) sb->setMinimum(static_cast<double>(range->min));
if (range->hasMax()) sb->setMaximum(static_cast<double>(range->max));
sb->setSingleStep(static_cast<double>(range->step));
#if QT_VERSION > QT_VERSION_CHECK(5, 12, 0)
if (range->adaptiveDecimal) sb->setStepType (QAbstractSpinBox::AdaptiveDecimalStepType);
#endif
}
}
void getEulerFromQuat(osg::Quat q, double& heading, double& attitude, double& bank)
{
double limit = 0.499999;
double sqx = q.x()*q.x();
double sqy = q.y()*q.y();
double sqz = q.z()*q.z();
double t = q.x()*q.y() + q.z()*q.w();
if (t>limit) { // gimbal lock ?
heading = 2 * atan2(q.x(),q.w());
attitude = osg::PI_2;
bank = 0;
} else if (t<-limit) {
heading = -2 * atan2(q.x(),q.w());
attitude = - osg::PI_2;
bank = 0;
} else {
heading = atan2(2*q.y()*q.w()-2*q.x()*q.z() , 1 - 2*sqy - 2*sqz);
attitude = asin(2*t);
bank = atan2(2*q.x()*q.w()-2*q.y()*q.z() , 1 - 2*sqx - 2*sqz);
}
}
void getQuatFromEuler(double heading, double attitude, double bank, osg::Quat& q)
{
double c1 = cos(heading/2);
double s1 = sin(heading/2);
double c2 = cos(attitude/2);
double s2 = sin(attitude/2);
double c3 = cos(bank/2);
double s3 = sin(bank/2);
double c1c2 = c1*c2;
double s1s2 = s1*s2;
double w =c1c2*c3 - s1s2*s3;
double x =c1c2*s3 + s1s2*c3;
double y =s1*c2*c3 + c1*s2*s3;
double z =c1*s2*c3 - s1*c2*s3;
q[0] = x; q[1] = y; q[2] = z; q[3] = w;
}
template <typename Vector>
inline void getValues (Vector& v, const QVector<QDoubleSpinBox*> spinBoxes)
{
int i = 0;
foreach (QDoubleSpinBox* sb, spinBoxes) {
v[i] = (float)sb->value ();
++i;
}
}
inline void getValues (Configuration& cfg, const QVector<QDoubleSpinBox*> spinBoxes)
{
const QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
cfg.position[0] = (float)x->value();
cfg.position[1] = (float)y->value();
cfg.position[2] = (float)z->value();
getQuatFromEuler (pitch->value(), roll->value(), yaw->value(), cfg.quat);
}
template <typename Vector>
inline void setValues (const Vector& v, QVector<QDoubleSpinBox*> spinBoxes)
{
int i = 0;
foreach (QDoubleSpinBox* sb, spinBoxes) {
sb->setValue (v[i]);
++i;
}
}
inline void setValues (const Configuration& cfg, QVector<QDoubleSpinBox*> spinBoxes)
{
QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
double _r,_p,_y;
getEulerFromQuat (cfg.quat,_p,_y,_r);
x->setValue(cfg.position[0]);
y->setValue(cfg.position[1]);
z->setValue(cfg.position[2]);
roll ->setValue(_r);
pitch->setValue(_p);
yaw ->setValue(_y);
}
static const QString sep(", ");
template <typename Vector>
QString valuesToString (const QVector<QDoubleSpinBox*> spinBoxes)
{
QString text = "[ ";
foreach (const QDoubleSpinBox* sb, spinBoxes)
text += QString::number (sb->value()) + sep;
text += " ]";
return text;
}
template <>
QString valuesToString<Configuration> (const QVector<QDoubleSpinBox*> spinBoxes)
{
const QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
osg::Quat quat;
getQuatFromEuler (pitch->value(), roll->value(), yaw->value(), quat);
return "[ "
+ QString::number (x->value()) + sep
+ QString::number (y->value()) + sep
+ QString::number (z->value()) + sep
+ QString::number (quat.x()) + sep
+ QString::number (quat.y()) + sep
+ QString::number (quat.z()) + sep
+ QString::number (quat.w()) + " ]";
}
#define DEFINE_PROPERTY_EDITOR(Name,Type) \
void Name::updateValue () \
{ \
Type cfg; \
getValues(cfg, spinBoxes); \
setPyValue (); \
emit valueChanged (cfg); \
} \
\
void Name::setValueFromProperty (viewer::Property* prop) \
{ \
Type cfg; \
prop->get (cfg); \
setValues(cfg, spinBoxes); \
setPyValue(); \
} \
\
void Name::set (const Type& v) \
{ \
foreach (QDoubleSpinBox* sb, spinBoxes) \
sb->blockSignals(true); \
setValues(v, spinBoxes); \
foreach (QDoubleSpinBox* sb, spinBoxes) \
sb->blockSignals(false); \
} \
\
void Name::setPyValue () \
{ \
pyValue->setText (valuesToString<Type>(spinBoxes)); \
}
DEFINE_PROPERTY_EDITOR(Vector2Dialog, osgVector2)
DEFINE_PROPERTY_EDITOR(Vector3Dialog, osgVector3)
DEFINE_PROPERTY_EDITOR(Vector4Dialog, osgVector4)
DEFINE_PROPERTY_EDITOR(ConfigurationDialog, Configuration)
template<typename T>
QString rowLabel(int i) { return "X" + QString::number(i); }
template<>
QString rowLabel<Configuration>(int i)
{
switch(i)
{
case 0: return "X";
case 1: return "Y";
case 2: return "Z";
case 3: return "Roll";
case 4: return "Pitch";
case 5: return "Yaw";
}
abort();
}
#define DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Name,Type,N) \
Name::Name (viewer::Property* property, QWidget *parent) \
: QDialog (parent) \
, pyValue (new QLineEdit) \
{ \
setModal (false); \
pyValue->setReadOnly (true); \
\
QFormLayout *layout = new QFormLayout; \
layout->addRow(new QLabel (property->objectName())); \
\
spinBoxes.reserve(N); \
for (int i = 0; i < N; ++i) { \
QDoubleSpinBox* sb (new QDoubleSpinBox); \
spinBoxes.append(sb); \
setSpinBoxRange(property, sb); \
connect(sb, SIGNAL(valueChanged(double)), SLOT(updateValue())); \
\
layout->addRow(rowLabel<Type>(i), sb); \
} \
layout->addRow("value", pyValue); \
\
QDialogButtonBox *buttonBox = new QDialogButtonBox ( \
QDialogButtonBox::Close, Qt::Horizontal); \
connect (buttonBox->button (QDialogButtonBox::Close), \
SIGNAL(clicked(bool)), SLOT(accept())); \
\
layout->addRow(buttonBox); \
\
setLayout (layout); \
}
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector2Dialog, osgVector2, 2)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector3Dialog, osgVector3, 3)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector4Dialog, osgVector4, 4)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(ConfigurationDialog, Configuration, 6)
} // namespace gui
} // namespace gepetto
<commit_msg>Set range for ConfigurationDialog<commit_after>// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of gepetto-viewer.
// gepetto-viewer 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.
//
// gepetto-viewer is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#include <gepetto/gui/dialog/configuration.hh>
#include <QtGlobal>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <gepetto/viewer/node-property.h>
namespace gepetto {
namespace gui {
using viewer::Configuration;
void setSpinBoxRange(const viewer::Property* prop, QDoubleSpinBox* sb)
{
sb->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
const viewer::Range<float>* range = dynamic_cast<const viewer::Range<float>*>(prop);
if (range) {
if (range->hasMin()) sb->setMinimum(static_cast<double>(range->min));
if (range->hasMax()) sb->setMaximum(static_cast<double>(range->max));
sb->setSingleStep(static_cast<double>(range->step));
#if QT_VERSION > QT_VERSION_CHECK(5, 12, 0)
if (range->adaptiveDecimal) sb->setStepType (QAbstractSpinBox::AdaptiveDecimalStepType);
#endif
}
}
void getEulerFromQuat(osg::Quat q, double& heading, double& attitude, double& bank)
{
double limit = 0.499999;
double sqx = q.x()*q.x();
double sqy = q.y()*q.y();
double sqz = q.z()*q.z();
double t = q.x()*q.y() + q.z()*q.w();
if (t>limit) { // gimbal lock ?
heading = 2 * atan2(q.x(),q.w());
attitude = osg::PI_2;
bank = 0;
} else if (t<-limit) {
heading = -2 * atan2(q.x(),q.w());
attitude = - osg::PI_2;
bank = 0;
} else {
heading = atan2(2*q.y()*q.w()-2*q.x()*q.z() , 1 - 2*sqy - 2*sqz);
attitude = asin(2*t);
bank = atan2(2*q.x()*q.w()-2*q.y()*q.z() , 1 - 2*sqx - 2*sqz);
}
}
void getQuatFromEuler(double heading, double attitude, double bank, osg::Quat& q)
{
double c1 = cos(heading/2);
double s1 = sin(heading/2);
double c2 = cos(attitude/2);
double s2 = sin(attitude/2);
double c3 = cos(bank/2);
double s3 = sin(bank/2);
double c1c2 = c1*c2;
double s1s2 = s1*s2;
double w =c1c2*c3 - s1s2*s3;
double x =c1c2*s3 + s1s2*c3;
double y =s1*c2*c3 + c1*s2*s3;
double z =c1*s2*c3 - s1*c2*s3;
q[0] = x; q[1] = y; q[2] = z; q[3] = w;
}
template <typename Vector>
inline void getValues (Vector& v, const QVector<QDoubleSpinBox*> spinBoxes)
{
int i = 0;
foreach (QDoubleSpinBox* sb, spinBoxes) {
v[i] = (float)sb->value ();
++i;
}
}
inline void getValues (Configuration& cfg, const QVector<QDoubleSpinBox*> spinBoxes)
{
const QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
cfg.position[0] = (float)x->value();
cfg.position[1] = (float)y->value();
cfg.position[2] = (float)z->value();
getQuatFromEuler (pitch->value(), roll->value(), yaw->value(), cfg.quat);
}
template <typename Vector>
inline void setValues (const Vector& v, QVector<QDoubleSpinBox*> spinBoxes)
{
int i = 0;
foreach (QDoubleSpinBox* sb, spinBoxes) {
sb->setValue (v[i]);
++i;
}
}
inline void setValues (const Configuration& cfg, QVector<QDoubleSpinBox*> spinBoxes)
{
QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
double _r,_p,_y;
getEulerFromQuat (cfg.quat,_p,_y,_r);
x->setValue(cfg.position[0]);
y->setValue(cfg.position[1]);
z->setValue(cfg.position[2]);
roll ->setValue(_r);
pitch->setValue(_p);
yaw ->setValue(_y);
}
static const QString sep(", ");
template <typename Vector>
QString valuesToString (const QVector<QDoubleSpinBox*> spinBoxes)
{
QString text = "[ ";
foreach (const QDoubleSpinBox* sb, spinBoxes)
text += QString::number (sb->value()) + sep;
text += " ]";
return text;
}
template <>
QString valuesToString<Configuration> (const QVector<QDoubleSpinBox*> spinBoxes)
{
const QDoubleSpinBox *x = spinBoxes[0], *y = spinBoxes[1], *z = spinBoxes[2],
*roll = spinBoxes[3], *pitch = spinBoxes[4], *yaw = spinBoxes[5];
osg::Quat quat;
getQuatFromEuler (pitch->value(), roll->value(), yaw->value(), quat);
return "[ "
+ QString::number (x->value()) + sep
+ QString::number (y->value()) + sep
+ QString::number (z->value()) + sep
+ QString::number (quat.x()) + sep
+ QString::number (quat.y()) + sep
+ QString::number (quat.z()) + sep
+ QString::number (quat.w()) + " ]";
}
#define DEFINE_PROPERTY_EDITOR(Name,Type) \
void Name::updateValue () \
{ \
Type cfg; \
getValues(cfg, spinBoxes); \
setPyValue (); \
emit valueChanged (cfg); \
} \
\
void Name::setValueFromProperty (viewer::Property* prop) \
{ \
Type cfg; \
prop->get (cfg); \
setValues(cfg, spinBoxes); \
setPyValue(); \
} \
\
void Name::set (const Type& v) \
{ \
foreach (QDoubleSpinBox* sb, spinBoxes) \
sb->blockSignals(true); \
setValues(v, spinBoxes); \
foreach (QDoubleSpinBox* sb, spinBoxes) \
sb->blockSignals(false); \
} \
\
void Name::setPyValue () \
{ \
pyValue->setText (valuesToString<Type>(spinBoxes)); \
}
DEFINE_PROPERTY_EDITOR(Vector2Dialog, osgVector2)
DEFINE_PROPERTY_EDITOR(Vector3Dialog, osgVector3)
DEFINE_PROPERTY_EDITOR(Vector4Dialog, osgVector4)
DEFINE_PROPERTY_EDITOR(ConfigurationDialog, Configuration)
template<typename T>
QString rowLabel(int i) { return "X" + QString::number(i); }
template<>
QString rowLabel<Configuration>(int i)
{
switch(i)
{
case 0: return "X";
case 1: return "Y";
case 2: return "Z";
case 3: return "Roll";
case 4: return "Pitch";
case 5: return "Yaw";
}
abort();
}
template<typename Dialog>
void constructor_hook(Dialog*, QVector<QDoubleSpinBox*>) {}
void constructor_hook(ConfigurationDialog*, QVector<QDoubleSpinBox*> spinBoxes)
{
foreach (QDoubleSpinBox* sb, spinBoxes) {
sb->setSingleStep(0.01);
sb->setDecimals(4);
}
foreach (QDoubleSpinBox* sb, spinBoxes.mid(3))
sb->setRange(-osg::PI, osg::PI);
}
#define DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Name,Type,N) \
Name::Name (viewer::Property* property, QWidget *parent) \
: QDialog (parent) \
, pyValue (new QLineEdit) \
{ \
setModal (false); \
pyValue->setReadOnly (true); \
\
QFormLayout *layout = new QFormLayout; \
layout->addRow(new QLabel (property->objectName())); \
\
spinBoxes.reserve(N); \
for (int i = 0; i < N; ++i) { \
QDoubleSpinBox* sb (new QDoubleSpinBox); \
spinBoxes.append(sb); \
setSpinBoxRange(property, sb); \
connect(sb, SIGNAL(valueChanged(double)), SLOT(updateValue())); \
\
layout->addRow(rowLabel<Type>(i), sb); \
} \
layout->addRow("value", pyValue); \
\
QDialogButtonBox *buttonBox = new QDialogButtonBox ( \
QDialogButtonBox::Close, Qt::Horizontal); \
connect (buttonBox->button (QDialogButtonBox::Close), \
SIGNAL(clicked(bool)), SLOT(accept())); \
\
layout->addRow(buttonBox); \
\
setLayout (layout); \
\
constructor_hook(this, spinBoxes); \
}
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector2Dialog, osgVector2, 2)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector3Dialog, osgVector3, 3)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(Vector4Dialog, osgVector4, 4)
DEFINE_PROPERTY_EDITOR_CONSTRUCTOR(ConfigurationDialog, Configuration, 6)
} // namespace gui
} // namespace gepetto
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include "libtorrent/config.hpp"
#include "libtorrent/gzip.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/bind.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/io.hpp"
using namespace libtorrent;
using boost::bind;
namespace libtorrent
{
http_tracker_connection::http_tracker_connection(
io_service& ios
, connection_queue& cc
, tracker_manager& man
, tracker_request const& req
, address bind_infc
, boost::weak_ptr<request_callback> c
, session_settings const& stn
, proxy_settings const& ps
, std::string const& auth)
: tracker_connection(man, req, ios, bind_infc, c)
, m_man(man)
{
// TODO: authentication
std::string url = req.url;
if (req.kind == tracker_request::scrape_request)
{
// find and replace "announce" with "scrape"
// in request
std::size_t pos = url.find("announce");
if (pos == std::string::npos)
{
fail(-1, ("scrape is not available on url: '"
+ req.url +"'").c_str());
return;
}
url.replace(pos, 8, "scrape");
}
// if request-string already contains
// some parameters, append an ampersand instead
// of a question mark
size_t arguments_start = url.find('?');
if (arguments_start != std::string::npos)
url += "&";
else
url += "?";
url += "info_hash=";
url += escape_string(
reinterpret_cast<const char*>(req.info_hash.begin()), 20);
if (req.kind == tracker_request::announce_request)
{
url += "&peer_id=";
url += escape_string(
reinterpret_cast<const char*>(req.pid.begin()), 20);
url += "&port=";
url += boost::lexical_cast<std::string>(req.listen_port);
url += "&uploaded=";
url += boost::lexical_cast<std::string>(req.uploaded);
url += "&downloaded=";
url += boost::lexical_cast<std::string>(req.downloaded);
url += "&left=";
url += boost::lexical_cast<std::string>(req.left);
if (req.event != tracker_request::none)
{
const char* event_string[] = {"completed", "started", "stopped"};
url += "&event=";
url += event_string[req.event - 1];
}
url += "&key=";
std::stringstream key_string;
key_string << std::hex << req.key;
url += key_string.str();
url += "&compact=1";
url += "&numwant=";
url += boost::lexical_cast<std::string>(
(std::min)(req.num_want, 999));
if (stn.announce_ip != address())
{
url += "&ip=";
url += stn.announce_ip.to_string();
}
#ifndef TORRENT_DISABLE_ENCRYPTION
url += "&supportcrypto=1";
#endif
url += "&ipv6=";
url += req.ipv6;
// extension that tells the tracker that
// we don't need any peer_id's in the response
url += "&no_peer_id=1";
}
m_tracker_connection.reset(new http_connection(ios, cc
, boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4)));
m_tracker_connection->get(url, seconds(stn.tracker_completion_timeout)
, &ps, 5, stn.user_agent, bind_infc);
#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)
boost::shared_ptr<request_callback> cb = requester();
if (cb)
{
cb->debug_log("==> TRACKER_REQUEST [ url: " + url + " ]");
}
#endif
}
void http_tracker_connection::close()
{
if (m_tracker_connection)
{
m_tracker_connection->close();
m_tracker_connection.reset();
}
tracker_connection::close();
}
void http_tracker_connection::on_response(asio::error_code const& ec
, http_parser const& parser, char const* data, int size)
{
// keep this alive
boost::intrusive_ptr<http_tracker_connection> me(this);
if (!parser.header_finished())
{
fail(-1, "premature end of file");
return;
}
if (parser.status_code() != 200)
{
fail(parser.status_code(), parser.message().c_str());
return;
}
if (ec && ec != asio::error::eof)
{
fail(parser.status_code(), ec.message().c_str());
return;
}
// handle tracker response
entry e = bdecode(data, data + size);
if (e.type() != entry::undefined_t)
{
parse(parser.status_code(), e);
}
else
{
std::string error_str("invalid bencoding of tracker response: \"");
for (char const* i = data, *end(data + size); i != end; ++i)
{
if (std::isprint(*i)) error_str += *i;
else error_str += "0x" + boost::lexical_cast<std::string>((unsigned int)*i) + " ";
}
error_str += "\"";
fail(parser.status_code(), error_str.c_str());
}
close();
}
bool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret)
{
// extract peer id (if any)
if (info.type() != entry::dictionary_t)
{
fail(-1, "invalid response from tracker (invalid peer entry)");
return false;
}
entry const* i = info.find_key("peer id");
if (i != 0)
{
if (i->type() != entry::string_t || i->string().length() != 20)
{
fail(-1, "invalid response from tracker (invalid peer id)");
return false;
}
std::copy(i->string().begin(), i->string().end(), ret.pid.begin());
}
else
{
// if there's no peer_id, just initialize it to a bunch of zeroes
std::fill_n(ret.pid.begin(), 20, 0);
}
// extract ip
i = info.find_key("ip");
if (i == 0 || i->type() != entry::string_t)
{
fail(-1, "invalid response from tracker");
return false;
}
ret.ip = i->string();
// extract port
i = info.find_key("port");
if (i == 0 || i->type() != entry::int_t)
{
fail(-1, "invalid response from tracker");
return false;
}
ret.port = (unsigned short)i->integer();
return true;
}
void http_tracker_connection::parse(int status_code, entry const& e)
{
boost::shared_ptr<request_callback> cb = requester();
if (!cb) return;
// parse the response
entry const* failure = e.find_key("failure reason");
if (failure && failure->type() == entry::string_t)
{
fail(status_code, failure->string().c_str());
return;
}
entry const* warning = e.find_key("warning message");
if (warning && warning->type() == entry::string_t)
{
cb->tracker_warning(warning->string());
}
std::vector<peer_entry> peer_list;
if (tracker_req().kind == tracker_request::scrape_request)
{
std::string ih;
std::copy(tracker_req().info_hash.begin(), tracker_req().info_hash.end()
, std::back_inserter(ih));
entry const* files = e.find_key("files");
if (files == 0 || files->type() != entry::dictionary_t)
{
fail(-1, "invalid or missing 'files' entry in scrape response");
return;
}
entry const* scrape_data = e.find_key(ih.c_str());
if (scrape_data == 0 || scrape_data->type() != entry::dictionary_t)
{
fail(-1, "missing or invalid info-hash entry in scrape response");
return;
}
entry const* complete = scrape_data->find_key("complete");
entry const* incomplete = scrape_data->find_key("incomplete");
entry const* downloaded = scrape_data->find_key("downloaded");
if (complete == 0 || incomplete == 0 || downloaded == 0
|| complete->type() != entry::int_t
|| incomplete->type() != entry::int_t
|| downloaded->type() != entry::int_t)
{
fail(-1, "missing 'complete' or 'incomplete' entries in scrape response");
return;
}
cb->tracker_scrape_response(tracker_req(), complete->integer()
, incomplete->integer(), downloaded->integer());
return;
}
entry const* interval = e.find_key("interval");
if (interval == 0 || interval->type() != entry::int_t)
{
fail(-1, "missing or invalid 'interval' entry in tracker response");
return;
}
entry const* peers_ent = e.find_key("peers");
if (peers_ent == 0)
{
fail(-1, "missing 'peers' entry in tracker response");
return;
}
if (peers_ent->type() == entry::string_t)
{
std::string const& peers = peers_ent->string();
for (std::string::const_iterator i = peers.begin();
i != peers.end();)
{
if (std::distance(i, peers.end()) < 6) break;
peer_entry p;
p.pid.clear();
p.ip = detail::read_v4_address(i).to_string();
p.port = detail::read_uint16(i);
peer_list.push_back(p);
}
}
else if (peers_ent->type() == entry::list_t)
{
entry::list_type const& l = peers_ent->list();
for(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i)
{
peer_entry p;
if (!extract_peer_info(*i, p)) return;
peer_list.push_back(p);
}
}
else
{
fail(-1, "invalid 'peers' entry in tracker response");
return;
}
entry const* ipv6_peers = e.find_key("peers6");
if (ipv6_peers && ipv6_peers->type() == entry::string_t)
{
std::string const& peers = ipv6_peers->string();
for (std::string::const_iterator i = peers.begin();
i != peers.end();)
{
if (std::distance(i, peers.end()) < 18) break;
peer_entry p;
p.pid.clear();
p.ip = detail::read_v6_address(i).to_string();
p.port = detail::read_uint16(i);
peer_list.push_back(p);
}
}
// look for optional scrape info
int complete = -1;
int incomplete = -1;
entry const* complete_ent = e.find_key("complete");
if (complete_ent && complete_ent->type() == entry::int_t)
complete = complete_ent->integer();
entry const* incomplete_ent = e.find_key("incomplete");
if (incomplete_ent && incomplete_ent->type() == entry::int_t)
incomplete = incomplete_ent->integer();
cb->tracker_response(tracker_req(), peer_list, interval->integer(), complete
, incomplete);
}
}
<commit_msg>improved tracker error messages<commit_after>/*
Copyright (c) 2003, 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 "libtorrent/pch.hpp"
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include "libtorrent/config.hpp"
#include "libtorrent/gzip.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/bind.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/io.hpp"
using namespace libtorrent;
using boost::bind;
namespace libtorrent
{
http_tracker_connection::http_tracker_connection(
io_service& ios
, connection_queue& cc
, tracker_manager& man
, tracker_request const& req
, address bind_infc
, boost::weak_ptr<request_callback> c
, session_settings const& stn
, proxy_settings const& ps
, std::string const& auth)
: tracker_connection(man, req, ios, bind_infc, c)
, m_man(man)
{
// TODO: authentication
std::string url = req.url;
if (req.kind == tracker_request::scrape_request)
{
// find and replace "announce" with "scrape"
// in request
std::size_t pos = url.find("announce");
if (pos == std::string::npos)
{
fail(-1, ("scrape is not available on url: '"
+ req.url +"'").c_str());
return;
}
url.replace(pos, 8, "scrape");
}
// if request-string already contains
// some parameters, append an ampersand instead
// of a question mark
size_t arguments_start = url.find('?');
if (arguments_start != std::string::npos)
url += "&";
else
url += "?";
url += "info_hash=";
url += escape_string(
reinterpret_cast<const char*>(req.info_hash.begin()), 20);
if (req.kind == tracker_request::announce_request)
{
url += "&peer_id=";
url += escape_string(
reinterpret_cast<const char*>(req.pid.begin()), 20);
url += "&port=";
url += boost::lexical_cast<std::string>(req.listen_port);
url += "&uploaded=";
url += boost::lexical_cast<std::string>(req.uploaded);
url += "&downloaded=";
url += boost::lexical_cast<std::string>(req.downloaded);
url += "&left=";
url += boost::lexical_cast<std::string>(req.left);
if (req.event != tracker_request::none)
{
const char* event_string[] = {"completed", "started", "stopped"};
url += "&event=";
url += event_string[req.event - 1];
}
url += "&key=";
std::stringstream key_string;
key_string << std::hex << req.key;
url += key_string.str();
url += "&compact=1";
url += "&numwant=";
url += boost::lexical_cast<std::string>(
(std::min)(req.num_want, 999));
if (stn.announce_ip != address())
{
url += "&ip=";
url += stn.announce_ip.to_string();
}
#ifndef TORRENT_DISABLE_ENCRYPTION
url += "&supportcrypto=1";
#endif
url += "&ipv6=";
url += req.ipv6;
// extension that tells the tracker that
// we don't need any peer_id's in the response
url += "&no_peer_id=1";
}
m_tracker_connection.reset(new http_connection(ios, cc
, boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4)));
m_tracker_connection->get(url, seconds(stn.tracker_completion_timeout)
, &ps, 5, stn.user_agent, bind_infc);
#if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING)
boost::shared_ptr<request_callback> cb = requester();
if (cb)
{
cb->debug_log("==> TRACKER_REQUEST [ url: " + url + " ]");
}
#endif
}
void http_tracker_connection::close()
{
if (m_tracker_connection)
{
m_tracker_connection->close();
m_tracker_connection.reset();
}
tracker_connection::close();
}
void http_tracker_connection::on_response(asio::error_code const& ec
, http_parser const& parser, char const* data, int size)
{
// keep this alive
boost::intrusive_ptr<http_tracker_connection> me(this);
if (ec && ec != asio::error::eof)
{
fail(-1, ec.message().c_str());
return;
}
if (!parser.header_finished())
{
fail(-1, "premature end of file");
return;
}
if (parser.status_code() != 200)
{
fail(parser.status_code(), parser.message().c_str());
return;
}
if (ec && ec != asio::error::eof)
{
fail(parser.status_code(), ec.message().c_str());
return;
}
// handle tracker response
entry e = bdecode(data, data + size);
if (e.type() != entry::undefined_t)
{
parse(parser.status_code(), e);
}
else
{
std::string error_str("invalid bencoding of tracker response: \"");
for (char const* i = data, *end(data + size); i != end; ++i)
{
if (std::isprint(*i)) error_str += *i;
else error_str += "0x" + boost::lexical_cast<std::string>((unsigned int)*i) + " ";
}
error_str += "\"";
fail(parser.status_code(), error_str.c_str());
}
close();
}
bool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret)
{
// extract peer id (if any)
if (info.type() != entry::dictionary_t)
{
fail(-1, "invalid response from tracker (invalid peer entry)");
return false;
}
entry const* i = info.find_key("peer id");
if (i != 0)
{
if (i->type() != entry::string_t || i->string().length() != 20)
{
fail(-1, "invalid response from tracker (invalid peer id)");
return false;
}
std::copy(i->string().begin(), i->string().end(), ret.pid.begin());
}
else
{
// if there's no peer_id, just initialize it to a bunch of zeroes
std::fill_n(ret.pid.begin(), 20, 0);
}
// extract ip
i = info.find_key("ip");
if (i == 0 || i->type() != entry::string_t)
{
fail(-1, "invalid response from tracker");
return false;
}
ret.ip = i->string();
// extract port
i = info.find_key("port");
if (i == 0 || i->type() != entry::int_t)
{
fail(-1, "invalid response from tracker");
return false;
}
ret.port = (unsigned short)i->integer();
return true;
}
void http_tracker_connection::parse(int status_code, entry const& e)
{
boost::shared_ptr<request_callback> cb = requester();
if (!cb) return;
// parse the response
entry const* failure = e.find_key("failure reason");
if (failure && failure->type() == entry::string_t)
{
fail(status_code, failure->string().c_str());
return;
}
entry const* warning = e.find_key("warning message");
if (warning && warning->type() == entry::string_t)
{
cb->tracker_warning(warning->string());
}
std::vector<peer_entry> peer_list;
if (tracker_req().kind == tracker_request::scrape_request)
{
std::string ih;
std::copy(tracker_req().info_hash.begin(), tracker_req().info_hash.end()
, std::back_inserter(ih));
entry const* files = e.find_key("files");
if (files == 0 || files->type() != entry::dictionary_t)
{
fail(-1, "invalid or missing 'files' entry in scrape response");
return;
}
entry const* scrape_data = e.find_key(ih.c_str());
if (scrape_data == 0 || scrape_data->type() != entry::dictionary_t)
{
fail(-1, "missing or invalid info-hash entry in scrape response");
return;
}
entry const* complete = scrape_data->find_key("complete");
entry const* incomplete = scrape_data->find_key("incomplete");
entry const* downloaded = scrape_data->find_key("downloaded");
if (complete == 0 || incomplete == 0 || downloaded == 0
|| complete->type() != entry::int_t
|| incomplete->type() != entry::int_t
|| downloaded->type() != entry::int_t)
{
fail(-1, "missing 'complete' or 'incomplete' entries in scrape response");
return;
}
cb->tracker_scrape_response(tracker_req(), complete->integer()
, incomplete->integer(), downloaded->integer());
return;
}
entry const* interval = e.find_key("interval");
if (interval == 0 || interval->type() != entry::int_t)
{
fail(-1, "missing or invalid 'interval' entry in tracker response");
return;
}
entry const* peers_ent = e.find_key("peers");
if (peers_ent == 0)
{
fail(-1, "missing 'peers' entry in tracker response");
return;
}
if (peers_ent->type() == entry::string_t)
{
std::string const& peers = peers_ent->string();
for (std::string::const_iterator i = peers.begin();
i != peers.end();)
{
if (std::distance(i, peers.end()) < 6) break;
peer_entry p;
p.pid.clear();
p.ip = detail::read_v4_address(i).to_string();
p.port = detail::read_uint16(i);
peer_list.push_back(p);
}
}
else if (peers_ent->type() == entry::list_t)
{
entry::list_type const& l = peers_ent->list();
for(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i)
{
peer_entry p;
if (!extract_peer_info(*i, p)) return;
peer_list.push_back(p);
}
}
else
{
fail(-1, "invalid 'peers' entry in tracker response");
return;
}
entry const* ipv6_peers = e.find_key("peers6");
if (ipv6_peers && ipv6_peers->type() == entry::string_t)
{
std::string const& peers = ipv6_peers->string();
for (std::string::const_iterator i = peers.begin();
i != peers.end();)
{
if (std::distance(i, peers.end()) < 18) break;
peer_entry p;
p.pid.clear();
p.ip = detail::read_v6_address(i).to_string();
p.port = detail::read_uint16(i);
peer_list.push_back(p);
}
}
// look for optional scrape info
int complete = -1;
int incomplete = -1;
entry const* complete_ent = e.find_key("complete");
if (complete_ent && complete_ent->type() == entry::int_t)
complete = complete_ent->integer();
entry const* incomplete_ent = e.find_key("incomplete");
if (incomplete_ent && incomplete_ent->type() == entry::int_t)
incomplete = incomplete_ent->integer();
cb->tracker_response(tracker_req(), peer_list, interval->integer(), complete
, incomplete);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "..\StdAfx.h"
#include "..\BatchEncoder.h"
#include "Hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
<commit_msg>Update Hyperlink.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "..\BatchEncoder.h"
#include "Hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
<|endoftext|> |
<commit_before>#ifndef ANIMATEDGROUP_HPP_
#define ANIMATEDGROUP_HPP_
#include <tuple>
#include <core/animated.hpp>
template <typename ...Tp>
using AnimatedTuple = std::tuple<Animated<Tp>...>;
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
iterateTick(AnimatedTuple<Tp...>&, int32_t)
{}
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
iterateTick(AnimatedTuple<Tp...>& properties, int32_t deltaTime)
{
std::get<I>(properties).tick(deltaTime);
iterateTick<I + 1, Tp...>(properties, deltaTime);
}
template <typename ...Tp>
class AnimatedGroup
{
public:
template <size_t I>
using AnimatedElement = typename std::tuple_element<I, AnimatedTuple<Tp...>>::type::type;
AnimatedGroup(Tp... properties):
m_properties(Animated<Tp>(properties)...)
{}
void tick(int32_t deltaTime)
{
iterateTick<0, Tp...>(m_properties, deltaTime);
}
template <size_t I>
void animate(AnimationPtr<AnimatedElement<I>> &&animation)
{
std::get<I>(m_properties).animate(std::move(animation));
}
template <size_t I>
AnimatedElement<I> value() const
{
return std::get<I>(m_properties).value();
}
private:
AnimatedTuple<Tp...> m_properties;
};
#endif // ANIMATEDGROUP_HPP_
<commit_msg>Add FIXME(#57)<commit_after>#ifndef ANIMATEDGROUP_HPP_
#define ANIMATEDGROUP_HPP_
#include <tuple>
#include <core/animated.hpp>
template <typename ...Tp>
using AnimatedTuple = std::tuple<Animated<Tp>...>;
// FIXME(#57): generalize tuple iteration process
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
iterateTick(AnimatedTuple<Tp...>&, int32_t)
{}
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
iterateTick(AnimatedTuple<Tp...>& properties, int32_t deltaTime)
{
std::get<I>(properties).tick(deltaTime);
iterateTick<I + 1, Tp...>(properties, deltaTime);
}
template <typename ...Tp>
class AnimatedGroup
{
public:
template <size_t I>
using AnimatedElement = typename std::tuple_element<I, AnimatedTuple<Tp...>>::type::type;
AnimatedGroup(Tp... properties):
m_properties(Animated<Tp>(properties)...)
{}
void tick(int32_t deltaTime)
{
iterateTick<0, Tp...>(m_properties, deltaTime);
}
template <size_t I>
void animate(AnimationPtr<AnimatedElement<I>> &&animation)
{
std::get<I>(m_properties).animate(std::move(animation));
}
template <size_t I>
AnimatedElement<I> value() const
{
return std::get<I>(m_properties).value();
}
private:
AnimatedTuple<Tp...> m_properties;
};
#endif // ANIMATEDGROUP_HPP_
<|endoftext|> |
<commit_before>/* junctions_main.cc -- handle the 'junction' commands
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <aramu@genome.wustl.edu>
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 <iostream>
#include <getopt.h>
#include <stdexcept>
#include "common.h"
#include "gtf_parser.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
using namespace std;
//Usage for junctions subcommands
int junctions_usage(ostream &out = cout) {
out << "\nUsage:\t\t" << "regtools junctions <command> [options]";
out << "\nCommand:\t" << "extract\t\tIdentify exon-exon junctions from alignments.";
out << "\n\t\tannotate\tAnnotate the junctions.";
out << "\n";
return 0;
}
//Run 'junctions extract'
int junctions_extract(int argc, char *argv[]) {
JunctionsExtractor extract;
try {
extract.parse_options(argc, argv);
extract.identify_junctions_from_BAM();
extract.print_all_junctions();
} catch(const cmdline_help_exception& e) {
cerr << e.what();
return 0;
} catch(const runtime_error& error) {
cerr << error.what();
extract.usage();
return 1;
}
return 0;
}
//Run 'junctions annotate' subcommand
int junctions_annotate(int argc, char *argv[]) {
JunctionsAnnotator anno;
AnnotatedJunction line;
line.reset();
int linec = 0;
ofstream out;
try {
anno.parse_options(argc, argv);
anno.read_gtf();
anno.open_junctions();
anno.set_ofstream_object(out);
line.print_header(out);
while(anno.get_single_junction(line)) {
anno.get_splice_site(line);
anno.annotate_junction_with_gtf(line);
line.print(out);
line.reset();
linec++;
}
anno.close_ofstream();
cerr << endl << "Annotated " << linec << " lines.";
anno.close_junctions();
} catch(const cmdline_help_exception& e) {
cerr << e.what();
return 0;
} catch(const runtime_error& e) {
cerr << endl << e.what() << endl;
return 1;
}
return 0;
}
//Parse out subcommands under junctions
int junctions_main(int argc, char *argv[]) {
if(argc > 1) {
string subcmd(argv[1]);
if(subcmd == "extract") {
return junctions_extract(argc - 1, argv + 1);
}
if(subcmd == "annotate") {
return junctions_annotate(argc - 1, argv + 1);
}
}
return junctions_usage();
}
<commit_msg>Use renamed method.<commit_after>/* junctions_main.cc -- handle the 'junction' commands
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <aramu@genome.wustl.edu>
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 <iostream>
#include <getopt.h>
#include <stdexcept>
#include "common.h"
#include "gtf_parser.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
using namespace std;
//Usage for junctions subcommands
int junctions_usage(ostream &out = cout) {
out << "\nUsage:\t\t" << "regtools junctions <command> [options]";
out << "\nCommand:\t" << "extract\t\tIdentify exon-exon junctions from alignments.";
out << "\n\t\tannotate\tAnnotate the junctions.";
out << "\n";
return 0;
}
//Run 'junctions extract'
int junctions_extract(int argc, char *argv[]) {
JunctionsExtractor extract;
try {
extract.parse_options(argc, argv);
extract.identify_junctions_from_BAM();
extract.print_all_junctions();
} catch(const cmdline_help_exception& e) {
cerr << e.what();
return 0;
} catch(const runtime_error& error) {
cerr << error.what();
extract.usage();
return 1;
}
return 0;
}
//Run 'junctions annotate' subcommand
int junctions_annotate(int argc, char *argv[]) {
JunctionsAnnotator anno;
AnnotatedJunction line;
line.reset();
int linec = 0;
ofstream out;
try {
anno.parse_options(argc, argv);
anno.load_gtf();
anno.open_junctions();
anno.set_ofstream_object(out);
line.print_header(out);
while(anno.get_single_junction(line)) {
anno.get_splice_site(line);
anno.annotate_junction_with_gtf(line);
line.print(out);
line.reset();
linec++;
}
anno.close_ofstream();
cerr << endl << "Annotated " << linec << " lines.";
anno.close_junctions();
} catch(const cmdline_help_exception& e) {
cerr << e.what();
return 0;
} catch(const runtime_error& e) {
cerr << endl << e.what() << endl;
return 1;
}
return 0;
}
//Parse out subcommands under junctions
int junctions_main(int argc, char *argv[]) {
if(argc > 1) {
string subcmd(argv[1]);
if(subcmd == "extract") {
return junctions_extract(argc - 1, argv + 1);
}
if(subcmd == "annotate") {
return junctions_annotate(argc - 1, argv + 1);
}
}
return junctions_usage();
}
<|endoftext|> |
<commit_before>#include "layers/loss.h"
namespace marian {
// @TODO, simplify this. Currently here for back-compat
Ptr<LabelwiseLoss> newLoss(Ptr<Options> options, bool inference) {
float smoothing = inference ? 0.f : options->get<float>("label-smoothing");
std::string costType = options->get<std::string>("cost-type", "ce-mean");
if(costType == "ce-rescore") {
return New<RescorerLoss>();
} else if(costType == "ce-rescore-mean") {
ABORT("Check me");
return New<RescorerLoss>();
} else { // same as ce-mean
return New<CrossEntropyLoss>(smoothing);
}
}
// see loss.h for detailed explanations of each class
Ptr<MultiRationalLoss> newMultiLoss(Ptr<Options> options) {
std::string multiLossType = options->get<std::string>("multi-loss-type", "sum");
if(multiLossType == "sum") // sum of sums
return New<SumMultiRationalLoss>();
else if(multiLossType == "scaled") // sum of scaled sums, first element is reference scale
return New<ScaledMultiRationalLoss>();
else if(multiLossType == "mean") // sum of means
return New<MeanMultiRationalLoss>();
else
ABORT("Unknown multi-loss-type {}", multiLossType);
return nullptr;
}
} // namespace marian
<commit_msg>removed an overly cautious check<commit_after>#include "layers/loss.h"
namespace marian {
// @TODO, simplify this. Currently here for back-compat
Ptr<LabelwiseLoss> newLoss(Ptr<Options> options, bool inference) {
float smoothing = inference ? 0.f : options->get<float>("label-smoothing");
std::string costType = options->get<std::string>("cost-type", "ce-mean");
if(costType == "ce-rescore") {
return New<RescorerLoss>();
} else if(costType == "ce-rescore-mean") {
return New<RescorerLoss>();
} else { // same as ce-mean
return New<CrossEntropyLoss>(smoothing);
}
}
// see loss.h for detailed explanations of each class
Ptr<MultiRationalLoss> newMultiLoss(Ptr<Options> options) {
std::string multiLossType = options->get<std::string>("multi-loss-type", "sum");
if(multiLossType == "sum") // sum of sums
return New<SumMultiRationalLoss>();
else if(multiLossType == "scaled") // sum of scaled sums, first element is reference scale
return New<ScaledMultiRationalLoss>();
else if(multiLossType == "mean") // sum of means
return New<MeanMultiRationalLoss>();
else
ABORT("Unknown multi-loss-type {}", multiLossType);
return nullptr;
}
} // namespace marian
<|endoftext|> |
<commit_before>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Create structure for storing IMU data
//bno055_t bno055;
// Holds the latest temperature value from the DS18B20 temperature sensor
ds18b20_t ds18b20;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
//yaw_controller intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
pthread_t depthThread;
pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
// Initialize pressure sensor
pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
// Read pressure sensor by passing calibration structure
ms5837 = ms5837_read(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
printf("Current Depth:\t %.3f\n",depth);
usleep(1000000);
// Write IMU values to screen
printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);
//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw and depth control
*****************************************************************************/
void *navigation(void* arg)
{
initialize_motors(motor_channels, HERTZ);
//float output_port; // port motor output
//float output_starboard; // starboard motor output
float yaw = 0; //Local variable for if statements
//////////////yaw controller initialization////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint for yaw_controller
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize yaw_controller error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize yaw_controller gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.SAT = YAW_SAT;
yaw_pid.DT = DT; // initialize time step
/////////////depth controller initialization///////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.DT = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; //Depth controller saturation values
depth_pid.SAT = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
//bno055 = read_imu_fifo();
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) //AUV pointed right
{
yaw = substate.imu.yaw;
}
else //AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
//calculate yaw controller output
motor_percent = marchPID(substate.imu, yaw);
//set_motor(0,motor_percent); // Set port motor
//set_motor(1, motor_percent); // Set starboard motor
// Sleep for 5 ms
usleep(5000);
}
//Turn motors off; Exit cleanly
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
void *safety_thread(void* arg)
{
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
ds18b20 = read_temp_fifo();
printf("Temperature: %f degC\n", ds18b20.temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
/*if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( ds18b20.temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}//*/
// Check for leak
/*leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}*/
// Check IMU accelerometer for collision (1+ g detected)
printf("x_acc: %f\n y_acc: %f\n z_acc: %f\n",
substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc);
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Sleep a little
usleep(100000);
}
pthread_exit(NULL);
}
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<commit_msg>Commented out imu printing<commit_after>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Create structure for storing IMU data
//bno055_t bno055;
// Holds the latest temperature value from the DS18B20 temperature sensor
ds18b20_t ds18b20;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
//yaw_controller intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
pthread_t depthThread;
pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
// Initialize pressure sensor
pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
// Read pressure sensor by passing calibration structure
ms5837 = ms5837_read(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
printf("Current Depth:\t %.3f\n",depth);
usleep(1000000);
// Write IMU values to screen
/* printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: %i Accel: %i Mag: %i\n ",
bno055.yaw, bno055.pitch, bno055.roll,
bno055.p, bno055.q, bno055.r,
bno055.sys, bno055.gyro, bno055.accel,
bno055.mag);//*/
//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw and depth control
*****************************************************************************/
void *navigation(void* arg)
{
initialize_motors(motor_channels, HERTZ);
//float output_port; // port motor output
//float output_starboard; // starboard motor output
float yaw = 0; //Local variable for if statements
//////////////yaw controller initialization////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint for yaw_controller
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize yaw_controller error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize yaw_controller gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.SAT = YAW_SAT;
yaw_pid.DT = DT; // initialize time step
/////////////depth controller initialization///////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.DT = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; //Depth controller saturation values
depth_pid.SAT = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
//bno055 = read_imu_fifo();
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) //AUV pointed right
{
yaw = substate.imu.yaw;
}
else //AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
//calculate yaw controller output
motor_percent = marchPID(substate.imu, yaw);
//set_motor(0,motor_percent); // Set port motor
//set_motor(1, motor_percent); // Set starboard motor
// Sleep for 5 ms
usleep(5000);
}
//Turn motors off; Exit cleanly
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
void *safety_thread(void* arg)
{
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
ds18b20 = read_temp_fifo();
printf("Temperature: %f degC\n", ds18b20.temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
/*if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( ds18b20.temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}//*/
// Check for leak
/*leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}*/
// Check IMU accelerometer for collision (1+ g detected)
printf("x_acc: %f\n y_acc: %f\n z_acc: %f\n",
substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc);
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Sleep a little
usleep(100000);
}
pthread_exit(NULL);
}
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<|endoftext|> |
<commit_before><commit_msg>Planning: bug fixes in open_sapce_roi_decider for PardAndGo scenario<commit_after><|endoftext|> |
<commit_before>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
// trimming params
int READ_LEN_THRESHOLD = 100000;
// BFS params in bubble popping
size_t MAX_NODES = 750;
int MAX_DISTANCE = MAX_NODES * 10000;
double MAX_DIFFERENCE = 0.25;
// contig extraction params
size_t MAX_BRANCHES = 16;
size_t MAX_START_NODES = 30;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;
// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {
int max_id = -1;
for (auto r: reads) {
max_id = max(max_id, r->getId());
}
mapped->resize(max_id + 1, nullptr);
for (auto r: reads) {
(*mapped)[r->getId()] = r;
}
}
int main(int argc, char **argv) {
cmdline::parser args;
// input params
args.add<string>("reads", 'r', "reads file", true);
args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta");
args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0);
args.add<string>("overlaps", 'x', "overlaps file", true);
args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");
args.add<bool>("verbose", 'v', "verbose output", false);
// bubble popping params
args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750);
args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25);
args.parse_check(argc, argv);
const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);
const string reads_filename = args.get<string>("reads");
const string reads_format = args.get<string>("reads_format");
const string overlaps_filename = args.get<string>("overlaps");
const string overlaps_format = args.get<string>("overlaps_format");
const bool verbose_output = args.get<bool>("verbose");
const int reads_id_offset = args.get<int>("reads_id_offset");
MAX_NODES = args.get<int>("bp_max_nodes");
MAX_DISTANCE = MAX_NODES * 10000;
MAX_DIFFERENCE = args.get<double>("bp_max_diff");
vector<Overlap*> overlaps, filtered;
vector<Read*> reads;
vector<Read*> reads_mapped;
if (reads_format == "fasta") {
readFastaReads(reads, reads_filename.c_str());
} else if (reads_format == "fastq") {
readFastqReads(reads, reads_filename.c_str());
} else if (reads_format == "afg") {
readAfgReads(reads, reads_filename.c_str());
} else {
assert(false);
}
// map reads so we have reads_mapped[read_id] -> read
map_reads(&reads_mapped, reads);
std::cerr << "Read " << reads.size() << " reads" << std::endl;
if (overlaps_format == "afg") {
readAfgOverlaps(overlaps, overlaps_filename.c_str());
} else if (overlaps_format == "mhap") {
fstream overlaps_file(overlaps_filename);
MHAP::read_overlaps(overlaps_file, &overlaps);
overlaps_file.close();
} else {
assert(false);
}
// fix overlap read ids
for (auto o: overlaps) {
o->setA(o->getA() - reads_id_offset);
o->setB(o->getB() - reads_id_offset);
}
for (auto o: overlaps) {
const auto a = o->getA();
const auto b = o->getB();
if (reads_mapped[a] == nullptr) {
cerr << "Read " << a << " not found" << endl;
exit(1);
}
if (reads_mapped[b] == nullptr) {
cerr << "Read " << b << " not found" << endl;
exit(1);
}
o->setReadA(reads_mapped[a]);
o->setReadB(reads_mapped[b]);
}
cerr << overlaps.size() << " overlaps read" << endl;
vector<Overlap*> nocontainments;
filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);
{
int filtered = overlaps.size() - nocontainments.size();
cerr << "Removed " << filtered << " overlaps as contained "
<< "(" << (1.*filtered)/overlaps.size() << ")" << endl;
}
if (verbose_output) {
writeOverlaps(nocontainments, "nocont.afg");
}
vector<Overlap*> notransitives;
filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);
{
int filtered = nocontainments.size() - notransitives.size();
cerr << "Removed " << filtered << " overlaps as transitive "
<< "(" << (1.*filtered)/nocontainments.size() << ")" << endl;
}
if (verbose_output) {
writeOverlaps(notransitives, "nocont.notran.afg");
}
createReverseComplements(reads, thread_num);
StringGraph* graph = new StringGraph(reads, notransitives);
graph->simplify();
if (verbose_output) {
vector<Overlap*> simplified_overlaps;
graph->extractOverlaps(simplified_overlaps);
writeOverlaps(notransitives, "simplified.afg");
}
std::vector<StringGraphComponent*> components;
graph->extractComponents(components);
std::vector<Contig*> contigs;
for (const auto& component : components) {
ContigExtractor* extractor = new ContigExtractor(component);
extractor->extractContig();
Contig* contig = component->createContig();
if (contig == nullptr) {
continue;
}
contigs.emplace_back(contig);
const auto& parts = contig->getParts();
fprintf(stdout, "* %lu | ", parts.size());
for (const auto& p: parts) {
fprintf(stdout, " %d", std::get<0>(p));
}
fprintf(stdout, "\n");
}
std::cerr << "number of contigs " << contigs.size() << std::endl;
writeAfgContigs(contigs, "contigs.afg");
for (auto r: reads) delete r;
for (auto o: overlaps) delete o;
for (auto c: components) delete c;
for (auto c: contigs) delete c;
delete graph;
return 0;
}
<commit_msg>fix outputting simplified graph overlaps<commit_after>
#include "cmdline/cmdline.h"
#include "mhap/overlap.h"
#include "mhap/parser.h"
#include "ra/include/ra/ra.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
// trimming params
int READ_LEN_THRESHOLD = 100000;
// BFS params in bubble popping
size_t MAX_NODES = 750;
int MAX_DISTANCE = MAX_NODES * 10000;
double MAX_DIFFERENCE = 0.25;
// contig extraction params
size_t MAX_BRANCHES = 16;
size_t MAX_START_NODES = 30;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;
// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {
int max_id = -1;
for (auto r: reads) {
max_id = max(max_id, r->getId());
}
mapped->resize(max_id + 1, nullptr);
for (auto r: reads) {
(*mapped)[r->getId()] = r;
}
}
int main(int argc, char **argv) {
cmdline::parser args;
// input params
args.add<string>("reads", 'r', "reads file", true);
args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta");
args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0);
args.add<string>("overlaps", 'x', "overlaps file", true);
args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");
args.add<bool>("verbose", 'v', "verbose output", false);
// bubble popping params
args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750);
args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25);
args.parse_check(argc, argv);
const int thread_num = std::max(std::thread::hardware_concurrency(), 1U);
const string reads_filename = args.get<string>("reads");
const string reads_format = args.get<string>("reads_format");
const string overlaps_filename = args.get<string>("overlaps");
const string overlaps_format = args.get<string>("overlaps_format");
const bool verbose_output = args.get<bool>("verbose");
const int reads_id_offset = args.get<int>("reads_id_offset");
MAX_NODES = args.get<int>("bp_max_nodes");
MAX_DISTANCE = MAX_NODES * 10000;
MAX_DIFFERENCE = args.get<double>("bp_max_diff");
vector<Overlap*> overlaps, filtered;
vector<Read*> reads;
vector<Read*> reads_mapped;
if (reads_format == "fasta") {
readFastaReads(reads, reads_filename.c_str());
} else if (reads_format == "fastq") {
readFastqReads(reads, reads_filename.c_str());
} else if (reads_format == "afg") {
readAfgReads(reads, reads_filename.c_str());
} else {
assert(false);
}
// map reads so we have reads_mapped[read_id] -> read
map_reads(&reads_mapped, reads);
std::cerr << "Read " << reads.size() << " reads" << std::endl;
if (overlaps_format == "afg") {
readAfgOverlaps(overlaps, overlaps_filename.c_str());
} else if (overlaps_format == "mhap") {
fstream overlaps_file(overlaps_filename);
MHAP::read_overlaps(overlaps_file, &overlaps);
overlaps_file.close();
} else {
assert(false);
}
// fix overlap read ids
for (auto o: overlaps) {
o->setA(o->getA() - reads_id_offset);
o->setB(o->getB() - reads_id_offset);
}
for (auto o: overlaps) {
const auto a = o->getA();
const auto b = o->getB();
if (reads_mapped[a] == nullptr) {
cerr << "Read " << a << " not found" << endl;
exit(1);
}
if (reads_mapped[b] == nullptr) {
cerr << "Read " << b << " not found" << endl;
exit(1);
}
o->setReadA(reads_mapped[a]);
o->setReadB(reads_mapped[b]);
}
cerr << overlaps.size() << " overlaps read" << endl;
vector<Overlap*> nocontainments;
filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true);
{
int filtered = overlaps.size() - nocontainments.size();
cerr << "Removed " << filtered << " overlaps as contained "
<< "(" << (1.*filtered)/overlaps.size() << ")" << endl;
}
if (verbose_output) {
writeOverlaps(nocontainments, "nocont.afg");
}
vector<Overlap*> notransitives;
filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true);
{
int filtered = nocontainments.size() - notransitives.size();
cerr << "Removed " << filtered << " overlaps as transitive "
<< "(" << (1.*filtered)/nocontainments.size() << ")" << endl;
}
if (verbose_output) {
writeOverlaps(notransitives, "nocont.notran.afg");
}
createReverseComplements(reads, thread_num);
StringGraph* graph = new StringGraph(reads, notransitives);
graph->simplify();
if (verbose_output) {
vector<Overlap*> simplified_overlaps;
graph->extractOverlaps(simplified_overlaps);
writeOverlaps(simplified_overlaps, "simplified.afg");
}
std::vector<StringGraphComponent*> components;
graph->extractComponents(components);
std::vector<Contig*> contigs;
for (const auto& component : components) {
ContigExtractor* extractor = new ContigExtractor(component);
extractor->extractContig();
Contig* contig = component->createContig();
if (contig == nullptr) {
continue;
}
contigs.emplace_back(contig);
const auto& parts = contig->getParts();
fprintf(stdout, "* %lu | ", parts.size());
for (const auto& p: parts) {
fprintf(stdout, " %d", std::get<0>(p));
}
fprintf(stdout, "\n");
}
std::cerr << "number of contigs " << contigs.size() << std::endl;
writeAfgContigs(contigs, "contigs.afg");
for (auto r: reads) delete r;
for (auto o: overlaps) delete o;
for (auto c: components) delete c;
for (auto c: contigs) delete c;
delete graph;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Planning: code clean for ROI decider.<commit_after><|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "learn_action.hh"
#include "helper.hh"
#include "params.hh"
Learn_action::Learn_action(Log&l,std::string&s): Learning(l),
constructor_param(s){
}
bool Learn_action::add_action(std::string&s) {
std::vector<std::string> alist;
commalist(s,alist);
std::vector<std::string>& names=alphabet->getActionNames();
std::vector<int> result;
for(unsigned i=0;i<alist.size();i+=2) {
std::string action_name=alist[i].substr(1,alist[i].size()-2);
std::string param;
if (i+1<alist.size()) {
param=alist[i+1];
}
Function* learning_multiplier = new_function(param);
if (learning_multiplier==NULL) {
learning_multiplier=new_function("0.5");
}
// function should be reffable...
//learning_multiplier->ref();
regexpmatch(action_name,names,result,true,1);
if (result.empty()) {
errormsg="No such action \""+action_name+"\"";
status=false;
return false;
}
for(unsigned j=0;j<result.size();j++) {
action_map[result[j]]=Learn_action::as(learning_multiplier);
}
// learning_multiplier->unref();
}
return true;
}
void Learn_action::setAlphabet(Alphabet* a) {
Learning::setAlphabet(a);
add_action(constructor_param);
constructor_param="";
std::vector<std::string>& names=alphabet->getActionNames();
unsigned actions=names.size();
pvec.resize(actions);
for(unsigned i=0;i<actions;i++) {
pvec[i].resize(actions);
}
}
void Learn_action::suggest(int action) {
suggested=true;
suggested_action=action;
}
void Learn_action::execute(int action) {
if (suggested) {
// called because something is suggested
pvec[suggested_action][action]++;
if (suggested_action==action) {
// Adapter executed what we suggested
// Nothing to do :)
} else {
// Adapter executed something else.
std::map<int,struct as>::iterator i=action_map.find(suggested_action);
if (i!=action_map.end()) {
i->second.value=i->second.value*i->second.learning_multiplier->fval();
}
}
} else {
// called because of output action?
pvec[action][action]++;
}
suggested=false;
}
float Learn_action::getF(int action) {
std::map<int,struct as>::iterator i=action_map.find(action);
if (i!=action_map.end()) {
return i->second.value;
}
return 1.0;
}
float Learn_action::getC(int sug,int exe) {
return pvec[sug][exe];
}
FACTORY_DEFAULT_CREATOR(Learning, Learn_action, "action")
<commit_msg>Remove core dumps when learning action is used without parameters<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "learn_action.hh"
#include "helper.hh"
#include "params.hh"
Learn_action::Learn_action(Log&l,std::string&s): Learning(l),
constructor_param(s){
}
bool Learn_action::add_action(std::string&s) {
std::vector<std::string> alist;
commalist(s,alist);
std::vector<std::string>& names=alphabet->getActionNames();
std::vector<int> result;
for(unsigned i=0;i<alist.size();i+=2) {
std::string action_name=alist[i].substr(1,alist[i].size()-2);
std::string param;
if (i+1<alist.size()) {
param=alist[i+1];
}
Function* learning_multiplier = new_function(param);
if (learning_multiplier==NULL) {
learning_multiplier=new_function("0.5");
}
// function should be reffable...
//learning_multiplier->ref();
regexpmatch(action_name,names,result,true,1);
if (result.empty()) {
errormsg="No such action \""+action_name+"\"";
status=false;
return false;
}
for(unsigned j=0;j<result.size();j++) {
action_map[result[j]]=Learn_action::as(learning_multiplier);
}
// learning_multiplier->unref();
}
return true;
}
void Learn_action::setAlphabet(Alphabet* a) {
Learning::setAlphabet(a);
if (constructor_param!="") {
add_action(constructor_param);
constructor_param="";
}
std::vector<std::string>& names=alphabet->getActionNames();
unsigned actions=names.size();
pvec.resize(actions);
for(unsigned i=0;i<actions;i++) {
pvec[i].resize(actions);
}
}
void Learn_action::suggest(int action) {
suggested=true;
suggested_action=action;
}
void Learn_action::execute(int action) {
if (suggested) {
// called because something is suggested
pvec[suggested_action][action]++;
if (suggested_action==action) {
// Adapter executed what we suggested
// Nothing to do :)
} else {
// Adapter executed something else.
std::map<int,struct as>::iterator i=action_map.find(suggested_action);
if (i!=action_map.end()) {
i->second.value=i->second.value*i->second.learning_multiplier->fval();
}
}
} else {
// called because of output action?
pvec[action][action]++;
}
suggested=false;
}
float Learn_action::getF(int action) {
std::map<int,struct as>::iterator i=action_map.find(action);
if (i!=action_map.end()) {
return i->second.value;
}
return 1.0;
}
float Learn_action::getC(int sug,int exe) {
return pvec[sug][exe];
}
FACTORY_DEFAULT_CREATOR(Learning, Learn_action, "action")
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
#include <iostream>
#include <string>
/*add the header if you need*/
using namespace std;
//Abstract base class for Dessert Item hierarchy
class DessertItem
{
private:
//Name of the DessertItem object
string name;
public:
DessertItem(){}
DessertItem(string name):name(name){}
//Empty virtual destructor for DessertItem class
virtual ~DessertItem(){}
//returns Name of DessertItem
string getName(){ return name;}
virtual string getDetails() = 0;
virtual double getCost() = 0;
};
class IceCream : public DessertItem
{
public:
/* Write about IceCream Constructor
IceCream(string name, double cost):DessertItem(name),cost(cost)
*/
IceCream() {}
IceCream(string name, double cost):DessertItem(name), cost(cost) {}
virtual ~IceCream() {}
/* Write about IceCream other member functions*/
virtual string getDetails() { return ""; }
virtual double getCost() { return cost; }
private:
double cost;
};
class Topping : public IceCream
{
public:
/* Write about Topping Constructor
Topping(string iceCreamName, double iceCreamCost,
string toppingName, double toppingCost)
*/
Topping() {}
Topping(string iceCreamName, double iceCreamCost, string toppingName, double toppingCost):IceCream(toppingName+" Sundae with "+iceCreamName,iceCreamCost),toppingName(toppingName),toppingCost(toppingCost+iceCreamCost) {}
virtual ~Topping() {}
/* Write about Topping other member functions*/
virtual string getDetails() { return ""; }
virtual double getCost() { return toppingCost; }
private:
string toppingName;
double toppingCost;
};
class Cookie : public DessertItem
{
public:
/* Write about Cookie Constructor
Cookie(string name, int number, double pricePerDozen)
*/
Cookie() {}
Cookie(string name, int number, double pricePerDozen):DessertItem(name),number(number),pricePerDozen(pricePerDozen) {}
virtual ~Cookie() {}
/* Write about Cookie other member functions*/
virtual string getDetails() {
stringstream s;
string strn, strp;
s << number;
s >> strn;
s.clear();
s << pricePerDozen;
s >> strp;
return "("+strn+" dozen(s) * "+strp+"/dozen)\n";
}
virtual double getCost() { return pricePerDozen*number; }
private:
//Number of dozens of Cookie
int number;
double pricePerDozen;
};
class Candy : public DessertItem
{
public:
/* Write here about Candy Constructor
Candy(string name, double weight, double pricePerGram)
*/
Candy() {}
Candy(string name, double weight, double pricePerGram):DessertItem(name),weight(weight),pricePerGram(pricePerGram) {}
virtual ~Candy() {}
/* Write about Candy other member functions*/
virtual string getDetails() {
stringstream s;
string strw, strp;
s << weight;
s >> strw;
s.clear();
s << pricePerGram;
s >> strp;
return "("+strw+" gram(s) * "+strp+"/gram)\n";
}
virtual double getCost() { return pricePerGram * weight; }
private:
//Weight of Candy
double weight;
double pricePerGram;
};
class Checkout {
public:
friend ostream &operator<<(std::ostream &, Checkout &);
/* Write about Checkout member functions
1. "enterItem" function to add the element into the list
2. "removeItem" function to remove the elemtent from the list
3. calculate the total cost and tax in the list
4. "numberOfItems" for number of Item in the list
5. "clear" clear all Items from list
*/
template<typename T>
void enterItem(T *di) {
itemList.push_back(di);
return;
}
template<typename T>
void removeItem(const T *di) {
itemList.remove(di);
return;
}
double totalCost() {
double cost = 0;
for(list<DessertItem*>::iterator it = itemList.begin(); it != itemList.end(); ++it)
cost += (*it)->getCost();
return cost;
}
double tax() {
return totalCost() * 0.05;
}
int numberOfIteams() {
return itemList.size();
}
void clear () {
itemList.clear();
return;
}
private:
list<DessertItem*> itemList;
};
ostream &operator<<(ostream &output, Checkout &checkout){
/*Overloaded operator that output a receipt for the current list of items*/
output << "Welcome to OOP’s shop\n------------------------------\n" << endl;
output << "Number of items: " << checkout.numberOfIteams() << endl << endl;
for(list<DessertItem*>::iterator it = checkout.itemList.begin(); it != checkout.itemList.end(); ++it)
output << setw(40) << left << (*it)->getName() << setw(5) << right << round((*it)->getCost()) << endl << (*it)->getDetails();
output << "\n------------------------------\n";
output << setw(40) << left << "Cost" << setw(5) << right << round(checkout.totalCost()) << endl;
output << setw(40) << left << "Tax" << setw(5) << right << round(checkout.tax()) << endl << endl;
output << setw(40) << left << "Total cost" << setw(5) << right << round(checkout.totalCost()+checkout.tax()) << endl;
output.clear();
return output;
}
<commit_msg>Modify p1.cpp<commit_after>#include <bits/stdc++.h>
#include <iostream>
#include <string>
/*add the header if you need*/
using namespace std;
//Abstract base class for Dessert Item hierarchy
class DessertItem
{
private:
//Name of the DessertItem object
string name;
public:
DessertItem(){}
DessertItem(string name):name(name){}
//Empty virtual destructor for DessertItem class
virtual ~DessertItem(){}
//returns Name of DessertItem
string getName(){ return name;}
virtual string getDetails() = 0;
virtual double getCost() = 0;
};
class IceCream : public DessertItem
{
public:
/* Write about IceCream Constructor
IceCream(string name, double cost):DessertItem(name),cost(cost)
*/
IceCream() {}
IceCream(string name, double cost):DessertItem(name), cost(cost) {}
virtual ~IceCream() {}
/* Write about IceCream other member functions*/
virtual string getDetails() { return ""; }
virtual double getCost() { return cost; }
private:
double cost;
};
class Topping : public IceCream
{
public:
/* Write about Topping Constructor
Topping(string iceCreamName, double iceCreamCost,
string toppingName, double toppingCost)
*/
Topping() {}
Topping(string iceCreamName, double iceCreamCost, string toppingName, double toppingCost):IceCream(toppingName+" Sundae with "+iceCreamName,iceCreamCost),toppingName(toppingName),toppingCost(toppingCost) {}
virtual ~Topping() {}
/* Write about Topping other member functions*/
virtual string getDetails() { return ""; }
virtual double getCost() { return toppingCost + IceCream::getCost(); }
private:
string toppingName;
double toppingCost;
};
class Cookie : public DessertItem
{
public:
/* Write about Cookie Constructor
Cookie(string name, int number, double pricePerDozen)
*/
Cookie() {}
Cookie(string name, int number, double pricePerDozen):DessertItem(name),number(number),pricePerDozen(pricePerDozen) {}
virtual ~Cookie() {}
/* Write about Cookie other member functions*/
virtual string getDetails() {
stringstream s;
string strn, strp;
s << number;
s >> strn;
s.clear();
s << pricePerDozen;
s >> strp;
return "("+strn+" dozen(s) * "+strp+"/dozen)\n";
}
virtual double getCost() { return pricePerDozen*number; }
private:
//Number of dozens of Cookie
int number;
double pricePerDozen;
};
class Candy : public DessertItem
{
public:
/* Write here about Candy Constructor
Candy(string name, double weight, double pricePerGram)
*/
Candy() {}
Candy(string name, double weight, double pricePerGram):DessertItem(name),weight(weight),pricePerGram(pricePerGram) {}
virtual ~Candy() {}
/* Write about Candy other member functions*/
virtual string getDetails() {
stringstream s;
string strw, strp;
s << weight;
s >> strw;
s.clear();
s << pricePerGram;
s >> strp;
return "("+strw+" gram(s) * "+strp+"/gram)\n";
}
virtual double getCost() { return pricePerGram * weight; }
private:
//Weight of Candy
double weight;
double pricePerGram;
};
class Checkout {
public:
friend ostream &operator<<(std::ostream &, Checkout &);
/* Write about Checkout member functions
1. "enterItem" function to add the element into the list
2. "removeItem" function to remove the elemtent from the list
3. calculate the total cost and tax in the list
4. "numberOfItems" for number of Item in the list
5. "clear" clear all Items from list
*/
template<typename T>
void enterItem(T *di) {
itemList.push_back(di);
return;
}
template<typename T>
void removeItem(const T *di) {
itemList.remove(di);
return;
}
double totalCost() {
double cost = 0;
for(list<DessertItem*>::iterator it = itemList.begin(); it != itemList.end(); ++it)
cost += (*it)->getCost();
return cost;
}
double tax() {
return totalCost() * 0.05;
}
int numberOfIteams() {
return itemList.size();
}
void clear () {
itemList.clear();
return;
}
private:
list<DessertItem*> itemList;
};
ostream &operator<<(ostream &output, Checkout &checkout){
/*Overloaded operator that output a receipt for the current list of items*/
output << "Welcome to OOP’s shop\n------------------------------\n" << endl;
output << "Number of items: " << checkout.numberOfIteams() << endl << endl;
for(list<DessertItem*>::iterator it = checkout.itemList.begin(); it != checkout.itemList.end(); ++it)
output << setw(40) << left << (*it)->getName() << setw(5) << right << round((*it)->getCost()) << endl << (*it)->getDetails();
output << "\n------------------------------\n";
output << setw(40) << left << "Cost" << setw(5) << right << round(checkout.totalCost()) << endl;
output << setw(40) << left << "Tax" << setw(5) << right << round(checkout.tax()) << endl << endl;
output << setw(40) << left << "Total cost" << setw(5) << right << round(checkout.totalCost()+checkout.tax()) << endl;
output.clear();
return output;
}
<|endoftext|> |
<commit_before><commit_msg>Updated tests for DirectXHelpers<commit_after><|endoftext|> |
<commit_before>#include "config.h"
#include <iostream>
#include <cstring>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include "hash.hh"
#include "archive.hh"
#include "util.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace nix {
Hash::Hash()
{
type = htUnknown;
hashSize = 0;
memset(hash, 0, maxHashSize);
}
Hash::Hash(HashType type)
{
this->type = type;
if (type == htMD5) hashSize = md5HashSize;
else if (type == htSHA1) hashSize = sha1HashSize;
else if (type == htSHA256) hashSize = sha256HashSize;
else if (type == htSHA512) hashSize = sha512HashSize;
else abort();
assert(hashSize <= maxHashSize);
memset(hash, 0, maxHashSize);
}
bool Hash::operator == (const Hash & h2) const
{
if (hashSize != h2.hashSize) return false;
for (unsigned int i = 0; i < hashSize; i++)
if (hash[i] != h2.hash[i]) return false;
return true;
}
bool Hash::operator != (const Hash & h2) const
{
return !(*this == h2);
}
bool Hash::operator < (const Hash & h) const
{
for (unsigned int i = 0; i < hashSize; i++) {
if (hash[i] < h.hash[i]) return true;
if (hash[i] > h.hash[i]) return false;
}
return false;
}
std::string Hash::to_string(bool base32) const
{
return printHashType(type) + ":" + (base32 ? printHash32(*this) : printHash(*this));
}
const string base16Chars = "0123456789abcdef";
string printHash(const Hash & hash)
{
char buf[hash.hashSize * 2];
for (unsigned int i = 0; i < hash.hashSize; i++) {
buf[i * 2] = base16Chars[hash.hash[i] >> 4];
buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f];
}
return string(buf, hash.hashSize * 2);
}
Hash parseHash(const string & s)
{
string::size_type colon = s.find(':');
if (colon == string::npos)
throw BadHash(format("invalid hash ‘%s’") % s);
string hts = string(s, 0, colon);
HashType ht = parseHashType(hts);
if (ht == htUnknown)
throw BadHash(format("unknown hash type ‘%s’") % hts);
return parseHash16or32(ht, string(s, colon + 1));
}
Hash parseHash(HashType ht, const string & s)
{
Hash hash(ht);
if (s.length() != hash.hashSize * 2)
throw BadHash(format("invalid hash ‘%1%’") % s);
for (unsigned int i = 0; i < hash.hashSize; i++) {
string s2(s, i * 2, 2);
if (!isxdigit(s2[0]) || !isxdigit(s2[1]))
throw BadHash(format("invalid hash ‘%1%’") % s);
std::istringstream str(s2);
int n;
str >> std::hex >> n;
hash.hash[i] = n;
}
return hash;
}
// omitted: E O U T
const string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz";
string printHash32(const Hash & hash)
{
assert(hash.type != htUnknown);
size_t len = hash.base32Len();
assert(len);
string s;
s.reserve(len);
for (int n = len - 1; n >= 0; n--) {
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
unsigned char c =
(hash.hash[i] >> j)
| (i >= hash.hashSize - 1 ? 0 : hash.hash[i + 1] << (8 - j));
s.push_back(base32Chars[c & 0x1f]);
}
return s;
}
string printHash16or32(const Hash & hash)
{
return hash.type == htMD5 ? printHash(hash) : printHash32(hash);
}
Hash parseHash32(HashType ht, const string & s)
{
Hash hash(ht);
size_t len = hash.base32Len();
assert(s.size() == len);
for (unsigned int n = 0; n < len; ++n) {
char c = s[len - n - 1];
unsigned char digit;
for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */
if (base32Chars[digit] == c) break;
if (digit >= 32)
throw BadHash(format("invalid base-32 hash ‘%1%’") % s);
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
hash.hash[i] |= digit << j;
if (i < hash.hashSize - 1) hash.hash[i + 1] |= digit >> (8 - j);
}
return hash;
}
Hash parseHash16or32(HashType ht, const string & s)
{
Hash hash(ht);
if (s.size() == hash.hashSize * 2)
/* hexadecimal representation */
hash = parseHash(ht, s);
else if (s.size() == hash.base32Len())
/* base-32 representation */
hash = parseHash32(ht, s);
else
throw BadHash(format("hash ‘%1%’ has wrong length for hash type ‘%2%’")
% s % printHashType(ht));
return hash;
}
bool isHash(const string & s)
{
if (s.length() != 32) return false;
for (int i = 0; i < 32; i++) {
char c = s[i];
if (!((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f')))
return false;
}
return true;
}
union Ctx
{
MD5_CTX md5;
SHA_CTX sha1;
SHA256_CTX sha256;
SHA512_CTX sha512;
};
static void start(HashType ht, Ctx & ctx)
{
if (ht == htMD5) MD5_Init(&ctx.md5);
else if (ht == htSHA1) SHA1_Init(&ctx.sha1);
else if (ht == htSHA256) SHA256_Init(&ctx.sha256);
else if (ht == htSHA512) SHA512_Init(&ctx.sha512);
}
static void update(HashType ht, Ctx & ctx,
const unsigned char * bytes, unsigned int len)
{
if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len);
else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len);
else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len);
else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len);
}
static void finish(HashType ht, Ctx & ctx, unsigned char * hash)
{
if (ht == htMD5) MD5_Final(hash, &ctx.md5);
else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1);
else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256);
else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512);
}
Hash hashString(HashType ht, const string & s)
{
Ctx ctx;
Hash hash(ht);
start(ht, ctx);
update(ht, ctx, (const unsigned char *) s.data(), s.length());
finish(ht, ctx, hash.hash);
return hash;
}
Hash hashFile(HashType ht, const Path & path)
{
Ctx ctx;
Hash hash(ht);
start(ht, ctx);
AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (!fd) throw SysError(format("opening file ‘%1%’") % path);
unsigned char buf[8192];
ssize_t n;
while ((n = read(fd.get(), buf, sizeof(buf)))) {
checkInterrupt();
if (n == -1) throw SysError(format("reading file ‘%1%’") % path);
update(ht, ctx, buf, n);
}
finish(ht, ctx, hash.hash);
return hash;
}
HashSink::HashSink(HashType ht) : ht(ht)
{
ctx = new Ctx;
bytes = 0;
start(ht, *ctx);
}
HashSink::~HashSink()
{
bufPos = 0;
delete ctx;
}
void HashSink::write(const unsigned char * data, size_t len)
{
bytes += len;
update(ht, *ctx, data, len);
}
HashResult HashSink::finish()
{
flush();
Hash hash(ht);
nix::finish(ht, *ctx, hash.hash);
return HashResult(hash, bytes);
}
HashResult HashSink::currentHash()
{
flush();
Ctx ctx2 = *ctx;
Hash hash(ht);
nix::finish(ht, ctx2, hash.hash);
return HashResult(hash, bytes);
}
HashResult hashPath(
HashType ht, const Path & path, PathFilter & filter)
{
HashSink sink(ht);
dumpPath(path, sink, filter);
return sink.finish();
}
Hash compressHash(const Hash & hash, unsigned int newSize)
{
Hash h;
h.hashSize = newSize;
for (unsigned int i = 0; i < hash.hashSize; ++i)
h.hash[i % newSize] ^= hash.hash[i];
return h;
}
HashType parseHashType(const string & s)
{
if (s == "md5") return htMD5;
else if (s == "sha1") return htSHA1;
else if (s == "sha256") return htSHA256;
else if (s == "sha512") return htSHA512;
else return htUnknown;
}
string printHashType(HashType ht)
{
if (ht == htMD5) return "md5";
else if (ht == htSHA1) return "sha1";
else if (ht == htSHA256) return "sha256";
else if (ht == htSHA512) return "sha512";
else abort();
}
}
<commit_msg>Fix assertion failure<commit_after>#include "config.h"
#include <iostream>
#include <cstring>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include "hash.hh"
#include "archive.hh"
#include "util.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace nix {
Hash::Hash()
{
type = htUnknown;
hashSize = 0;
memset(hash, 0, maxHashSize);
}
Hash::Hash(HashType type)
{
this->type = type;
if (type == htMD5) hashSize = md5HashSize;
else if (type == htSHA1) hashSize = sha1HashSize;
else if (type == htSHA256) hashSize = sha256HashSize;
else if (type == htSHA512) hashSize = sha512HashSize;
else abort();
assert(hashSize <= maxHashSize);
memset(hash, 0, maxHashSize);
}
bool Hash::operator == (const Hash & h2) const
{
if (hashSize != h2.hashSize) return false;
for (unsigned int i = 0; i < hashSize; i++)
if (hash[i] != h2.hash[i]) return false;
return true;
}
bool Hash::operator != (const Hash & h2) const
{
return !(*this == h2);
}
bool Hash::operator < (const Hash & h) const
{
for (unsigned int i = 0; i < hashSize; i++) {
if (hash[i] < h.hash[i]) return true;
if (hash[i] > h.hash[i]) return false;
}
return false;
}
std::string Hash::to_string(bool base32) const
{
return printHashType(type) + ":" + (base32 ? printHash32(*this) : printHash(*this));
}
const string base16Chars = "0123456789abcdef";
string printHash(const Hash & hash)
{
char buf[hash.hashSize * 2];
for (unsigned int i = 0; i < hash.hashSize; i++) {
buf[i * 2] = base16Chars[hash.hash[i] >> 4];
buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f];
}
return string(buf, hash.hashSize * 2);
}
Hash parseHash(const string & s)
{
string::size_type colon = s.find(':');
if (colon == string::npos)
throw BadHash(format("invalid hash ‘%s’") % s);
string hts = string(s, 0, colon);
HashType ht = parseHashType(hts);
if (ht == htUnknown)
throw BadHash(format("unknown hash type ‘%s’") % hts);
return parseHash16or32(ht, string(s, colon + 1));
}
Hash parseHash(HashType ht, const string & s)
{
Hash hash(ht);
if (s.length() != hash.hashSize * 2)
throw BadHash(format("invalid hash ‘%1%’") % s);
for (unsigned int i = 0; i < hash.hashSize; i++) {
string s2(s, i * 2, 2);
if (!isxdigit(s2[0]) || !isxdigit(s2[1]))
throw BadHash(format("invalid hash ‘%1%’") % s);
std::istringstream str(s2);
int n;
str >> std::hex >> n;
hash.hash[i] = n;
}
return hash;
}
// omitted: E O U T
const string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz";
string printHash32(const Hash & hash)
{
assert(hash.hashSize);
size_t len = hash.base32Len();
assert(len);
string s;
s.reserve(len);
for (int n = len - 1; n >= 0; n--) {
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
unsigned char c =
(hash.hash[i] >> j)
| (i >= hash.hashSize - 1 ? 0 : hash.hash[i + 1] << (8 - j));
s.push_back(base32Chars[c & 0x1f]);
}
return s;
}
string printHash16or32(const Hash & hash)
{
return hash.type == htMD5 ? printHash(hash) : printHash32(hash);
}
Hash parseHash32(HashType ht, const string & s)
{
Hash hash(ht);
size_t len = hash.base32Len();
assert(s.size() == len);
for (unsigned int n = 0; n < len; ++n) {
char c = s[len - n - 1];
unsigned char digit;
for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */
if (base32Chars[digit] == c) break;
if (digit >= 32)
throw BadHash(format("invalid base-32 hash ‘%1%’") % s);
unsigned int b = n * 5;
unsigned int i = b / 8;
unsigned int j = b % 8;
hash.hash[i] |= digit << j;
if (i < hash.hashSize - 1) hash.hash[i + 1] |= digit >> (8 - j);
}
return hash;
}
Hash parseHash16or32(HashType ht, const string & s)
{
Hash hash(ht);
if (s.size() == hash.hashSize * 2)
/* hexadecimal representation */
hash = parseHash(ht, s);
else if (s.size() == hash.base32Len())
/* base-32 representation */
hash = parseHash32(ht, s);
else
throw BadHash(format("hash ‘%1%’ has wrong length for hash type ‘%2%’")
% s % printHashType(ht));
return hash;
}
bool isHash(const string & s)
{
if (s.length() != 32) return false;
for (int i = 0; i < 32; i++) {
char c = s[i];
if (!((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f')))
return false;
}
return true;
}
union Ctx
{
MD5_CTX md5;
SHA_CTX sha1;
SHA256_CTX sha256;
SHA512_CTX sha512;
};
static void start(HashType ht, Ctx & ctx)
{
if (ht == htMD5) MD5_Init(&ctx.md5);
else if (ht == htSHA1) SHA1_Init(&ctx.sha1);
else if (ht == htSHA256) SHA256_Init(&ctx.sha256);
else if (ht == htSHA512) SHA512_Init(&ctx.sha512);
}
static void update(HashType ht, Ctx & ctx,
const unsigned char * bytes, unsigned int len)
{
if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len);
else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len);
else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len);
else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len);
}
static void finish(HashType ht, Ctx & ctx, unsigned char * hash)
{
if (ht == htMD5) MD5_Final(hash, &ctx.md5);
else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1);
else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256);
else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512);
}
Hash hashString(HashType ht, const string & s)
{
Ctx ctx;
Hash hash(ht);
start(ht, ctx);
update(ht, ctx, (const unsigned char *) s.data(), s.length());
finish(ht, ctx, hash.hash);
return hash;
}
Hash hashFile(HashType ht, const Path & path)
{
Ctx ctx;
Hash hash(ht);
start(ht, ctx);
AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (!fd) throw SysError(format("opening file ‘%1%’") % path);
unsigned char buf[8192];
ssize_t n;
while ((n = read(fd.get(), buf, sizeof(buf)))) {
checkInterrupt();
if (n == -1) throw SysError(format("reading file ‘%1%’") % path);
update(ht, ctx, buf, n);
}
finish(ht, ctx, hash.hash);
return hash;
}
HashSink::HashSink(HashType ht) : ht(ht)
{
ctx = new Ctx;
bytes = 0;
start(ht, *ctx);
}
HashSink::~HashSink()
{
bufPos = 0;
delete ctx;
}
void HashSink::write(const unsigned char * data, size_t len)
{
bytes += len;
update(ht, *ctx, data, len);
}
HashResult HashSink::finish()
{
flush();
Hash hash(ht);
nix::finish(ht, *ctx, hash.hash);
return HashResult(hash, bytes);
}
HashResult HashSink::currentHash()
{
flush();
Ctx ctx2 = *ctx;
Hash hash(ht);
nix::finish(ht, ctx2, hash.hash);
return HashResult(hash, bytes);
}
HashResult hashPath(
HashType ht, const Path & path, PathFilter & filter)
{
HashSink sink(ht);
dumpPath(path, sink, filter);
return sink.finish();
}
Hash compressHash(const Hash & hash, unsigned int newSize)
{
Hash h;
h.hashSize = newSize;
for (unsigned int i = 0; i < hash.hashSize; ++i)
h.hash[i % newSize] ^= hash.hash[i];
return h;
}
HashType parseHashType(const string & s)
{
if (s == "md5") return htMD5;
else if (s == "sha1") return htSHA1;
else if (s == "sha256") return htSHA256;
else if (s == "sha512") return htSHA512;
else return htUnknown;
}
string printHashType(HashType ht)
{
if (ht == htMD5) return "md5";
else if (ht == htSHA1) return "sha1";
else if (ht == htSHA256) return "sha256";
else if (ht == htSHA512) return "sha512";
else abort();
}
}
<|endoftext|> |
<commit_before>#include <map>
#include <llvm/IR/Value.h>
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/raw_ostream.h>
#include "LLVMNode.h"
#include "LLVMDependenceGraph.h"
#include "DefUse.h"
#include "AnalysisGeneric.h"
#include "analysis/DFS.h"
using namespace llvm;
namespace dg {
namespace analysis {
LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg)
: DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), DATAFLOW_INTERPROCEDURAL),
dg(dg)
{
Module *m = dg->getModule();
// set data layout
DL = m->getDataLayout();
}
Pointer LLVMDefUseAnalysis::getConstantExprPointer(const ConstantExpr *CE)
{
return dg::analysis::getConstantExprPointer(CE, dg, DL);
}
DefMap::DefMap(const DefMap& o)
{
merge(&o);
}
bool DefMap::merge(const DefMap *oth, PointsToSetT *without)
{
bool changed = false;
if (this == oth)
return false;
for (auto it : oth->defs) {
const Pointer& ptr = it.first;
// should we skip this pointer
if (without && without->count(ptr) != 0)
continue;
// our values that we have for
// this pointer
ValuesSetT& our_vals = defs[ptr];
// copy values that have map oth for the
// pointer to our values
for (LLVMNode *defnode : it.second) {
changed |= our_vals.insert(defnode).second;
}
}
return changed;
}
bool DefMap::add(const Pointer& p, LLVMNode *n)
{
return defs[p].insert(n).second;
}
bool DefMap::update(const Pointer& p, LLVMNode *n)
{
bool ret;
ValuesSetT& dfs = defs[p];
ret = dfs.count(n) == 0 || dfs.size() > 1;
dfs.clear();
dfs.insert(n);
return ret;
}
static DefMap *getDefMap(LLVMNode *n)
{
DefMap *r = n->getData<DefMap>();
if (!r) {
r = new DefMap();
n->setData(r);
}
// must always have
assert(r);
return r;
}
/// --------------------------------------------------
// Reaching definitions analysis
/// --------------------------------------------------
static bool handleCallInst(LLVMDependenceGraph *graph,
LLVMNode *callNode, DefMap *df)
{
bool changed = false;
LLVMNode *exitNode = graph->getExit();
assert(exitNode && "No exit node in subgraph");
DefMap *subgraph_df = getDefMap(exitNode);
// get actual parameters (operands) and for every pointer in there
// check if the memory location it points to get defined
// in the subprocedure
LLVMNode **operands = callNode->getOperands();
LLVMDGParameters *params = callNode->getParameters();
// we call this func only on non-void functions
assert(params && "No actual parameters in call node");
// operand[0] is the called func
for (int i = 1, e = callNode->getOperandsNum(); i < e; ++i) {
LLVMNode *op = operands[i];
if (!op)
continue;
if (!op->isPointerTy())
continue;
for (const Pointer& ptr : op->getPointsTo()) {
ValuesSetT& defs = subgraph_df->get(ptr);
if (defs.empty())
continue;
// ok, the memory location is defined in the subprocedure,
// so add reaching definition to out param of this call node
LLVMDGParameter *p = params->find(op->getKey());
if (!p) {
errs() << "ERR: no actual param for value: "
<< *op->getKey() << "\n";
abort();
}
changed |= df->add(ptr, p->out);
}
}
return changed;
}
static bool handleCallInst(LLVMNode *callNode, DefMap *df)
{
bool changed = false;
// ignore callInst with void prototype
if (callNode->getOperandsNum() == 1)
return false;
for (LLVMDependenceGraph *subgraph : callNode->getSubgraphs())
changed |= handleCallInst(subgraph, callNode, df);
return changed;
}
static bool handleStoreInst(LLVMNode *storeNode, DefMap *df,
PointsToSetT *&strong_update)
{
bool changed = false;
LLVMNode *ptrNode = storeNode->getOperand(0);
assert(ptrNode && "No pointer operand");
// update definitions
PointsToSetT& S = ptrNode->getPointsTo();
if (S.size() == 1) {// strong update
changed |= df->update(*S.begin(), storeNode);
strong_update = &S;
} else { // weak update
for (const Pointer& ptr : ptrNode->getPointsTo())
changed |= df->add(ptr, storeNode);
}
return changed;
}
bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node)
{
bool changed = false;
// pointers that should not be updated
// because they were updated strongly
PointsToSetT *strong_update = nullptr;
// update states according to predcessors
DefMap *df = getDefMap(node);
LLVMNode *pred = node->getPredcessor();
if (pred) {
const Value *predVal = pred->getKey();
// if the predcessor is StoreInst, it add and may kill some definitions
if (isa<StoreInst>(predVal))
changed |= dg::analysis::handleStoreInst(pred, df, strong_update);
// call inst may add some definitions to (StoreInst in subgraph)
else if (isa<CallInst>(predVal))
changed |= dg::analysis::handleCallInst(pred, df);
changed |= df->merge(getDefMap(pred), strong_update);
} else { // BB predcessors
LLVMBBlock *BB = node->getBasicBlock();
assert(BB && "Node has no BB");
for (auto predBB : BB->predcessors()) {
pred = predBB->getLastNode();
assert(pred && "BB has no last node");
const Value *predVal = pred->getKey();
if (isa<StoreInst>(predVal))
changed |= dg::analysis::handleStoreInst(pred, df, strong_update);
else if (isa<CallInst>(predVal))
changed |= dg::analysis::handleCallInst(pred, df);
df->merge(getDefMap(pred), nullptr);
}
}
return changed;
}
} // namespace analysis
} // namespace dg
/// --------------------------------------------------
// Add def-use edges
/// --------------------------------------------------
namespace dg {
namespace analysis {
LLVMNode *LLVMDefUseAnalysis::getOperand(LLVMNode *node,
const Value *val, unsigned int idx)
{
return dg::analysis::getOperand(node, val, idx, DL);
}
static void addIndirectDefUsePtr(const Pointer& ptr, LLVMNode *to, DefMap *df)
{
if (ptr.isNull() || ptr.obj->isUnknown()) {
errs() << "ERR: pointer pointing to unknown location, UNSOUND! "
<< *to->getKey() << "\n";
return;
}
LLVMNode *ptrnode = ptr.obj->node;
const Value *ptrVal = ptrnode->getKey();
// functions does not have indirect reaching definitions
if (isa<Function>(ptrVal))
return;
ValuesSetT& defs = df->get(ptr);
// do we have any reaching definition at all?
if (defs.empty()) {
// we do not add initial def to global variables because not all
// global variables could be used in the code and we'd redundantly
// iterate through the defintions. Do it lazily here.
if (isa<GlobalVariable>(ptrVal)) {
// ok, so the GV was defined in initialization phase,
// so the reaching definition for the ptr is there.
// If it was not defined, then we still want the edge
// from the global node in this case
defs.insert(ptrnode);
} else if (isa<AllocaInst>(ptrVal)) {
// AllocaInst without any reaching definition
// may mean that the value is undefined. Nevertheless
// we use the value that is defined via the AllocaInst,
// so add definition on the AllocaInst
// This is the same as with global variables
defs.insert(ptrnode);
} else {
errs() << "WARN: no reaching definition for "
<< *ptr.obj->node->getKey()
<< " + " << *ptr.offset << "\n";
return;
}
}
assert(!defs.empty());
for (LLVMNode *n : defs)
n->addDataDependence(to);
// if we got pointer to our object with UNKNOWN_OFFSET,
// it still can be reaching definition, so we must take it into
// account
ValuesSetT& defsUnknown = df->get(Pointer(ptr.obj, UNKNOWN_OFFSET));
if (!defsUnknown.empty()) {
for (LLVMNode *n : defsUnknown)
n->addDataDependence(to);
}
}
static void addIndirectDefUse(LLVMNode *ptrNode, LLVMNode *to, DefMap *df)
{
// iterate over all memory locations that this
// store can define and check where they are defined
for (const Pointer& ptr : ptrNode->getPointsTo())
addIndirectDefUsePtr(ptr, to, df);
}
// return Value used on operand LLVMNode
// It is either the operand itself or
// global value used in ConstantExpr if the
// operand is ConstantExpr
static void addStoreLoadInstDefUse(LLVMNode *storeNode, LLVMNode *op, DefMap *df)
{
const Value *val = op->getKey();
if (isa<ConstantExpr>(val)) {
// it should be one ptr
PointsToSetT& PS = op->getPointsTo();
assert(PS.size() == 1);
const Pointer& ptr = *PS.begin();
addIndirectDefUsePtr(ptr, storeNode, df);
} else {
op->addDataDependence(storeNode);
}
}
void LLVMDefUseAnalysis::handleStoreInst(const StoreInst *Inst, LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode *valNode = node->getOperand(1);
// this node uses what is defined on valNode
if (valNode) {
addStoreLoadInstDefUse(node, valNode, df);
}
#ifdef DEBUG_ENABLED
else {
if (!isa<ConstantInt>(Inst->getValueOperand()))
errs() << "ERR def-use: Unhandled value operand for "
<< *Inst << "\n";
}
#endif
LLVMNode *ptrNode = node->getOperand(0);
assert(ptrNode);
// and also uses what is defined on ptrNode
addStoreLoadInstDefUse(node, ptrNode, df);
}
void LLVMDefUseAnalysis::handleLoadInst(LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode *ptrNode = node->getOperand(0);
assert(ptrNode && "No ptr node");
// load inst is reading from the memory,
// so add indirect def-use edges
addIndirectDefUse(ptrNode, node, df);
// load inst is reading from the memory that is pointed by
// the top-level value, so add def-use edge
addStoreLoadInstDefUse(node, ptrNode, df);
}
static void addOutParamsEdges(LLVMDependenceGraph *graph)
{
LLVMDGParameters *params = graph->getParameters();
assert(params && "No formal params in subgraph with actual params");
LLVMNode *exitNode = graph->getExit();
assert(exitNode && "No exit node in subgraph");
DefMap *df = getDefMap(exitNode);
for (auto it : *params) {
const Value *val = it.first;
if (!val->getType()->isPointerTy())
continue;
LLVMDGParameter& p = it.second;
// points to set is contained in the input param
for (const Pointer& ptr : p.in->getPointsTo()) {
ValuesSetT& defs = df->get(ptr);
if (defs.empty())
continue;
// ok, the memory location is defined in this subgraph,
// so add data dependence edge to the out param
for (LLVMNode *def : defs)
def->addDataDependence(p.out);
}
}
}
static void addOutParamsEdges(LLVMNode *callNode)
{
for (LLVMDependenceGraph *subgraph : callNode->getSubgraphs()) {
addOutParamsEdges(subgraph);
// FIXME we're loosing some accuracy here and
// this edges causes that we'll go into subprocedure
// even with summary edges
if (!callNode->isVoidTy())
subgraph->getExit()->addDataDependence(callNode);
}
}
static void handleCallInst(LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode **operands = node->getOperands();
LLVMDGParameters *params = node->getParameters();
// if we have a node for the called function,
// it is call via function pointer, so add the
// data dependence edge to corresponding node
if (operands[0]) {
operands[0]->addDataDependence(node);
}
if (!params) // function has no arguments
return;
// parameters begin from 1
for (int i = 1, e = node->getOperandsNum(); i < e; ++i) {
LLVMNode *op = operands[i];
if (!op)
continue;
// find actual parameter
LLVMDGParameter *p = params->find(op->getKey());
if (!p) {
errs() << "ERR: no actual parameter for " << *op->getKey() << "\n";
continue;
}
if (op->isPointerTy()) {
// add data dependencies to in parameters
addIndirectDefUse(op, p->in, df);
// FIXME
// look for reaching definitions inside the procedure
// because since this is a pointer, we can change things
} else
op->addDataDependence(p->in);
}
addOutParamsEdges(node);
}
static void handleInstruction(const Instruction *Inst, LLVMNode *node)
{
LLVMDependenceGraph *dg = node->getDG();
for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) {
LLVMNode *op = dg->getNode(*I);
if (op)
op->addDataDependence(node);
#ifdef DEBUG_ENABLED
else if (!isa<ConstantInt>(*I) && !isa<BranchInst>(Inst))
errs() << "WARN: no node for operand " << **I
<< "in " << *Inst << "\n";
#endif
}
}
void LLVMDefUseAnalysis::handleNode(LLVMNode *node)
{
const Value *val = node->getKey();
if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) {
handleStoreInst(Inst, node);
} else if (isa<LoadInst>(val)) {
handleLoadInst(node);
} else if (isa<CallInst>(val)) {
handleCallInst(node);
} else if (const Instruction *Inst = dyn_cast<Instruction>(val)) {
handleInstruction(Inst, node); // handle rest of Insts
}
}
void handleBlock(LLVMBBlock *BB, LLVMDefUseAnalysis *analysis)
{
LLVMNode *n = BB->getFirstNode();
while (n) {
analysis->handleNode(n);
n = n->getSuccessor();
}
}
void LLVMDefUseAnalysis::addDefUseEdges()
{
// it doesn't matter how we'll go through the nodes
BBlockDFS<LLVMNode> runner(DFS_INTERPROCEDURAL);
runner.run(dg->getEntryBB(), handleBlock, this);
}
} // namespace analysis
} // namespace dg
<commit_msg>def-use: handle nullptr value<commit_after>#include <map>
#include <llvm/IR/Value.h>
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/raw_ostream.h>
#include "LLVMNode.h"
#include "LLVMDependenceGraph.h"
#include "DefUse.h"
#include "AnalysisGeneric.h"
#include "analysis/DFS.h"
using namespace llvm;
namespace dg {
namespace analysis {
LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg)
: DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), DATAFLOW_INTERPROCEDURAL),
dg(dg)
{
Module *m = dg->getModule();
// set data layout
DL = m->getDataLayout();
}
Pointer LLVMDefUseAnalysis::getConstantExprPointer(const ConstantExpr *CE)
{
return dg::analysis::getConstantExprPointer(CE, dg, DL);
}
DefMap::DefMap(const DefMap& o)
{
merge(&o);
}
bool DefMap::merge(const DefMap *oth, PointsToSetT *without)
{
bool changed = false;
if (this == oth)
return false;
for (auto it : oth->defs) {
const Pointer& ptr = it.first;
// should we skip this pointer
if (without && without->count(ptr) != 0)
continue;
// our values that we have for
// this pointer
ValuesSetT& our_vals = defs[ptr];
// copy values that have map oth for the
// pointer to our values
for (LLVMNode *defnode : it.second) {
changed |= our_vals.insert(defnode).second;
}
}
return changed;
}
bool DefMap::add(const Pointer& p, LLVMNode *n)
{
return defs[p].insert(n).second;
}
bool DefMap::update(const Pointer& p, LLVMNode *n)
{
bool ret;
ValuesSetT& dfs = defs[p];
ret = dfs.count(n) == 0 || dfs.size() > 1;
dfs.clear();
dfs.insert(n);
return ret;
}
static DefMap *getDefMap(LLVMNode *n)
{
DefMap *r = n->getData<DefMap>();
if (!r) {
r = new DefMap();
n->setData(r);
}
// must always have
assert(r);
return r;
}
/// --------------------------------------------------
// Reaching definitions analysis
/// --------------------------------------------------
static bool handleCallInst(LLVMDependenceGraph *graph,
LLVMNode *callNode, DefMap *df)
{
bool changed = false;
LLVMNode *exitNode = graph->getExit();
assert(exitNode && "No exit node in subgraph");
DefMap *subgraph_df = getDefMap(exitNode);
// get actual parameters (operands) and for every pointer in there
// check if the memory location it points to get defined
// in the subprocedure
LLVMNode **operands = callNode->getOperands();
LLVMDGParameters *params = callNode->getParameters();
// we call this func only on non-void functions
assert(params && "No actual parameters in call node");
// operand[0] is the called func
for (int i = 1, e = callNode->getOperandsNum(); i < e; ++i) {
LLVMNode *op = operands[i];
if (!op)
continue;
if (!op->isPointerTy())
continue;
for (const Pointer& ptr : op->getPointsTo()) {
ValuesSetT& defs = subgraph_df->get(ptr);
if (defs.empty())
continue;
// ok, the memory location is defined in the subprocedure,
// so add reaching definition to out param of this call node
LLVMDGParameter *p = params->find(op->getKey());
if (!p) {
errs() << "ERR: no actual param for value: "
<< *op->getKey() << "\n";
abort();
}
changed |= df->add(ptr, p->out);
}
}
return changed;
}
static bool handleCallInst(LLVMNode *callNode, DefMap *df)
{
bool changed = false;
// ignore callInst with void prototype
if (callNode->getOperandsNum() == 1)
return false;
for (LLVMDependenceGraph *subgraph : callNode->getSubgraphs())
changed |= handleCallInst(subgraph, callNode, df);
return changed;
}
static bool handleStoreInst(LLVMNode *storeNode, DefMap *df,
PointsToSetT *&strong_update)
{
bool changed = false;
LLVMNode *ptrNode = storeNode->getOperand(0);
assert(ptrNode && "No pointer operand");
// update definitions
PointsToSetT& S = ptrNode->getPointsTo();
if (S.size() == 1) {// strong update
changed |= df->update(*S.begin(), storeNode);
strong_update = &S;
} else { // weak update
for (const Pointer& ptr : ptrNode->getPointsTo())
changed |= df->add(ptr, storeNode);
}
return changed;
}
bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node)
{
bool changed = false;
// pointers that should not be updated
// because they were updated strongly
PointsToSetT *strong_update = nullptr;
// update states according to predcessors
DefMap *df = getDefMap(node);
LLVMNode *pred = node->getPredcessor();
if (pred) {
const Value *predVal = pred->getKey();
// if the predcessor is StoreInst, it add and may kill some definitions
if (isa<StoreInst>(predVal))
changed |= dg::analysis::handleStoreInst(pred, df, strong_update);
// call inst may add some definitions to (StoreInst in subgraph)
else if (isa<CallInst>(predVal))
changed |= dg::analysis::handleCallInst(pred, df);
changed |= df->merge(getDefMap(pred), strong_update);
} else { // BB predcessors
LLVMBBlock *BB = node->getBasicBlock();
assert(BB && "Node has no BB");
for (auto predBB : BB->predcessors()) {
pred = predBB->getLastNode();
assert(pred && "BB has no last node");
const Value *predVal = pred->getKey();
if (isa<StoreInst>(predVal))
changed |= dg::analysis::handleStoreInst(pred, df, strong_update);
else if (isa<CallInst>(predVal))
changed |= dg::analysis::handleCallInst(pred, df);
df->merge(getDefMap(pred), nullptr);
}
}
return changed;
}
} // namespace analysis
} // namespace dg
/// --------------------------------------------------
// Add def-use edges
/// --------------------------------------------------
namespace dg {
namespace analysis {
LLVMNode *LLVMDefUseAnalysis::getOperand(LLVMNode *node,
const Value *val, unsigned int idx)
{
return dg::analysis::getOperand(node, val, idx, DL);
}
static void addIndirectDefUsePtr(const Pointer& ptr, LLVMNode *to, DefMap *df)
{
if (ptr.isNull() || ptr.obj->isUnknown()) {
errs() << "ERR: pointer pointing to unknown location, UNSOUND! "
<< *to->getKey() << "\n";
return;
}
LLVMNode *ptrnode = ptr.obj->node;
const Value *ptrVal = ptrnode->getKey();
// functions does not have indirect reaching definitions
if (isa<Function>(ptrVal))
return;
ValuesSetT& defs = df->get(ptr);
// do we have any reaching definition at all?
if (defs.empty()) {
// we do not add initial def to global variables because not all
// global variables could be used in the code and we'd redundantly
// iterate through the defintions. Do it lazily here.
if (isa<GlobalVariable>(ptrVal)) {
// ok, so the GV was defined in initialization phase,
// so the reaching definition for the ptr is there.
// If it was not defined, then we still want the edge
// from the global node in this case
defs.insert(ptrnode);
} else if (isa<AllocaInst>(ptrVal)) {
// AllocaInst without any reaching definition
// may mean that the value is undefined. Nevertheless
// we use the value that is defined via the AllocaInst,
// so add definition on the AllocaInst
// This is the same as with global variables
defs.insert(ptrnode);
} else if (isa<ConstantPointerNull>(ptrVal)) {
// just do nothing, it has no reaching definition
return;
} else {
errs() << "WARN: no reaching definition for "
<< *ptr.obj->node->getKey()
<< " + " << *ptr.offset << "\n";
return;
}
}
assert(!defs.empty());
for (LLVMNode *n : defs)
n->addDataDependence(to);
// if we got pointer to our object with UNKNOWN_OFFSET,
// it still can be reaching definition, so we must take it into
// account
ValuesSetT& defsUnknown = df->get(Pointer(ptr.obj, UNKNOWN_OFFSET));
if (!defsUnknown.empty()) {
for (LLVMNode *n : defsUnknown)
n->addDataDependence(to);
}
}
static void addIndirectDefUse(LLVMNode *ptrNode, LLVMNode *to, DefMap *df)
{
// iterate over all memory locations that this
// store can define and check where they are defined
for (const Pointer& ptr : ptrNode->getPointsTo())
addIndirectDefUsePtr(ptr, to, df);
}
// return Value used on operand LLVMNode
// It is either the operand itself or
// global value used in ConstantExpr if the
// operand is ConstantExpr
static void addStoreLoadInstDefUse(LLVMNode *storeNode, LLVMNode *op, DefMap *df)
{
const Value *val = op->getKey();
if (isa<ConstantExpr>(val)) {
// it should be one ptr
PointsToSetT& PS = op->getPointsTo();
assert(PS.size() == 1);
const Pointer& ptr = *PS.begin();
addIndirectDefUsePtr(ptr, storeNode, df);
} else {
op->addDataDependence(storeNode);
}
}
void LLVMDefUseAnalysis::handleStoreInst(const StoreInst *Inst, LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode *valNode = node->getOperand(1);
// this node uses what is defined on valNode
if (valNode) {
addStoreLoadInstDefUse(node, valNode, df);
}
#ifdef DEBUG_ENABLED
else {
if (!isa<ConstantInt>(Inst->getValueOperand()))
errs() << "ERR def-use: Unhandled value operand for "
<< *Inst << "\n";
}
#endif
LLVMNode *ptrNode = node->getOperand(0);
assert(ptrNode);
// and also uses what is defined on ptrNode
addStoreLoadInstDefUse(node, ptrNode, df);
}
void LLVMDefUseAnalysis::handleLoadInst(LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode *ptrNode = node->getOperand(0);
assert(ptrNode && "No ptr node");
// load inst is reading from the memory,
// so add indirect def-use edges
addIndirectDefUse(ptrNode, node, df);
// load inst is reading from the memory that is pointed by
// the top-level value, so add def-use edge
addStoreLoadInstDefUse(node, ptrNode, df);
}
static void addOutParamsEdges(LLVMDependenceGraph *graph)
{
LLVMDGParameters *params = graph->getParameters();
assert(params && "No formal params in subgraph with actual params");
LLVMNode *exitNode = graph->getExit();
assert(exitNode && "No exit node in subgraph");
DefMap *df = getDefMap(exitNode);
for (auto it : *params) {
const Value *val = it.first;
if (!val->getType()->isPointerTy())
continue;
LLVMDGParameter& p = it.second;
// points to set is contained in the input param
for (const Pointer& ptr : p.in->getPointsTo()) {
ValuesSetT& defs = df->get(ptr);
if (defs.empty())
continue;
// ok, the memory location is defined in this subgraph,
// so add data dependence edge to the out param
for (LLVMNode *def : defs)
def->addDataDependence(p.out);
}
}
}
static void addOutParamsEdges(LLVMNode *callNode)
{
for (LLVMDependenceGraph *subgraph : callNode->getSubgraphs()) {
addOutParamsEdges(subgraph);
// FIXME we're loosing some accuracy here and
// this edges causes that we'll go into subprocedure
// even with summary edges
if (!callNode->isVoidTy())
subgraph->getExit()->addDataDependence(callNode);
}
}
static void handleCallInst(LLVMNode *node)
{
DefMap *df = getDefMap(node);
LLVMNode **operands = node->getOperands();
LLVMDGParameters *params = node->getParameters();
// if we have a node for the called function,
// it is call via function pointer, so add the
// data dependence edge to corresponding node
if (operands[0]) {
operands[0]->addDataDependence(node);
}
if (!params) // function has no arguments
return;
// parameters begin from 1
for (int i = 1, e = node->getOperandsNum(); i < e; ++i) {
LLVMNode *op = operands[i];
if (!op)
continue;
// find actual parameter
LLVMDGParameter *p = params->find(op->getKey());
if (!p) {
errs() << "ERR: no actual parameter for " << *op->getKey() << "\n";
continue;
}
if (op->isPointerTy()) {
// add data dependencies to in parameters
addIndirectDefUse(op, p->in, df);
// FIXME
// look for reaching definitions inside the procedure
// because since this is a pointer, we can change things
} else
op->addDataDependence(p->in);
}
addOutParamsEdges(node);
}
static void handleInstruction(const Instruction *Inst, LLVMNode *node)
{
LLVMDependenceGraph *dg = node->getDG();
for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) {
LLVMNode *op = dg->getNode(*I);
if (op)
op->addDataDependence(node);
/*
#ifdef DEBUG_ENABLED
else if (!isa<ConstantInt>(*I) && !isa<BranchInst>(Inst))
errs() << "WARN: no node for operand " << **I
<< "in " << *Inst << "\n";
#endif
*/
}
}
void LLVMDefUseAnalysis::handleNode(LLVMNode *node)
{
const Value *val = node->getKey();
if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) {
handleStoreInst(Inst, node);
} else if (isa<LoadInst>(val)) {
handleLoadInst(node);
} else if (isa<CallInst>(val)) {
handleCallInst(node);
} else if (const Instruction *Inst = dyn_cast<Instruction>(val)) {
handleInstruction(Inst, node); // handle rest of Insts
}
}
void handleBlock(LLVMBBlock *BB, LLVMDefUseAnalysis *analysis)
{
LLVMNode *n = BB->getFirstNode();
while (n) {
analysis->handleNode(n);
n = n->getSuccessor();
}
}
void LLVMDefUseAnalysis::addDefUseEdges()
{
// it doesn't matter how we'll go through the nodes
BBlockDFS<LLVMNode> runner(DFS_INTERPROCEDURAL);
runner.run(dg->getEntryBB(), handleBlock, this);
}
} // namespace analysis
} // namespace dg
<|endoftext|> |
<commit_before>using namespace std;
#include "ui.h"
int WIDTH = 600; // width of the user window
int HEIGHT = 480; // height of the user window
char programName[] = "scheduler";
// button info
vector<Button> buttons;
vector<TextBox> textboxes;
vector<Label> labels;
void drawWindow() {
// clear the buffer
glClear(GL_COLOR_BUFFER_BIT);
// Add hover colors after Monday
// if ( buttonIsPressed ) glColor3f(1., 0., 0.); // make it red
// else if ( overButton ) glColor3f(.75,.75,.75); // light gray
// else glColor3f(.5, .5, .5); // gray
// drawBox(buttonPos);
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i)
i->draw();
// draw the textbox
// glColor3f(.25, .25, .25); // dark gray
// drawBox(textBox1);
// if ( overTextBox ) glColor3f(1,1,1); // white
// else glColor3f(.75, .75, .75); // light gray
// drawBox(textBox2);
// glColor3f(0, 0, 0); // black
// if (overTextBox) { // draw with a cursor
// string withCursor(textInBox);
// withCursor += '|';
// drawText( textBox2[0]+5, textBox2[1]+textBox2[3]-10, withCursor.c_str() );
// } else drawText( textBox2[0]+5, textBox2[1]+textBox2[3]-10, textInBox.c_str() );
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
i->draw();
}
for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) {
i->draw();
}
// tell the graphics card that we're done-- go ahead and draw!
// (technically, we are switching between two color buffers...)
glutSwapBuffers();
}
// close the window and finish the program
void exitAll() {
int win = glutGetWindow();
glutDestroyWindow(win);
exit(0);
}
// process keyboard events
void keyboard( unsigned char c, int x, int y ) {
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if ( i->hover() ) { // intercept keyboard press, to place in text box
if ( 27==c ) exitAll(); // escape terminates the program, even in textbox
if ( 13==c ) {
cout << "textBox content was: " << i->textInBox << endl;
i->textInBox = "";
} else if ( '\b'==c || 127==c ) { // handle backspace
if ( i->textInBox.length() > 0 ) i->textInBox.erase(i->textInBox.end()-1);
} else if ( c >= 32 && c <= 126 ) { // check for printable character
// check that we don't overflow the box
if ( i->textInBox.length() < MAX_NUM_CHARS_IN_TEXTBOX ) i->textInBox += c;
}
} else {
switch(c) {
case 'q':
case 'Q':
case 27:
exitAll();
break;
default:
break;
}
}
glutPostRedisplay();
}
}
// the reshape function handles the case where the user changes the size
// of the window. We need to fix the coordinate
// system, so that the drawing area is still the unit square.
void reshape(int w, int h) {
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
WIDTH = w; HEIGHT = h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0);
}
// the mouse function is called when a mouse button is pressed down or released
void mouse(int mouseButton, int state, int x, int y) {
if ( GLUT_LEFT_BUTTON == mouseButton ) {
if ( GLUT_DOWN == state ) {
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) {
if (i->hover())
i->active = true;
else i->active = false;
}
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if (i->hover())
i->active = true;
else i->active = false;
}
} else {
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) {
if (i->hover() && i->active)
cout << "Button press." << endl;
i->active = false;
}
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if (i->hover() && i->active)
cout << "Button press." << endl;
i->active = false;
}
// for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) {
// if (i->hover() && i->active)
// cout << "Label press." << endl;
// i->active = false;
// } // todo: click on label to focus associated textbox
}
} else if ( GLUT_RIGHT_BUTTON == mouseButton ) {}
glutPostRedisplay();
}
// the init function sets up the graphics card to draw properly
void init(void) {
// clear the window to black
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// set up the coordinate system: number of pixels along x and y
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0);
// welcome message
cout << "Welcome to " << programName << endl;
}
// initGlWindow is the function that starts the ball rolling, in
// terms of getting everything set up and passing control over to the
// glut library for event handling. It needs to tell the glut library
// about all the essential functions: what function to call if the
// window changes shape, what to do to redraw, handle the keyboard,
// etc.
void initGlWindow() {
char *argv[] = { programName };
int argc = sizeof(argv) / sizeof(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize(WIDTH,HEIGHT);
glutInitWindowPosition(100,100);
glutCreateWindow(programName);
init();
glutDisplayFunc(drawWindow);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
// glutMotionFunc(mouse_motion);
// glutPassiveMotionFunc(mouse_motion);
glutMainLoop();
}
int main() {
initGlWindow();
}
<commit_msg>Pass x and y to hover functions<commit_after>using namespace std;
#include "ui.h"
int WIDTH = 600; // width of the user window
int HEIGHT = 480; // height of the user window
char programName[] = "scheduler";
// button info
vector<Button> buttons;
vector<TextBox> textboxes;
vector<Label> labels;
void drawWindow() {
// clear the buffer
glClear(GL_COLOR_BUFFER_BIT);
// Add hover colors after Monday
// if ( buttonIsPressed ) glColor3f(1., 0., 0.); // make it red
// else if ( overButton ) glColor3f(.75,.75,.75); // light gray
// else glColor3f(.5, .5, .5); // gray
// drawBox(buttonPos);
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i)
i->draw();
// draw the textbox
// glColor3f(.25, .25, .25); // dark gray
// drawBox(textBox1);
// if ( overTextBox ) glColor3f(1,1,1); // white
// else glColor3f(.75, .75, .75); // light gray
// drawBox(textBox2);
// glColor3f(0, 0, 0); // black
// if (overTextBox) { // draw with a cursor
// string withCursor(textInBox);
// withCursor += '|';
// drawText( textBox2[0]+5, textBox2[1]+textBox2[3]-10, withCursor.c_str() );
// } else drawText( textBox2[0]+5, textBox2[1]+textBox2[3]-10, textInBox.c_str() );
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
i->draw();
}
for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) {
i->draw();
}
// tell the graphics card that we're done-- go ahead and draw!
// (technically, we are switching between two color buffers...)
glutSwapBuffers();
}
// close the window and finish the program
void exitAll() {
int win = glutGetWindow();
glutDestroyWindow(win);
exit(0);
}
// process keyboard events
void keyboard( unsigned char c, int x, int y ) {
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if ( i->hover(x, y) ) { // intercept keyboard press, to place in text box
if ( 27==c ) exitAll(); // escape terminates the program, even in textbox
if ( 13==c ) {
cout << "textBox content was: " << i->textInBox << endl;
i->textInBox = "";
} else if ( '\b'==c || 127==c ) { // handle backspace
if ( i->textInBox.length() > 0 ) i->textInBox.erase(i->textInBox.end()-1);
} else if ( c >= 32 && c <= 126 ) { // check for printable character
// check that we don't overflow the box
if ( i->textInBox.length() < MAX_NUM_CHARS_IN_TEXTBOX ) i->textInBox += c;
}
} else {
switch(c) {
case 'q':
case 'Q':
case 27:
exitAll();
break;
default:
break;
}
}
glutPostRedisplay();
}
}
// the reshape function handles the case where the user changes the size
// of the window. We need to fix the coordinate
// system, so that the drawing area is still the unit square.
void reshape(int w, int h) {
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
WIDTH = w; HEIGHT = h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0);
}
// the mouse function is called when a mouse button is pressed down or released
void mouse(int mouseButton, int state, int x, int y) {
if ( GLUT_LEFT_BUTTON == mouseButton ) {
if ( GLUT_DOWN == state ) {
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) {
if (i->hover(x, y))
i->active = true;
else i->active = false;
}
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if (i->hover(x, y))
i->active = true;
else i->active = false;
}
} else {
for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) {
if (i->hover(x, y) && i->active)
cout << "Button press." << endl;
i->active = false;
}
for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) {
if (i->hover(x, y) && i->active)
cout << "Button press." << endl;
i->active = false;
}
// for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) {
// if (i->hover(x, y) && i->active)
// cout << "Label press." << endl;
// i->active = false;
// } // todo: click on label to focus associated textbox
}
} else if ( GLUT_RIGHT_BUTTON == mouseButton ) {}
glutPostRedisplay();
}
// the init function sets up the graphics card to draw properly
void init(void) {
// clear the window to black
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// set up the coordinate system: number of pixels along x and y
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0);
// welcome message
cout << "Welcome to " << programName << endl;
}
// initGlWindow is the function that starts the ball rolling, in
// terms of getting everything set up and passing control over to the
// glut library for event handling. It needs to tell the glut library
// about all the essential functions: what function to call if the
// window changes shape, what to do to redraw, handle the keyboard,
// etc.
void initGlWindow() {
char *argv[] = { programName };
int argc = sizeof(argv) / sizeof(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize(WIDTH,HEIGHT);
glutInitWindowPosition(100,100);
glutCreateWindow(programName);
init();
glutDisplayFunc(drawWindow);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
// glutMotionFunc(mouse_motion);
// glutPassiveMotionFunc(mouse_motion);
glutMainLoop();
}
int main() {
initGlWindow();
}
<|endoftext|> |
<commit_before>
#include "ExecutionEngine.h"
#include <csetjmp>
#include <chrono>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#include <libevm/VM.h>
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
ExecutionEngine::ExecutionEngine()
{
}
int ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, u256& _gas, ExtVMFace* _ext)
{
auto module = _module.get(); // Keep ownership of the module in _module
llvm::sys::PrintStackTraceOnErrorSignal();
static const auto program = "evmcc";
llvm::PrettyStackTraceProgram X(1, &program);
auto&& context = llvm::getGlobalContext();
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string errorMsg;
llvm::EngineBuilder builder(module);
//builder.setMArch(MArch);
//builder.setMCPU(MCPU);
//builder.setMAttrs(MAttrs);
//builder.setRelocationModel(RelocModel);
//builder.setCodeModel(CMModel);
builder.setErrorStr(&errorMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
builder.setMCJITMemoryManager(new llvm::SectionMemoryManager());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
module->setTargetTriple(triple.str());
auto exec = std::unique_ptr<llvm::ExecutionEngine>(builder.create());
if (!exec)
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment(errorMsg));
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
auto finalizationStartTime = std::chrono::high_resolution_clock::now();
exec->finalizeObject();
auto finalizationEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << "Module finalization time: "
<< std::chrono::duration_cast<std::chrono::microseconds>(finalizationEndTime - finalizationStartTime).count();
// Create fake ExtVM interface
if (!_ext)
{
_ext = new ExtVMFace;
_ext->myAddress = Address(1122334455667788);
_ext->caller = Address(0xfacefacefaceface);
_ext->origin = Address(101010101010101010);
_ext->value = 0xabcd;
_ext->gasPrice = 1002;
_ext->previousBlock.hash = u256(1003);
_ext->currentBlock.coinbaseAddress = Address(1004);
_ext->currentBlock.timestamp = 1005;
_ext->currentBlock.number = 1006;
_ext->currentBlock.difficulty = 1007;
_ext->currentBlock.gasLimit = 1008;
std::string calldata = "Hello the Beautiful World of Ethereum!";
_ext->data = calldata;
unsigned char fakecode[] = {0x0d, 0x0e, 0x0a, 0x0d, 0x0b, 0x0e, 0xe, 0xf};
_ext->code = decltype(_ext->code)(fakecode, 8);
}
auto entryFunc = module->getFunction("main");
if (!entryFunc)
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("main function not found"));
ReturnCode returnCode;
std::jmp_buf buf;
Runtime runtime(_gas, *_ext, buf);
auto r = setjmp(buf);
if (r == 0)
{
auto executionStartTime = std::chrono::high_resolution_clock::now();
auto result = exec->runFunction(entryFunc, {{}, llvm::GenericValue(runtime.getDataPtr())});
returnCode = static_cast<ReturnCode>(result.IntVal.getZExtValue());
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << "Execution time : "
<< std::chrono::duration_cast<std::chrono::microseconds>(executionEndTime - executionStartTime).count();
}
else
returnCode = static_cast<ReturnCode>(r);
// Return remaining gas
_gas = returnCode == ReturnCode::OutOfGas ? 0 : runtime.getGas();
clog(JIT) << "Max stack size: " << Stack::maxStackSize;
if (returnCode == ReturnCode::Return)
{
returnData = runtime.getReturnData().toVector(); // TODO: It might be better to place is in Runtime interface
auto&& log = clog(JIT);
log << "RETURN [ ";
for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)
log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " ";
log << "]";
}
else
cslog(JIT) << "RETURN " << (int)returnCode;
return static_cast<int>(returnCode);
}
}
}
}
<commit_msg>Improve ExecutionEngine code formatting<commit_after>
#include "ExecutionEngine.h"
#include <csetjmp>
#include <chrono>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#include <libevm/VM.h>
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
ExecutionEngine::ExecutionEngine()
{
}
int ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, u256& _gas, ExtVMFace* _ext)
{
auto module = _module.get(); // Keep ownership of the module in _module
llvm::sys::PrintStackTraceOnErrorSignal();
static const auto program = "evmcc";
llvm::PrettyStackTraceProgram X(1, &program);
auto&& context = llvm::getGlobalContext();
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string errorMsg;
llvm::EngineBuilder builder(module);
//builder.setMArch(MArch);
//builder.setMCPU(MCPU);
//builder.setMAttrs(MAttrs);
//builder.setRelocationModel(RelocModel);
//builder.setCodeModel(CMModel);
builder.setErrorStr(&errorMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
builder.setMCJITMemoryManager(new llvm::SectionMemoryManager());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
module->setTargetTriple(triple.str());
auto exec = std::unique_ptr<llvm::ExecutionEngine>(builder.create());
if (!exec)
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment(errorMsg));
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
auto finalizationStartTime = std::chrono::high_resolution_clock::now();
exec->finalizeObject();
auto finalizationEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << "Module finalization time: "
<< std::chrono::duration_cast<std::chrono::microseconds>(finalizationEndTime - finalizationStartTime).count();
// Create fake ExtVM interface
if (!_ext)
{
_ext = new ExtVMFace;
_ext->myAddress = Address(1122334455667788);
_ext->caller = Address(0xfacefacefaceface);
_ext->origin = Address(101010101010101010);
_ext->value = 0xabcd;
_ext->gasPrice = 1002;
_ext->previousBlock.hash = u256(1003);
_ext->currentBlock.coinbaseAddress = Address(1004);
_ext->currentBlock.timestamp = 1005;
_ext->currentBlock.number = 1006;
_ext->currentBlock.difficulty = 1007;
_ext->currentBlock.gasLimit = 1008;
std::string calldata = "Hello the Beautiful World of Ethereum!";
_ext->data = calldata;
unsigned char fakecode[] = {0x0d, 0x0e, 0x0a, 0x0d, 0x0b, 0x0e, 0xe, 0xf};
_ext->code = decltype(_ext->code)(fakecode, 8);
}
auto entryFunc = module->getFunction("main");
if (!entryFunc)
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("main function not found"));
ReturnCode returnCode;
std::jmp_buf buf;
Runtime runtime(_gas, *_ext, buf);
auto r = setjmp(buf);
if (r == 0)
{
auto executionStartTime = std::chrono::high_resolution_clock::now();
auto result = exec->runFunction(entryFunc, {{}, llvm::GenericValue(runtime.getDataPtr())});
returnCode = static_cast<ReturnCode>(result.IntVal.getZExtValue());
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << "Execution time : "
<< std::chrono::duration_cast<std::chrono::microseconds>(executionEndTime - executionStartTime).count();
}
else
returnCode = static_cast<ReturnCode>(r);
// Return remaining gas
_gas = returnCode == ReturnCode::OutOfGas ? 0 : runtime.getGas();
clog(JIT) << "Max stack size: " << Stack::maxStackSize;
if (returnCode == ReturnCode::Return)
{
returnData = runtime.getReturnData().toVector(); // TODO: It might be better to place is in Runtime interface
auto&& log = clog(JIT);
log << "RETURN [ ";
for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)
log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " ";
log << "]";
}
else
cslog(JIT) << "RETURN " << (int)returnCode;
return static_cast<int>(returnCode);
}
}
}
}
<|endoftext|> |
<commit_before>/* created by fbellini@cern.ch on 14/09/2010 */
/* last modified by fbellini on 08/03/2010 */
#include "AliAnalysisTaskTOFqa.h"
AliAnalysisTaskSE * AddTaskTOFQA()
{
// Task for checking TOF QA
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTask", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTask", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Configure analysis
//===========================================================================
// Create the task
AliAnalysisTaskTOFqa *task = new AliAnalysisTaskTOFqa("taskTOFqa");
//AliLog::SetClassDebugLevel("AliAnalysisTaskTOFqa",1);
mgr->AddTask(task);
//--------------- set the filtering ------------
// Barrel Tracks
/* cuts used for QA in 2010 p-p */
AliESDtrackCuts* esdTrackCutsLoose2010 = new AliESDtrackCuts("AliESDtrackCuts", "esdTrackCutsLoose2010");
esdTrackCutsL->SetMinNClustersTPC(70);
esdTrackCutsL->SetMaxChi2PerClusterTPC(3.5);
esdTrackCutsL->SetMaxCovDiagonalElements(2, 2, 0.5, 0.5, 2);
esdTrackCutsL->SetRequireTPCRefit(kTRUE);
esdTrackCutsL->SetMaxDCAToVertexXY(3.0);
esdTrackCutsL->SetMaxDCAToVertexZ(3.0);
esdTrackCutsL->SetRequireSigmaToVertex(kTRUE);
esdTrackCutsL->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsL->SetMaxNsigmaToVertex(4.0);
/* standard cuts ITS-TPC 2010 */
AliESDtrackCuts* esdTrackCutsStd2010 = new AliESDtrackCuts("AliESDtrackCuts", "Standard2010");
// TPC
esdTrackCutsStd2010->SetMinNClustersTPC(70);
esdTrackCutsStd2010->SetMaxChi2PerClusterTPC(4);
esdTrackCutsStd2010->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsStd2010->SetRequireTPCRefit(kTRUE);
// ITS
esdTrackCuts->SetRequireITSRefit(kTRUE);
esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kAny);
esdTrackCuts->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01");//selects primaries
esdTrackCutsStd2010->SetMaxDCAToVertexZ(2);
esdTrackCutsStd2010->SetDCAToVertex2D(kFALSE);
esdTrackCutsStd2010->SetRequireSigmaToVertex(kFALSE);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsStd2010);
task->SetTrackFilter(trackFilter);
// Create containers for input/output
AliAnalysisDataContainer *cInputTOFqa = mgr->CreateContainer("cInputTOFqa",TChain::Class(),AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *cGeneralTOFqa = mgr->CreateContainer("cGeneralTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
AliAnalysisDataContainer *cTimeZeroTOFqa = mgr->CreateContainer("cTimeZeroTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
AliAnalysisDataContainer *cPIDTOFqa = mgr->CreateContainer("cPIDTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
// Attach i/o
mgr->ConnectInput(task, 0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, cGeneralTOFqa);
mgr->ConnectOutput(task, 2, cTimeZeroTOFqa);
mgr->ConnectOutput(task, 3, cPIDTOFqa);
return task;
}
<commit_msg>Fixed macro from Francesca<commit_after>/* created by fbellini@cern.ch on 14/09/2010 */
/* last modified by fbellini on 08/03/2010 */
#include "AliAnalysisTaskTOFqa.h"
AliAnalysisTaskSE * AddTaskTOFQA()
{
// Task for checking TOF QA
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTask", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTask", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Configure analysis
//===========================================================================
// Create the task
AliAnalysisTaskTOFqa *task = new AliAnalysisTaskTOFqa("taskTOFqa");
//AliLog::SetClassDebugLevel("AliAnalysisTaskTOFqa",1);
mgr->AddTask(task);
//--------------- set the filtering ------------
// Barrel Tracks
/* cuts used for QA in 2010 p-p */
AliESDtrackCuts* esdTrackCutsLoose2010 = new AliESDtrackCuts("AliESDtrackCuts", "esdTrackCutsLoose2010");
esdTrackCutsLoose2010->SetMinNClustersTPC(70);
esdTrackCutsLoose2010->SetMaxChi2PerClusterTPC(3.5);
esdTrackCutsLoose2010->SetMaxCovDiagonalElements(2, 2, 0.5, 0.5, 2);
esdTrackCutsLoose2010->SetRequireTPCRefit(kTRUE);
esdTrackCutsLoose2010->SetMaxDCAToVertexXY(3.0);
esdTrackCutsLoose2010->SetMaxDCAToVertexZ(3.0);
esdTrackCutsLoose2010->SetRequireSigmaToVertex(kTRUE);
esdTrackCutsLoose2010->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsLoose2010->SetMaxNsigmaToVertex(4.0);
/* standard cuts ITS-TPC 2010 */
AliESDtrackCuts* esdTrackCutsStd2010 = new AliESDtrackCuts("AliESDtrackCuts", "Standard2010");
// TPC
esdTrackCutsStd2010->SetMinNClustersTPC(70);
esdTrackCutsStd2010->SetMaxChi2PerClusterTPC(4);
esdTrackCutsStd2010->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsStd2010->SetRequireTPCRefit(kTRUE);
// ITS
esdTrackCutsStd2010->SetRequireITSRefit(kTRUE);
esdTrackCutsStd2010->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kAny);
esdTrackCutsStd2010->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01");//selects primaries
esdTrackCutsStd2010->SetMaxDCAToVertexZ(2);
esdTrackCutsStd2010->SetDCAToVertex2D(kFALSE);
esdTrackCutsStd2010->SetRequireSigmaToVertex(kFALSE);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsStd2010);
task->SetTrackFilter(trackFilter);
// Create containers for input/output
AliAnalysisDataContainer *cInputTOFqa = mgr->CreateContainer("cInputTOFqa",TChain::Class(),AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *cGeneralTOFqa = mgr->CreateContainer("cGeneralTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
AliAnalysisDataContainer *cTimeZeroTOFqa = mgr->CreateContainer("cTimeZeroTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
AliAnalysisDataContainer *cPIDTOFqa = mgr->CreateContainer("cPIDTOFqa",TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:TOF_Performance",mgr->GetCommonFileName()));
// Attach i/o
mgr->ConnectInput(task, 0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, cGeneralTOFqa);
mgr->ConnectOutput(task, 2, cTimeZeroTOFqa);
mgr->ConnectOutput(task, 3, cPIDTOFqa);
return task;
}
<|endoftext|> |
<commit_before>#include "pin_mesh_base.hpp"
#include <iostream>
#include "error.hpp"
namespace mocc {
PinMesh::PinMesh( const pugi::xml_node &input ) {
// Extract pin id
id_ = input.attribute( "id" ).as_int(-1);
if(id_ < 0) {
throw EXCEPT( "Failed to read pin ID." );
}
// Extract pitch
pitch_x_ = input.attribute( "pitch" ).as_float(-1.0);
// Just treat square pitch for now
pitch_y_ = pitch_x_;
if( pitch_x_ <= 0.0 ) {
throw EXCEPT( "Failed to read valid pin pitch." );
}
return;
}
void PinMesh::print( std::ostream &os ) const {
os << "ID: " << id_ << std::endl;
os << "X Pitch: " << pitch_x_ << std::endl;
os << "Y Pitch: " << pitch_y_ << std::endl;
os << "# of Regions: " << n_reg_ << std::endl;
os << "# of XS Regions: " << n_xsreg_;
return;
}
}
<commit_msg>Parse pin pitch as double...<commit_after>#include "pin_mesh_base.hpp"
#include <iostream>
#include "error.hpp"
namespace mocc {
PinMesh::PinMesh( const pugi::xml_node &input ) {
// Extract pin id
id_ = input.attribute( "id" ).as_int(-1);
if(id_ < 0) {
throw EXCEPT( "Failed to read pin ID." );
}
// Extract pitch
pitch_x_ = input.attribute( "pitch" ).as_double(-1.0);
// Just treat square pitch for now
pitch_y_ = pitch_x_;
if( pitch_x_ <= 0.0 ) {
throw EXCEPT( "Failed to read valid pin pitch." );
}
return;
}
void PinMesh::print( std::ostream &os ) const {
os << "ID: " << id_ << std::endl;
os << "X Pitch: " << pitch_x_ << std::endl;
os << "Y Pitch: " << pitch_y_ << std::endl;
os << "# of Regions: " << n_reg_ << std::endl;
os << "# of XS Regions: " << n_xsreg_;
return;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <votca/xtp/aomatrix.h>
#include <votca/xtp/logger.h>
#include <votca/xtp/multiarray.h>
#include <votca/xtp/threecenter.h>
using std::flush;
namespace votca {
namespace xtp {
void TCMatrix_gwbse::Initialize(int basissize, int mmin, int mmax, int nmin,
int nmax) {
// here as storage indices starting from zero
_nmin = nmin;
_nmax = nmax;
_ntotal = nmax - nmin + 1;
_mmin = mmin;
_mmax = mmax;
_mtotal = mmax - mmin + 1;
_basissize = basissize;
// vector has mtotal elements
_matrix = std::vector<Eigen::MatrixXd>(
_mtotal, Eigen::MatrixXd::Zero(_ntotal, _basissize));
}
/*
* Modify 3-center matrix elements consistent with use of symmetrized
* Coulomb interaction using either CUDA or Openmp
*/
void TCMatrix_gwbse::MultiplyRightWithAuxMatrix(const Eigen::MatrixXd& matrix) {
// Try to run the operation in a Nvidia GPU, otherwise is the default Openmp
// implementation
#if defined(USE_CUDA)
EigenCuda cuda_handle;
try {
_matrix = cuda_handle.right_matrix_tensor_mult(_matrix, matrix);
} catch (const std::runtime_error& error) {
XTP_LOG_SAVE(logDEBUG, _log)
<< TimeStamp()
<< " CUDA Multiplyrightwithauxmatrix failed due to: " << error.what()
<< " Using default OpenMP implementation!" << flush;
this->MultiplyRightWithAuxMatrixOpenMP(matrix);
}
#else
XTP_LOG_SAVE(logDEBUG, _log)
<< TimeStamp() << "Call MultiplyRightWithAuxMatrixOpenMP method" << flush;
this->MultiplyRightWithAuxMatrixOpenMP(matrix);
#endif
return;
}
/*
* Fill the 3-center object by looping over shells of GW basis set and
* calling FillBlock, which calculates all 3-center overlap integrals
* associated to a particular shell, convoluted with the DFT orbital
* coefficients
*/
void TCMatrix_gwbse::Fill(const AOBasis& gwbasis, const AOBasis& dftbasis,
const Eigen::MatrixXd& dft_orbitals) {
// needed for Rebuild())
_auxbasis = &gwbasis;
_dftbasis = &dftbasis;
_dft_orbitals = &dft_orbitals;
#if defined(USE_CUDA)
auto cuda_matrices = SendDFTMatricesToGPU(dft_orbitals);
#endif
// loop over all shells in the GW basis and get _Mmn for that shell
#pragma omp parallel for schedule(guided) // private(_block)
for (int is = 0; is < gwbasis.getNumofShells(); is++) {
const AOShell& shell = gwbasis.getShell(is);
std::vector<Eigen::MatrixXd> block;
for (int i = 0; i < _mtotal; i++) {
block.push_back(Eigen::MatrixXd::Zero(_ntotal, shell.getNumFunc()));
}
// Fill block for this shell (3-center overlap with _dft_basis +
// multiplication with _dft_orbitals )
std::vector<Eigen::MatrixXd> symmstorage =
ComputeSymmStorage(shell, dftbasis, dft_orbitals);
#if defined(USE_CUDA)
FillBlockCUDA(block, symmstorage, cuda_matrices);
#else
FillBlock(block, symmstorage, dft_orbitals);
#endif
// put into correct position
for (int m_level = 0; m_level < _mtotal; m_level++) {
_matrix[m_level].block(0, shell.getStartIndex(), _ntotal,
shell.getNumFunc()) = block[m_level];
} // m-th DFT orbital
} // shells of GW basis set
AOOverlap auxoverlap;
auxoverlap.Fill(gwbasis);
AOCoulomb auxcoulomb;
auxcoulomb.Fill(gwbasis);
Eigen::MatrixXd inv_sqrt = auxcoulomb.Pseudo_InvSqrt_GWBSE(auxoverlap, 5e-7);
_removedfunctions = auxcoulomb.Removedfunctions();
MultiplyRightWithAuxMatrix(inv_sqrt);
return;
}
/*
* Determines the 3-center integrals for a given shell in the GW basis
* by calculating the 3-center overlap integral of the functions in the
* GW shell with ALL functions in the DFT basis set (FillThreeCenterOLBlock)
*/
std::vector<Eigen::MatrixXd> TCMatrix_gwbse::ComputeSymmStorage(
const AOShell& auxshell, const AOBasis& dftbasis,
const Eigen::MatrixXd& dft_orbitals) const {
tensor3d::extent_gen extents;
std::vector<Eigen::MatrixXd> symmstorage;
for (int i = 0; i < auxshell.getNumFunc(); ++i) {
symmstorage.push_back(
Eigen::MatrixXd::Zero(dftbasis.AOBasisSize(), dftbasis.AOBasisSize()));
}
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
// alpha-loop over the "left" DFT basis function
for (int row = 0; row < dftbasis.getNumofShells(); row++) {
const AOShell& shell_row = dftbasis.getShell(row);
const int row_start = shell_row.getStartIndex();
// ThreecMatrix is symmetric, restrict explicit calculation to triangular
// matrix
for (int col = 0; col <= row; col++) {
const AOShell& shell_col = dftbasis.getShell(col);
const int col_start = shell_col.getStartIndex();
tensor3d threec_block(extents[range(0, auxshell.getNumFunc())][range(
0, shell_row.getNumFunc())][range(0, shell_col.getNumFunc())]);
std::fill_n(threec_block.data(), threec_block.num_elements(), 0.0);
bool nonzero =
FillThreeCenterRepBlock(threec_block, auxshell, shell_row, shell_col);
if (nonzero) {
for (int aux_c = 0; aux_c < auxshell.getNumFunc(); aux_c++) {
for (int row_c = 0; row_c < shell_row.getNumFunc(); row_c++) {
for (int col_c = 0; col_c < shell_col.getNumFunc(); col_c++) {
// symmetry
if ((col_start + col_c) > (row_start + row_c)) {
break;
}
symmstorage[aux_c](row_start + row_c, col_start + col_c) =
threec_block[aux_c][row_c][col_c];
} // ROW copy
} // COL copy
} // AUX copy
}
} // gamma-loop
} // alpha-loop
return symmstorage;
}
/*
* Convolution of the GW shell with ALL functions with the DFT orbital
* coefficients
*/
void TCMatrix_gwbse::FillBlock(std::vector<Eigen::MatrixXd>& block,
const std::vector<Eigen::MatrixXd>& symmstorage,
const Eigen::MatrixXd& dft_orbitals) {
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
for (auto k = 0; k < symmstorage.size(); ++k) {
const Eigen::MatrixXd& matrix = symmstorage[k];
Eigen::MatrixXd threec_inMo =
dftn.transpose() * matrix.selfadjointView<Eigen::Lower>() * dftm;
for (int i = 0; i < threec_inMo.cols(); ++i) {
block[i].col(k) = threec_inMo.col(i);
}
}
return;
}
/*
* Modify 3-center matrix elements consistent with use of symmetrized
* Coulomb interaction using OPENMP parallelization
*/
void TCMatrix_gwbse::MultiplyRightWithAuxMatrixOpenMP(
const Eigen::MatrixXd& matrix) {
#pragma omp parallel for
for (int i_occ = 0; i_occ < _mtotal; i_occ++) {
Eigen::MatrixXd temp = _matrix[i_occ] * matrix;
_matrix[i_occ] = temp;
}
return;
}
#if defined(USE_CUDA)
/*
* Convolution of the GW shell with ALL functions with the DFT orbital
* coefficients using an Nvidia GPU
*/
void TCMatrix_gwbse::FillBlockCUDA(
std::vector<Eigen::MatrixXd>& block,
const std::vector<Eigen::MatrixXd>& symmstorage,
const std::pair<CudaMatrix, CudaMatrix>& cuda_matrices) {
EigenCuda cuda_handle;
for (auto k = 0; k < symmstorage.size(); ++k) {
const Eigen::MatrixXd& matrix = symmstorage[k];
Eigen::MatrixXd threec_inMo = cuda_handle.triple_matrix_mult(
cuda_matrices.first, matrix.selfadjointView<Eigen::Lower>(),
cuda_matrices.second);
for (int i = 0; i < threec_inMo.cols(); ++i) {
block[i].col(k) = threec_inMo.col(i);
}
}
return;
}
std::pair<CudaMatrix, CudaMatrix> TCMatrix_gwbse::SendDFTMatricesToGPU(
const Eigen::MatrixXd& dft_orbitals) {
EigenCuda cuda_handle;
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
// Pointers to the cuda arrays
uniq_double dev_dftnT = cuda_handle.copy_matrix_to_gpu(dftn.transpose());
uniq_double dev_dftm = cuda_handle.copy_matrix_to_gpu(dftm);
CudaMatrix matrixA{std::move(dev_dftnT), dftn.cols(), dftn.rows()};
CudaMatrix matrixB{std::move(dev_dftm), dftm.rows(), dftm.cols()};
return std::make_pair(std::move(matrixA), std::move(matrixB));
}
#endif
} // namespace xtp
} // namespace votca
<commit_msg>static cast symmstorage to int<commit_after>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <votca/xtp/aomatrix.h>
#include <votca/xtp/logger.h>
#include <votca/xtp/multiarray.h>
#include <votca/xtp/threecenter.h>
using std::flush;
namespace votca {
namespace xtp {
void TCMatrix_gwbse::Initialize(int basissize, int mmin, int mmax, int nmin,
int nmax) {
// here as storage indices starting from zero
_nmin = nmin;
_nmax = nmax;
_ntotal = nmax - nmin + 1;
_mmin = mmin;
_mmax = mmax;
_mtotal = mmax - mmin + 1;
_basissize = basissize;
// vector has mtotal elements
_matrix = std::vector<Eigen::MatrixXd>(
_mtotal, Eigen::MatrixXd::Zero(_ntotal, _basissize));
}
/*
* Modify 3-center matrix elements consistent with use of symmetrized
* Coulomb interaction using either CUDA or Openmp
*/
void TCMatrix_gwbse::MultiplyRightWithAuxMatrix(const Eigen::MatrixXd& matrix) {
// Try to run the operation in a Nvidia GPU, otherwise is the default Openmp
// implementation
#if defined(USE_CUDA)
EigenCuda cuda_handle;
try {
_matrix = cuda_handle.right_matrix_tensor_mult(_matrix, matrix);
} catch (const std::runtime_error& error) {
XTP_LOG_SAVE(logDEBUG, _log)
<< TimeStamp()
<< " CUDA Multiplyrightwithauxmatrix failed due to: " << error.what()
<< " Using default OpenMP implementation!" << flush;
this->MultiplyRightWithAuxMatrixOpenMP(matrix);
}
#else
XTP_LOG_SAVE(logDEBUG, _log)
<< TimeStamp() << "Call MultiplyRightWithAuxMatrixOpenMP method" << flush;
this->MultiplyRightWithAuxMatrixOpenMP(matrix);
#endif
return;
}
/*
* Fill the 3-center object by looping over shells of GW basis set and
* calling FillBlock, which calculates all 3-center overlap integrals
* associated to a particular shell, convoluted with the DFT orbital
* coefficients
*/
void TCMatrix_gwbse::Fill(const AOBasis& gwbasis, const AOBasis& dftbasis,
const Eigen::MatrixXd& dft_orbitals) {
// needed for Rebuild())
_auxbasis = &gwbasis;
_dftbasis = &dftbasis;
_dft_orbitals = &dft_orbitals;
#if defined(USE_CUDA)
auto cuda_matrices = SendDFTMatricesToGPU(dft_orbitals);
#endif
// loop over all shells in the GW basis and get _Mmn for that shell
#pragma omp parallel for schedule(guided) // private(_block)
for (int is = 0; is < gwbasis.getNumofShells(); is++) {
const AOShell& shell = gwbasis.getShell(is);
std::vector<Eigen::MatrixXd> block;
for (int i = 0; i < _mtotal; i++) {
block.push_back(Eigen::MatrixXd::Zero(_ntotal, shell.getNumFunc()));
}
// Fill block for this shell (3-center overlap with _dft_basis +
// multiplication with _dft_orbitals )
std::vector<Eigen::MatrixXd> symmstorage =
ComputeSymmStorage(shell, dftbasis, dft_orbitals);
#if defined(USE_CUDA)
FillBlockCUDA(block, symmstorage, cuda_matrices);
#else
FillBlock(block, symmstorage, dft_orbitals);
#endif
// put into correct position
for (int m_level = 0; m_level < _mtotal; m_level++) {
_matrix[m_level].block(0, shell.getStartIndex(), _ntotal,
shell.getNumFunc()) = block[m_level];
} // m-th DFT orbital
} // shells of GW basis set
AOOverlap auxoverlap;
auxoverlap.Fill(gwbasis);
AOCoulomb auxcoulomb;
auxcoulomb.Fill(gwbasis);
Eigen::MatrixXd inv_sqrt = auxcoulomb.Pseudo_InvSqrt_GWBSE(auxoverlap, 5e-7);
_removedfunctions = auxcoulomb.Removedfunctions();
MultiplyRightWithAuxMatrix(inv_sqrt);
return;
}
/*
* Determines the 3-center integrals for a given shell in the GW basis
* by calculating the 3-center overlap integral of the functions in the
* GW shell with ALL functions in the DFT basis set (FillThreeCenterOLBlock)
*/
std::vector<Eigen::MatrixXd> TCMatrix_gwbse::ComputeSymmStorage(
const AOShell& auxshell, const AOBasis& dftbasis,
const Eigen::MatrixXd& dft_orbitals) const {
tensor3d::extent_gen extents;
std::vector<Eigen::MatrixXd> symmstorage;
for (int i = 0; i < auxshell.getNumFunc(); ++i) {
symmstorage.push_back(
Eigen::MatrixXd::Zero(dftbasis.AOBasisSize(), dftbasis.AOBasisSize()));
}
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
// alpha-loop over the "left" DFT basis function
for (int row = 0; row < dftbasis.getNumofShells(); row++) {
const AOShell& shell_row = dftbasis.getShell(row);
const int row_start = shell_row.getStartIndex();
// ThreecMatrix is symmetric, restrict explicit calculation to triangular
// matrix
for (int col = 0; col <= row; col++) {
const AOShell& shell_col = dftbasis.getShell(col);
const int col_start = shell_col.getStartIndex();
tensor3d threec_block(extents[range(0, auxshell.getNumFunc())][range(
0, shell_row.getNumFunc())][range(0, shell_col.getNumFunc())]);
std::fill_n(threec_block.data(), threec_block.num_elements(), 0.0);
bool nonzero =
FillThreeCenterRepBlock(threec_block, auxshell, shell_row, shell_col);
if (nonzero) {
for (int aux_c = 0; aux_c < auxshell.getNumFunc(); aux_c++) {
for (int row_c = 0; row_c < shell_row.getNumFunc(); row_c++) {
for (int col_c = 0; col_c < shell_col.getNumFunc(); col_c++) {
// symmetry
if ((col_start + col_c) > (row_start + row_c)) {
break;
}
symmstorage[aux_c](row_start + row_c, col_start + col_c) =
threec_block[aux_c][row_c][col_c];
} // ROW copy
} // COL copy
} // AUX copy
}
} // gamma-loop
} // alpha-loop
return symmstorage;
}
/*
* Convolution of the GW shell with ALL functions with the DFT orbital
* coefficients
*/
void TCMatrix_gwbse::FillBlock(std::vector<Eigen::MatrixXd>& block,
const std::vector<Eigen::MatrixXd>& symmstorage,
const Eigen::MatrixXd& dft_orbitals) {
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
int dim = static_cast<int>(symmstorage.size());
for (auto k = 0; k < dim; ++k) {
const Eigen::MatrixXd& matrix = symmstorage[k];
Eigen::MatrixXd threec_inMo =
dftn.transpose() * matrix.selfadjointView<Eigen::Lower>() * dftm;
for (int i = 0; i < threec_inMo.cols(); ++i) {
block[i].col(k) = threec_inMo.col(i);
}
}
return;
}
/*
* Modify 3-center matrix elements consistent with use of symmetrized
* Coulomb interaction using OPENMP parallelization
*/
void TCMatrix_gwbse::MultiplyRightWithAuxMatrixOpenMP(
const Eigen::MatrixXd& matrix) {
#pragma omp parallel for
for (int i_occ = 0; i_occ < _mtotal; i_occ++) {
Eigen::MatrixXd temp = _matrix[i_occ] * matrix;
_matrix[i_occ] = temp;
}
return;
}
#if defined(USE_CUDA)
/*
* Convolution of the GW shell with ALL functions with the DFT orbital
* coefficients using an Nvidia GPU
*/
void TCMatrix_gwbse::FillBlockCUDA(
std::vector<Eigen::MatrixXd>& block,
const std::vector<Eigen::MatrixXd>& symmstorage,
const std::pair<CudaMatrix, CudaMatrix>& cuda_matrices) {
EigenCuda cuda_handle;
int dim = static_cast<int>(symmstorage.size());
for (int k = 0; k < dim; ++k) {
const Eigen::MatrixXd& matrix = symmstorage[k];
Eigen::MatrixXd threec_inMo = cuda_handle.triple_matrix_mult(
cuda_matrices.first, matrix.selfadjointView<Eigen::Lower>(),
cuda_matrices.second);
for (int i = 0; i < threec_inMo.cols(); ++i) {
block[i].col(k) = threec_inMo.col(i);
}
}
return;
}
std::pair<CudaMatrix, CudaMatrix> TCMatrix_gwbse::SendDFTMatricesToGPU(
const Eigen::MatrixXd& dft_orbitals) {
EigenCuda cuda_handle;
const Eigen::MatrixXd dftm =
dft_orbitals.block(0, _mmin, dft_orbitals.rows(), _mtotal);
const Eigen::MatrixXd dftn =
dft_orbitals.block(0, _nmin, dft_orbitals.rows(), _ntotal);
// Pointers to the cuda arrays
uniq_double dev_dftnT = cuda_handle.copy_matrix_to_gpu(dftn.transpose());
uniq_double dev_dftm = cuda_handle.copy_matrix_to_gpu(dftm);
CudaMatrix matrixA{std::move(dev_dftnT), dftn.cols(), dftn.rows()};
CudaMatrix matrixB{std::move(dev_dftm), dftm.rows(), dftm.cols()};
return std::make_pair(std::move(matrixA), std::move(matrixB));
}
#endif
} // namespace xtp
} // namespace votca
<|endoftext|> |
<commit_before>/**
* @file Walk.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich, Mellmann</a>
* @author <a href="mailto:kaden@informatik.hu-berlin.de">Steffen, Kaden</a>
*
*/
#include "Walk2018.h"
#include "../Walk/FootTrajectoryGenerator.h"
#include "../Walk/ZMPPlanner.h"
#include "Tools/DataStructures/Spline.h"
using namespace naoth;
using namespace InverseKinematic;
Walk2018::Walk2018() : IKMotion(getInverseKinematicsMotionEngineService(), motion::walk, getMotionLock())
{
DEBUG_REQUEST_REGISTER("Walk:draw_step_plan_geometry", "draw all planed steps, zmp and executed com", false);
DEBUG_REQUEST_REGISTER("Walk:plot_genTrajectoryWithSplines", "plot spline interpolation to parametrize 3D foot trajectory", false);
theCoMErrorProvider = registerModule<CoMErrorProvider>("CoMErrorProvider", true);
theFootStepPlanner = registerModule<FootStepPlanner2018>("FootStepPlanner2018", true); // TODO: call init()
theZMPPlanner = registerModule<ZMPPlanner2018>("ZMPPlanner2018", true); // TODO: call init()
theZMPPreviewController = registerModule<ZMPPreviewController>("ZMPPreviewController", true);
theFootTrajectoryGenerator = registerModule<FootTrajectoryGenerator2018>("FootTrajectoryGenerator2018", true);
theHipRotationOffsetModifier = registerModule<HipRotationOffsetModifier>("HipRotationOffsetModifier", true);
theLiftingFootCompensator = registerModule<LiftingFootCompensator>("LiftingFootCompensator", true);
theTorsoRotationStabilizer = registerModule<TorsoRotationStabilizer>("TorsoRotationStabilizer", true);
theFeetStabilizer = registerModule<FeetStabilizer>("FeetStabilizer", true);
CoMFeetPose currentCOMFeetPose = getInverseKinematicsMotionEngineService().getEngine().getCurrentCoMFeetPose();
currentCOMFeetPose.localInLeftFoot();
Vector3d targetZMP(currentCOMFeetPose.com.translation);
targetZMP.z = getInverseKinematicsMotionEngineService().getEngine().getParameters().walk.hip.comHeight;
// init state of preview controller
theZMPPreviewController->getModuleT()->init(currentCOMFeetPose.com.translation);
int inital_number_of_cycles = static_cast<int>(theZMPPreviewController->getModuleT()->previewSteps());
// init step buffer using the foot step planner
theFootStepPlanner->getModuleT()->init(inital_number_of_cycles,currentCOMFeetPose.feet);
// init zmp reference buffer using the zmp planner
theZMPPlanner->getModuleT()->init(inital_number_of_cycles, currentCOMFeetPose.com.translation, targetZMP);
std::cout << "walk start" << std::endl;
}
void Walk2018::execute()
{
// check the integrity
getMotionRequest().walkRequest.assertValid();
theCoMErrorProvider->execute();
// planing phase
// add new steps or delete executed ones if necessary
theFootStepPlanner->execute();
// NOTE: check the integrity of the step buffer
ASSERT(!getStepBuffer().empty());
ASSERT(!getStepBuffer().last().isPlanned());
theZMPPlanner->execute();
// running phase
ASSERT(!getStepBuffer().first().isExecuted());
calculateTargetCoMFeetPose();
DEBUG_REQUEST("Walk:draw_step_plan_geometry",
FIELD_DRAWING_CONTEXT;
getStepBuffer().draw(getDebugDrawings());
);
// set arms
// Attention: this will be overwritten by the arm motion engine if the ArmMotionRequest's MotionID is not equal to "none" or "arms_synchronised_with_walk"
// NOTE: we set the arms before the calculation of the com, so the motion of the com can be adjusted to the arms
if(parameters().general.useArm) {
getEngine().armsSynchronisedWithWalk(getRobotInfo(), getTargetCoMFeetPose().pose, getMotorJointData());
}
// calculate HipFeetPose which is getting close to the target CoMFeetPose
bool solved = false;
getTargetHipFeetPose().pose = getEngine().controlCenterOfMass(getMotorJointData(), getTargetCoMFeetPose().pose, solved, false);
HipFeetPose cassert(getTargetHipFeetPose().pose);
cassert.localInHip();
ASSERT(std::abs(cassert.feet.left.translation.x) < 150);
ASSERT(std::abs(cassert.feet.left.translation.y) < 200);
ASSERT(std::abs(cassert.feet.left.translation.z) < 350);
ASSERT(std::abs(cassert.feet.right.translation.x) < 150);
ASSERT(std::abs(cassert.feet.right.translation.y) < 200);
ASSERT(std::abs(cassert.feet.right.translation.z) < 350);
theTorsoRotationStabilizer->execute();
calculateJoints();
// STABILIZATION
if(parameters().stabilization.stabilizeFeet) {
theFeetStabilizer->execute();
}
updateMotionStatus(getMotionStatus());
if(getMotionRequest().id != getId() && theZMPPreviewController->getModuleT()->is_stationary()) {
// reset buffers
getCoMErrors().reset();
getCommandBuffer().reset();
getStepBuffer().reset();
getZMPReferenceBuffer().reset();
theHipRotationOffsetModifier->getModuleT()->reset();
setCurrentState(motion::stopped);
std::cout << "walk stopped" << std::endl;
} else {
setCurrentState(motion::running);
}
}//end execute
void Walk2018::calculateTargetCoMFeetPose()
{
theZMPPreviewController->execute();
Vector3d com = getTargetCoMFeetPose().pose.com.translation;
DEBUG_REQUEST("Walk:draw_step_plan_geometry",
FIELD_DRAWING_CONTEXT;
getDebugDrawings().pen(Color::BLUE, 1.0);
getDebugDrawings().fillOval(com.x, com.y, 10, 10);
);
theFootTrajectoryGenerator->execute();
theHipRotationOffsetModifier->execute();
theLiftingFootCompensator->execute();
// buffer target CoM feet pose
getCommandBuffer().footIds.add(getStepBuffer().first().footStep.liftingFoot());
getCommandBuffer().poses.add(getTargetCoMFeetPose().pose);
getStepBuffer().first().executingCycle++;
}
void Walk2018::calculateJoints() {
getEngine().solveHipFeetIK(getTargetHipFeetPose().pose);
getEngine().copyLegJoints(getMotorJointData().position);
// set stiffness for the arms
for (size_t i = JointData::RShoulderRoll; i <= JointData::LElbowYaw; ++i) {
getMotorJointData().stiffness[i] = parameters().general.stiffnessArms;
}
getMotorJointData().stiffness[JointData::LWristYaw] = parameters().general.stiffnessArms;
getMotorJointData().stiffness[JointData::RWristYaw] = parameters().general.stiffnessArms;
// set the legs stiffness for walking
for (size_t i = JointData::RHipYawPitch; i <= JointData::LAnkleRoll; ++i) {
getMotorJointData().stiffness[i] = parameters().general.stiffness;
}
// WIEDERLICHER HACK: force the hip joint
if (getMotorJointData().position[JointData::LHipRoll] < 0) {
getMotorJointData().position[JointData::LHipRoll] *= parameters().general.hipRollSingleSupFactorLeft; // if = 1 no damping or amplifing
}
if (getMotorJointData().position[JointData::RHipRoll] > 0) {
getMotorJointData().position[JointData::RHipRoll] *= parameters().general.hipRollSingleSupFactorRight; // if = 1 no damping or amplifing
}
}
void Walk2018::updateMotionStatus(MotionStatus& motionStatus) const
{
if ( getStepBuffer().empty() )
{
motionStatus.plannedMotion.lFoot = Pose2D();
motionStatus.plannedMotion.rFoot = Pose2D();
motionStatus.plannedMotion.hip = Pose2D();
}
else
{
// TODO: check
FeetPose lastFeet = getStepBuffer().last().footStep.end();
Pose3D lastCom = calculateStableCoMByFeet(lastFeet, getEngine().getParameters().walk.general.bodyPitchOffset);
Pose3D plannedHip = getTargetCoMFeetPose().pose.com.invert() * lastCom;
Pose3D plannedlFoot = getTargetCoMFeetPose().pose.feet.left.invert() * lastFeet.left;
Pose3D plannedrFoot = getTargetCoMFeetPose().pose.feet.right.invert() * lastFeet.right;
motionStatus.plannedMotion.hip = plannedHip.projectXY();
motionStatus.plannedMotion.lFoot = plannedlFoot.projectXY();
motionStatus.plannedMotion.rFoot = plannedrFoot.projectXY();
}
// step control
if ( getStepBuffer().empty() )
{
motionStatus.stepControl.stepID = 0;
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::BOTH;
}
else
{
motionStatus.stepControl.stepID = getStepBuffer().last().id() + 1;
FootStep::Foot lastMovingFoot = getStepBuffer().last().footStep.liftingFoot();
switch(lastMovingFoot)
{
case FootStep::NONE:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::BOTH;
break;
case FootStep::LEFT:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::RIGHT;
break;
case FootStep::RIGHT:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::LEFT;
break;
default:
ASSERT(false);
}
}
}//end updateMotionStatus
<commit_msg>small clean up in Walk2018<commit_after>/**
* @file Walk.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich, Mellmann</a>
* @author <a href="mailto:kaden@informatik.hu-berlin.de">Steffen, Kaden</a>
*
*/
#include "Walk2018.h"
#include "../Walk/FootTrajectoryGenerator.h"
#include "../Walk/ZMPPlanner.h"
#include "Tools/DataStructures/Spline.h"
using namespace naoth;
using namespace InverseKinematic;
Walk2018::Walk2018() : IKMotion(getInverseKinematicsMotionEngineService(), motion::walk, getMotionLock())
{
DEBUG_REQUEST_REGISTER("Walk:draw_step_plan_geometry", "draw all planed steps, zmp and executed com", false);
DEBUG_REQUEST_REGISTER("Walk:plot_genTrajectoryWithSplines", "plot spline interpolation to parametrize 3D foot trajectory", false);
theCoMErrorProvider = registerModule<CoMErrorProvider>("CoMErrorProvider", true);
theFootStepPlanner = registerModule<FootStepPlanner2018>("FootStepPlanner2018", true);
theZMPPlanner = registerModule<ZMPPlanner2018>("ZMPPlanner2018", true);
theZMPPreviewController = registerModule<ZMPPreviewController>("ZMPPreviewController", true);
theFootTrajectoryGenerator = registerModule<FootTrajectoryGenerator2018>("FootTrajectoryGenerator2018", true);
theHipRotationOffsetModifier = registerModule<HipRotationOffsetModifier>("HipRotationOffsetModifier", true);
theLiftingFootCompensator = registerModule<LiftingFootCompensator>("LiftingFootCompensator", true);
theTorsoRotationStabilizer = registerModule<TorsoRotationStabilizer>("TorsoRotationStabilizer", true);
theFeetStabilizer = registerModule<FeetStabilizer>("FeetStabilizer", true);
CoMFeetPose currentCOMFeetPose = getInverseKinematicsMotionEngineService().getEngine().getCurrentCoMFeetPose();
currentCOMFeetPose.localInLeftFoot();
Vector3d targetZMP(currentCOMFeetPose.com.translation);
targetZMP.z = getInverseKinematicsMotionEngineService().getEngine().getParameters().walk.hip.comHeight;
// init state of preview controller
theZMPPreviewController->getModuleT()->init(currentCOMFeetPose.com.translation);
int inital_number_of_cycles = static_cast<int>(theZMPPreviewController->getModuleT()->previewSteps());
// init step buffer using the foot step planner
theFootStepPlanner->getModuleT()->init(inital_number_of_cycles,currentCOMFeetPose.feet);
// init zmp reference buffer using the zmp planner
theZMPPlanner->getModuleT()->init(inital_number_of_cycles, currentCOMFeetPose.com.translation, targetZMP);
std::cout << "walk start" << std::endl;
}
void Walk2018::execute()
{
// check the integrity
getMotionRequest().walkRequest.assertValid();
theCoMErrorProvider->execute();
// planing phase
// add new steps or delete executed ones if necessary
theFootStepPlanner->execute();
DEBUG_REQUEST("Walk:draw_step_plan_geometry",
FIELD_DRAWING_CONTEXT;
getStepBuffer().draw(getDebugDrawings());
);
// NOTE: check the integrity of the step buffer
ASSERT(!getStepBuffer().empty());
ASSERT(!getStepBuffer().last().isPlanned());
theZMPPlanner->execute();
// running phase
ASSERT(!getStepBuffer().first().isExecuted());
calculateTargetCoMFeetPose();
// set arms
// Attention: this will be overwritten by the arm motion engine if the ArmMotionRequest's MotionID is not equal to "none" or "arms_synchronised_with_walk"
// NOTE: we set the arms before the calculation of the com, so the motion of the com can be adjusted to the arms
if(parameters().general.useArm) {
getEngine().armsSynchronisedWithWalk(getRobotInfo(), getTargetCoMFeetPose().pose, getMotorJointData());
}
// calculate HipFeetPose which is getting close to the target CoMFeetPose
bool solved = false;
getTargetHipFeetPose().pose = getEngine().controlCenterOfMass(getMotorJointData(), getTargetCoMFeetPose().pose, solved, false);
HipFeetPose cassert(getTargetHipFeetPose().pose);
cassert.localInHip();
ASSERT(std::abs(cassert.feet.left.translation.x) < 150);
ASSERT(std::abs(cassert.feet.left.translation.y) < 200);
ASSERT(std::abs(cassert.feet.left.translation.z) < 350);
ASSERT(std::abs(cassert.feet.right.translation.x) < 150);
ASSERT(std::abs(cassert.feet.right.translation.y) < 200);
ASSERT(std::abs(cassert.feet.right.translation.z) < 350);
theTorsoRotationStabilizer->execute();
calculateJoints();
updateMotionStatus(getMotionStatus());
if(getMotionRequest().id != getId() && theZMPPreviewController->getModuleT()->is_stationary()) {
// reset buffers
getCoMErrors().reset();
getCommandBuffer().reset();
getStepBuffer().reset();
getZMPReferenceBuffer().reset();
theHipRotationOffsetModifier->getModuleT()->reset();
setCurrentState(motion::stopped);
std::cout << "walk stopped" << std::endl;
} else {
setCurrentState(motion::running);
}
}//end execute
void Walk2018::calculateTargetCoMFeetPose()
{
theZMPPreviewController->execute();
Vector3d com = getTargetCoMFeetPose().pose.com.translation;
DEBUG_REQUEST("Walk:draw_step_plan_geometry",
FIELD_DRAWING_CONTEXT;
getDebugDrawings().pen(Color::BLUE, 1.0);
getDebugDrawings().fillOval(com.x, com.y, 10, 10);
);
theFootTrajectoryGenerator->execute();
theHipRotationOffsetModifier->execute();
theLiftingFootCompensator->execute();
// buffer target CoM feet pose
getCommandBuffer().footIds.add(getStepBuffer().first().footStep.liftingFoot());
getCommandBuffer().poses.add(getTargetCoMFeetPose().pose);
getStepBuffer().first().executingCycle++;
}
void Walk2018::calculateJoints() {
getEngine().solveHipFeetIK(getTargetHipFeetPose().pose);
getEngine().copyLegJoints(getMotorJointData().position);
// set stiffness for the arms
for (size_t i = JointData::RShoulderRoll; i <= JointData::LElbowYaw; ++i) {
getMotorJointData().stiffness[i] = parameters().general.stiffnessArms;
}
getMotorJointData().stiffness[JointData::LWristYaw] = parameters().general.stiffnessArms;
getMotorJointData().stiffness[JointData::RWristYaw] = parameters().general.stiffnessArms;
// set the legs stiffness for walking
for (size_t i = JointData::RHipYawPitch; i <= JointData::LAnkleRoll; ++i) {
getMotorJointData().stiffness[i] = parameters().general.stiffness;
}
// WIEDERLICHER HACK: force the hip joint
if (getMotorJointData().position[JointData::LHipRoll] < 0) {
getMotorJointData().position[JointData::LHipRoll] *= parameters().general.hipRollSingleSupFactorLeft; // if = 1 no damping or amplifing
}
if (getMotorJointData().position[JointData::RHipRoll] > 0) {
getMotorJointData().position[JointData::RHipRoll] *= parameters().general.hipRollSingleSupFactorRight; // if = 1 no damping or amplifing
}
// STABILIZATION
theFeetStabilizer->execute();
}
void Walk2018::updateMotionStatus(MotionStatus& motionStatus) const
{
if ( getStepBuffer().empty() )
{
motionStatus.plannedMotion.lFoot = Pose2D();
motionStatus.plannedMotion.rFoot = Pose2D();
motionStatus.plannedMotion.hip = Pose2D();
}
else
{
// TODO: check
FeetPose lastFeet = getStepBuffer().last().footStep.end();
Pose3D lastCom = calculateStableCoMByFeet(lastFeet, getEngine().getParameters().walk.general.bodyPitchOffset);
Pose3D plannedHip = getTargetCoMFeetPose().pose.com.invert() * lastCom;
Pose3D plannedlFoot = getTargetCoMFeetPose().pose.feet.left.invert() * lastFeet.left;
Pose3D plannedrFoot = getTargetCoMFeetPose().pose.feet.right.invert() * lastFeet.right;
motionStatus.plannedMotion.hip = plannedHip.projectXY();
motionStatus.plannedMotion.lFoot = plannedlFoot.projectXY();
motionStatus.plannedMotion.rFoot = plannedrFoot.projectXY();
}
// step control
if ( getStepBuffer().empty() )
{
motionStatus.stepControl.stepID = 0;
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::BOTH;
}
else
{
motionStatus.stepControl.stepID = getStepBuffer().last().id() + 1;
FootStep::Foot lastMovingFoot = getStepBuffer().last().footStep.liftingFoot();
switch(lastMovingFoot)
{
case FootStep::NONE:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::BOTH;
break;
case FootStep::LEFT:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::RIGHT;
break;
case FootStep::RIGHT:
motionStatus.stepControl.moveableFoot = MotionStatus::StepControlStatus::LEFT;
break;
default:
ASSERT(false);
}
}
}//end updateMotionStatus
<|endoftext|> |
<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "task_panel_manager.h"
using Task = You::Controller::Task;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(false);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->setColumnHidden(0, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
if (task.getDeadline() == Task::NEVER) {
result.push_back(QString("Never"));
} else {
result.push_back(boost::lexical_cast<QString>(task.getDeadline()));
}
// Iterate through task list and add it to the task panel
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// TODO(angathorion): Deal with dependencies
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
<commit_msg>Fixed stretch last section of header.<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "task_panel_manager.h"
using Task = You::Controller::Task;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(true);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->setColumnHidden(0, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
if (task.getDeadline() == Task::NEVER) {
result.push_back(QString("Never"));
} else {
result.push_back(boost::lexical_cast<QString>(task.getDeadline()));
}
// Iterate through task list and add it to the task panel
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// TODO(angathorion): Deal with dependencies
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
<|endoftext|> |
<commit_before>// Read a file and parse each line according to the format file.
// Output integer matrices with lookup maps in either ascii text
// or matlab binary form.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <limits>
#include "utils.h"
#include "gzstream.h"
#define BUFSIZE 1048576
class stringIndexer {
public:
ivector count;
unhash unh;
strhash htab;
int size;
char * linebuf;
stringIndexer() : htab(0), unh(0), count(0), size(0) {
linebuf = new char[BUFSIZE];
};
stringIndexer(const stringIndexer & si);
~stringIndexer();
stringIndexer(char *);
int writeMap(string fname, string suffix) {
writeIntVec(count, fname + ".cnt.imat" + suffix, BUFSIZE);
return writeSBVecs(unh, fname + ".sbmat" + suffix, BUFSIZE);
}
int checkword(char *str);
};
int stringIndexer::
checkword(char * str) {
int userno;
char * newstr;
if (htab.count(str)) {
userno = htab[str];
count[userno-1]++;
} else {
try {
newstr = new char[strlen(str)+1];
strcpy(newstr, str);
userno = ++size;
htab[newstr] = userno;
count.push_back(1);
unh.push_back(newstr);
} catch (std::bad_alloc) {
cerr << "stringIndexer:checkstr: allocation error" << endl;
throw;
}
}
return userno;
}
stringIndexer::
~stringIndexer() {
int i;
for (i=0; i<unh.size(); i++) {
if (unh[i]) {
delete [] unh[i];
unh[i] = NULL;
}
}
if (linebuf) {
delete [] linebuf;
linebuf = NULL;
}
}
int parseLine(char * line, const char * delim1, const char * delim2, const char *delim3,
const char * delim4, stringIndexer & si, fvector &labels, imatrix & imat, fvector & fvec) {
char *here, *next, *fpos;
int label, indx;
float fval;
ivector iv;
here = line;
next = strpbrk(here, delim1); // get the label(s)
*(next++) = 0;
sscanf(here, "%d", &label);
here = next;
labels.push_back(label);
next = strpbrk(here, delim2); // get the tag
*(next++) = 0;
// Do nothing with the tag for now
here = next;
while (here != NULL) {
next = strpbrk(here, delim3); // get a feature/value pair
if (next) {
*(next++) = 0;
}
// Actually parse in here
fpos = strpbrk(here, delim4); // get a value, if there is one
fval = 1.0;
if (fpos) {
sscanf(fpos+1, "%f", &fval);
*fpos = 0;
}
indx = si.checkword(here);
iv.push_back(indx);
fvec.push_back(fval);
here = next;
}
imat.push_back(iv);
return 0;
}
void writefiles(string fname, imatrix &imat, fvector &fvec, fvector &labels, string suffix, int &ifile, int membuf) {
char num[6];
sprintf(num, "%05d", ifile);
writeIntVecs(imat, fname+"inds"+num+".imat"+suffix, membuf);
writeFVec(fvec, fname+"vals"+num+".fmat"+suffix, membuf);
writeFVec(labels, fname+"labels"+num+".fmat"+suffix, membuf);
ifile++;
imat.clear();
fvec.clear();
labels.clear();
}
const char usage[] =
"\nParser for generalized libsvm files. Arguments are\n"
" -i <infile> input file[s] to read\n"
" -o <outd> output files will be written to <outd><infile>.imat[.gz]\n"
" -d <dictfile> dictionary will be written to <dictfile>.sbmat[.gz]\n"
" and word counts will be written to <dictfile>.imat[.gz]\n"
" -s N set buffer size to N.\n"
" -n N split files at N lines.\n"
" -c produce compressed (gzipped) output files.\n\n"
;
int main(int argc, char ** argv) {
int jmax, iarg=1, membuf=1048576, nsplit=100000, nfiles = 0;
long long numlines;
char *here, *linebuf, *readbuf;
char *ifname = NULL;
string odname="", dictname = "", suffix = "";
string delim1=" ", delim2="|", delim3=" ", delim4=":";
while (iarg < argc) {
if (strncmp(argv[iarg], "-i", 2) == 0) {
ifname = argv[++iarg];
} else if (strncmp(argv[iarg], "-o", 2) == 0) {
odname = argv[++iarg];
} else if (strncmp(argv[iarg], "-d", 2) == 0) {
dictname = argv[++iarg];
} else if (strncmp(argv[iarg], "-s", 2) == 0) {
membuf = strtol(argv[++iarg],NULL,10);
} else if (strncmp(argv[iarg], "-n", 2) == 0) {
nsplit = strtol(argv[++iarg],NULL,10);
} else if (strncmp(argv[iarg], "-c", 2) == 0) {
suffix=".gz";
} else if (strncmp(argv[iarg], "-?", 2) == 0) {
printf("%s", usage);
return 1;
} else if (strncmp(argv[iarg], "-h", 2) == 0) {
printf("%s", usage);
return 1;
} else {
cout << "Unknown option " << argv[iarg] << endl;
exit(1);
}
iarg++;
}
imatrix imat;
fvector fvec;
fvector labels;
istream * ifstr;
stringIndexer si;
linebuf = new char[membuf];
readbuf = new char[membuf];
if (dictname.size() == 0) dictname = odname+"dict";
here = strtok(ifname, " ,");
while (here != NULL) {
ifstr = open_in_buf(ifname, readbuf, membuf);
numlines = 0;
while (!ifstr->bad() && !ifstr->eof()) {
ifstr->getline(linebuf, membuf-1);
linebuf[membuf-1] = 0;
if (ifstr->fail()) {
ifstr->clear();
ifstr->ignore(std::numeric_limits<long>::max(),'\n');
}
if (strlen(linebuf) > 0) {
jmax++;
numlines++;
try {
parseLine(linebuf, delim1.c_str(), delim2.c_str(), delim3.c_str(), delim4.c_str(),
si, labels, imat, fvec);
} catch (int e) {
cerr << "Continuing" << endl;
}
}
if ((numlines % 100000) == 0) {
cout<<"\r"<<numlines<<" lines processed";
cout.flush();
}
if ((numlines % nsplit) == 0) {
writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf);
}
}
if ((numlines % nsplit) != 0) {
writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf);
}
if (ifstr) delete ifstr;
cout<<"\r"<<numlines<<" lines processed";
cout.flush();
string rname = here;
if (strstr(here, ".gz") - here == strlen(here) - 3) {
rname = rname.substr(0, strlen(here) - 3);
}
here = strtok(NULL, " ,");
}
fprintf(stderr, "\nWriting Dictionary\n");
si.writeMap(dictname, suffix);
}
<commit_msg>fixed parsevw<commit_after>// Read a file and parse each line according to the format file.
// Output integer matrices with lookup maps in either ascii text
// or matlab binary form.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <limits>
#include "utils.h"
#include "gzstream.h"
#define BUFSIZE 1048576
class stringIndexer {
public:
ivector count;
unhash unh;
strhash htab;
int size;
char * linebuf;
stringIndexer() : htab(0), unh(0), count(0), size(0) {
linebuf = new char[BUFSIZE];
};
stringIndexer(const stringIndexer & si);
~stringIndexer();
stringIndexer(char *);
int writeMap(string fname, string suffix) {
writeIntVec(count, fname + ".cnt.imat" + suffix, BUFSIZE);
return writeSBVecs(unh, fname + ".sbmat" + suffix, BUFSIZE);
}
int checkword(char *str);
};
int stringIndexer::
checkword(char * str) {
int userno;
char * newstr;
if (htab.count(str)) {
userno = htab[str];
count[userno-1]++;
} else {
try {
newstr = new char[strlen(str)+1];
strcpy(newstr, str);
userno = ++size;
htab[newstr] = userno;
count.push_back(1);
unh.push_back(newstr);
} catch (std::bad_alloc) {
cerr << "stringIndexer:checkstr: allocation error" << endl;
throw;
}
}
return userno;
}
stringIndexer::
~stringIndexer() {
int i;
for (i=0; i<unh.size(); i++) {
if (unh[i]) {
delete [] unh[i];
unh[i] = NULL;
}
}
if (linebuf) {
delete [] linebuf;
linebuf = NULL;
}
}
int parseLine(char * line, const char * delim1, const char * delim2, const char *delim3,
const char * delim4, stringIndexer & si, fvector &labels, imatrix & imat, fvector & fvec) {
char *here, *next, *fpos;
int label, indx;
float fval;
ivector iv;
here = line;
next = strpbrk(here, delim1); // get the label(s)
*(next++) = 0;
sscanf(here, "%d", &label);
here = next;
labels.push_back(label);
next = strpbrk(here, delim2); // get the tag
*(next++) = 0;
// Do nothing with the tag for now
here = next;
while (here != NULL) {
next = strpbrk(here, delim3); // get a feature/value pair
if (next) {
*(next++) = 0;
}
// Actually parse in here
fpos = strpbrk(here, delim4); // get a value, if there is one
fval = 1.0;
if (fpos) {
sscanf(fpos+1, "%f", &fval);
*fpos = 0;
}
indx = si.checkword(here);
iv.push_back(indx-1);
fvec.push_back(fval);
here = next;
}
imat.push_back(iv);
return 0;
}
void writefiles(string fname, imatrix &imat, fvector &fvec, fvector &labels, string suffix, int &ifile, int membuf) {
char num[6];
sprintf(num, "%05d", ifile);
writeIntVecs(imat, fname+"inds"+num+".imat"+suffix, membuf);
writeFVec(fvec, fname+"vals"+num+".fmat"+suffix, membuf);
writeFVec(labels, fname+"labels"+num+".fmat"+suffix, membuf);
ifile++;
imat.clear();
fvec.clear();
labels.clear();
}
const char usage[] =
"\nParser for generalized libsvm files. Arguments are\n"
" -i <infile> input file[s] to read\n"
" -o <outd> output files will be written to <outd><infile>.imat[.gz]\n"
" -d <dictfile> dictionary will be written to <dictfile>.sbmat[.gz]\n"
" and word counts will be written to <dictfile>.imat[.gz]\n"
" -s N set buffer size to N.\n"
" -n N split files at N lines.\n"
" -c produce compressed (gzipped) output files.\n\n"
;
int main(int argc, char ** argv) {
int jmax, iarg=1, membuf=1048576, nsplit=100000, nfiles = 0;
long long numlines;
char *here, *linebuf, *readbuf;
char *ifname = NULL;
string odname="", dictname = "", suffix = "";
string delim1=" ", delim2="|", delim3=" ", delim4=":";
while (iarg < argc) {
if (strncmp(argv[iarg], "-i", 2) == 0) {
ifname = argv[++iarg];
} else if (strncmp(argv[iarg], "-o", 2) == 0) {
odname = argv[++iarg];
} else if (strncmp(argv[iarg], "-d", 2) == 0) {
dictname = argv[++iarg];
} else if (strncmp(argv[iarg], "-s", 2) == 0) {
membuf = strtol(argv[++iarg],NULL,10);
} else if (strncmp(argv[iarg], "-n", 2) == 0) {
nsplit = strtol(argv[++iarg],NULL,10);
} else if (strncmp(argv[iarg], "-c", 2) == 0) {
suffix=".gz";
} else if (strncmp(argv[iarg], "-?", 2) == 0) {
printf("%s", usage);
return 1;
} else if (strncmp(argv[iarg], "-h", 2) == 0) {
printf("%s", usage);
return 1;
} else {
cout << "Unknown option " << argv[iarg] << endl;
exit(1);
}
iarg++;
}
imatrix imat;
fvector fvec;
fvector labels;
istream * ifstr;
stringIndexer si;
linebuf = new char[membuf];
readbuf = new char[membuf];
if (dictname.size() == 0) dictname = odname+"dict";
here = strtok(ifname, " ,");
while (here != NULL) {
ifstr = open_in_buf(ifname, readbuf, membuf);
numlines = 0;
while (!ifstr->bad() && !ifstr->eof()) {
ifstr->getline(linebuf, membuf-1);
linebuf[membuf-1] = 0;
if (ifstr->fail()) {
ifstr->clear();
ifstr->ignore(std::numeric_limits<long>::max(),'\n');
}
if (strlen(linebuf) > 0) {
jmax++;
numlines++;
try {
parseLine(linebuf, delim1.c_str(), delim2.c_str(), delim3.c_str(), delim4.c_str(),
si, labels, imat, fvec);
} catch (int e) {
cerr << "Continuing" << endl;
}
}
if ((numlines % 100000) == 0) {
cout<<"\r"<<numlines<<" lines processed";
cout.flush();
}
if ((numlines % nsplit) == 0) {
writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf);
}
}
if ((numlines % nsplit) != 0) {
writefiles(odname, imat, fvec, labels, suffix, nfiles, membuf);
}
if (ifstr) delete ifstr;
cout<<"\r"<<numlines<<" lines processed";
cout.flush();
string rname = here;
if (strstr(here, ".gz") - here == strlen(here) - 3) {
rname = rname.substr(0, strlen(here) - 3);
}
here = strtok(NULL, " ,");
}
fprintf(stderr, "\nWriting Dictionary\n");
si.writeMap(dictname, suffix);
}
<|endoftext|> |
<commit_before>#pragma once
#include <unordered_map>
namespace ln {
namespace detail {
class ShaderManager;
}
}
class FxcCommand
{
public:
ln::Path outputFile;
bool saveCodes = true;
int execute(const ln::Path& inputFile);
private:
bool generate(const ln::Path& inputFile);
ln::Ref<ln::detail::ShaderManager> m_manager;
ln::Ref<ln::DiagnosticsManager> m_diag;
//struct ShaderCode
//{
// std::string glslCode;
// //std::vector<uint32_t> spirvCode;
//};
//std::unordered_map<std::string, ShaderCode> m_vertexShaderCodeMap;
//std::unordered_map<std::string, ShaderCode> m_pixelShaderCodeMap;
};
<commit_msg>fxc disable code saving<commit_after>#pragma once
#include <unordered_map>
namespace ln {
namespace detail {
class ShaderManager;
}
}
class FxcCommand
{
public:
ln::Path outputFile;
bool saveCodes = false;
int execute(const ln::Path& inputFile);
private:
bool generate(const ln::Path& inputFile);
ln::Ref<ln::detail::ShaderManager> m_manager;
ln::Ref<ln::DiagnosticsManager> m_diag;
//struct ShaderCode
//{
// std::string glslCode;
// //std::vector<uint32_t> spirvCode;
//};
//std::unordered_map<std::string, ShaderCode> m_vertexShaderCodeMap;
//std::unordered_map<std::string, ShaderCode> m_pixelShaderCodeMap;
};
<|endoftext|> |
<commit_before>/* detectMotionObject.cpp */
//-----------------------------------------------------------------------
// include files
//-----------------------------------------------------------------------
#include <vector>
#include <opencv2/opencv.hpp>
#include "detectMotionObject.h"
#include "optFlow2RGB.h"
//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------
//***********************************************************************
// Function : detectMotionObject |
//***********************************************************************
void detectMotionObject( cv::Mat& curr, cv::Mat& gray, std::vector<cv::Rect>& detected_obj ){
// 平滑化
blur( gray, gray, cv::Size(3,3) );
// cv::imshow("gray", gray);
// 二値化
cv::Mat bin;
cv::threshold((gray.type() == CV_32FC1) ? cv::Mat1b(gray*255): gray, bin, 10, 255.0, CV_THRESH_BINARY);
// cv::imshow("bin", bin);
//輪郭の座標リスト
std::vector<std::vector<cv::Point>> contours;
//輪郭取得
cv::findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Mat curr_disp = curr.clone();
std::vector<cv::Rect> detected_obj_tmp;
for (auto contour: contours){
// 輪郭を直線近似する
std::vector< cv::Point > approx;
cv::approxPolyDP(cv::Mat(contour), approx, 0.01 * cv::arcLength(contour, true), true);
// 近似の面積が一定以上なら取得
double area = cv::contourArea(approx);
if (area > 1000.0){
// 検出された輪郭線を緑で描画
// cv::polylines(curr_disp, *contour, true, cv::Scalar(0, 255, 0), 2);
// 外接矩形を描画
detected_obj_tmp.push_back( cv::boundingRect(cv::Mat(approx).reshape(2)) );
// cv::rectangle(curr_disp, detected_obj.back().tl(), detected_obj.back().br(), cv::Scalar(255, 0, 0), 2, CV_AA);
}
}
// 近接する矩形同士をマージ
// cout << detected_obj_tmp.size() << ", ";
if( detected_obj_tmp.size() > 1 ){
for(auto& i: detected_obj_tmp){
if(i.area() == 0){
continue;
}
cv::Point2i i_centerP = (i.tl() + i.br())/2;
int i_S = i.area();
for(auto& j: detected_obj_tmp){
if(i == j || j.area() == 0){
continue;
}
cv::Point2i j_centerP = (j.tl() + j.br())/2;
int j_S = j.area();
cv::Rect rect_tmp(i_centerP, j_centerP);
int contain = 0;
if(i_S > j_S){
contain += (i.contains(rect_tmp.tl()))?1:0;
contain += (i.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
contain += (i.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
contain += (i.contains(rect_tmp.br()))?1:0;
} else {
contain += (j.contains(rect_tmp.tl()))?1:0;
contain += (j.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
contain += (j.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
contain += (j.contains(rect_tmp.br()))?1:0;
}
if(contain > 3){
i |= j;
} else if( contain == 2){
if( rect_tmp.width > rect_tmp.height ){
if( 10 < rect_tmp.width - (i.width + j.width)/2 ){
i |= j;
j = cv::Rect();
}
} else {
if( 10 < rect_tmp.height - (i.height + j.height)/2 ){
i |= j;
j = cv::Rect();
}
}
}
}
}
}
for(auto i: detected_obj_tmp){
if(i.area() > 0){
detected_obj.push_back(i);
}
}
// cout << detected_obj.size() << "| ";
//全体を表示する場合
// cv::imshow("coun", curr_disp);
}
<commit_msg>インデントとか修正<commit_after>/* detectMotionObject.cpp */
//-----------------------------------------------------------------------
// include files
//-----------------------------------------------------------------------
#include <vector>
#include <opencv2/opencv.hpp>
#include "detectMotionObject.h"
#include "optFlow2RGB.h"
//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------
//***********************************************************************
// Function : detectMotionObject |
//***********************************************************************
void detectMotionObject( cv::Mat& curr, cv::Mat& gray, std::vector<cv::Rect>& detected_obj ){
// 平滑化
blur( gray, gray, cv::Size(3,3) );
// cv::imshow("gray", gray);
// 二値化
cv::Mat bin;
cv::threshold((gray.type() == CV_32FC1) ? cv::Mat1b(gray*255): gray, bin, 10, 255.0, CV_THRESH_BINARY);
// cv::imshow("bin", bin);
//輪郭の座標リスト
std::vector<std::vector<cv::Point>> contours;
//輪郭取得
cv::findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::Mat curr_disp = curr.clone();
std::vector<cv::Rect> detected_obj_tmp;
for (auto contour: contours){
// 輪郭を直線近似する
std::vector< cv::Point > approx;
cv::approxPolyDP(cv::Mat(contour), approx, 0.01 * cv::arcLength(contour, true), true);
// 近似の面積が一定以上なら取得
double area = cv::contourArea(approx);
if (area > 1000.0){
// 検出された輪郭線を緑で描画
// cv::polylines(curr_disp, *contour, true, cv::Scalar(0, 255, 0), 2);
// 外接矩形を描画
detected_obj_tmp.push_back( cv::boundingRect(cv::Mat(approx).reshape(2)) );
// cv::rectangle(curr_disp, detected_obj.back().tl(), detected_obj.back().br(), cv::Scalar(255, 0, 0), 2, CV_AA);
}
}
// 近接する矩形同士をマージ
if( detected_obj_tmp.size() > 1 ){
for(auto& i: detected_obj_tmp){
if(i.area() == 0){
continue;
}
cv::Point2i i_centerP = (i.tl() + i.br())/2;
int i_S = i.area();
for(auto& j: detected_obj_tmp){
if(i == j || j.area() == 0){
continue;
}
cv::Point2i j_centerP = (j.tl() + j.br())/2;
int j_S = j.area();
cv::Rect rect_tmp(i_centerP, j_centerP);
int contain = 0;
if(i_S > j_S){
contain += (i.contains(rect_tmp.tl()))?1:0;
contain += (i.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
contain += (i.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
contain += (i.contains(rect_tmp.br()))?1:0;
} else {
contain += (j.contains(rect_tmp.tl()))?1:0;
contain += (j.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
contain += (j.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
contain += (j.contains(rect_tmp.br()))?1:0;
}
if(contain > 3){
i |= j;
} else if( contain == 2){
if( rect_tmp.width > rect_tmp.height ){
if( 10 < rect_tmp.width - (i.width + j.width)/2 ){
i |= j;
j = cv::Rect();
}
} else {
if( 10 < rect_tmp.height - (i.height + j.height)/2 ){
i |= j;
j = cv::Rect();
}
}
}
}
}
}
for(auto i: detected_obj_tmp){
if(i.area() > 0){
detected_obj.push_back(i);
}
}
// cv::imshow("coun", curr_disp);
}
<|endoftext|> |
<commit_before>//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Object/MachO.h"
#include <string>
namespace llvm {
namespace dsymutil {
namespace {
/// \brief Stores all information relating to a compile unit, be it in
/// its original instance in the object file to its brand new cloned
/// and linked DIE tree.
class CompileUnit {
public:
/// \brief Information gathered about a DIE in the object file.
struct DIEInfo {
uint32_t ParentIdx;
};
CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
Info.resize(OrigUnit.getNumDIEs());
}
DWARFUnit &getOrigUnit() const { return OrigUnit; }
DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
private:
DWARFUnit &OrigUnit;
std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
};
/// \brief The core of the Dwarf linking logic.
///
/// The link of the dwarf information from the object files will be
/// driven by the selection of 'root DIEs', which are DIEs that
/// describe variables or functions that are present in the linked
/// binary (and thus have entries in the debug map). All the debug
/// information that will be linked (the DIEs, but also the line
/// tables, ranges, ...) is derived from that set of root DIEs.
///
/// The root DIEs are identified because they contain relocations that
/// correspond to a debug map entry at specific places (the low_pc for
/// a function, the location for a variable). These relocations are
/// called ValidRelocs in the DwarfLinker and are gathered as a very
/// first step when we start processing a DebugMapObject.
class DwarfLinker {
public:
DwarfLinker(StringRef OutputFilename, bool Verbose)
: OutputFilename(OutputFilename), Verbose(Verbose), BinHolder(Verbose) {}
/// \brief Link the contents of the DebugMap.
bool link(const DebugMap &);
private:
/// \brief Called at the start of a debug object link.
void startDebugObject(DWARFContext &);
/// \brief Called at the end of a debug object link.
void endDebugObject();
/// \defgroup FindValidRelocations Translate debug map into a list
/// of relevant relocations
///
/// @{
struct ValidReloc {
uint32_t Offset;
uint32_t Size;
uint64_t Addend;
const DebugMapObject::DebugMapEntry *Mapping;
ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
const DebugMapObject::DebugMapEntry *Mapping)
: Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
};
/// \brief The valid relocations for the current DebugMapObject.
/// This vector is sorted by relocation offset.
std::vector<ValidReloc> ValidRelocs;
/// \brief Index into ValidRelocs of the next relocation to
/// consider. As we walk the DIEs in acsending file offset and as
/// ValidRelocs is sorted by file offset, keeping this index
/// uptodate is all we have to do to have a cheap lookup during the
/// root DIE selection.
unsigned NextValidReloc;
bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
const DebugMapObject &DMO);
bool findValidRelocs(const object::SectionRef &Section,
const object::ObjectFile &Obj,
const DebugMapObject &DMO);
void findValidRelocsMachO(const object::SectionRef &Section,
const object::MachOObjectFile &Obj,
const DebugMapObject &DMO);
/// @}
/// \defgroup Helpers Various helper methods.
///
/// @{
const DWARFDebugInfoEntryMinimal *
resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit *&ReferencedCU);
CompileUnit *getUnitForOffset(unsigned Offset);
void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
const DWARFDebugInfoEntryMinimal *DIE = nullptr);
/// @}
private:
std::string OutputFilename;
bool Verbose;
BinaryHolder BinHolder;
/// The units of the current debug map object.
std::vector<CompileUnit> Units;
/// The debug map object curently under consideration.
DebugMapObject *CurrentDebugObject;
};
/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
/// returning our CompileUnit object instead.
CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
auto CU =
std::upper_bound(Units.begin(), Units.end(), Offset,
[](uint32_t LHS, const CompileUnit &RHS) {
return LHS < RHS.getOrigUnit().getNextUnitOffset();
});
return CU != Units.end() ? &*CU : nullptr;
}
/// \brief Resolve the DIE attribute reference that has been
/// extracted in \p RefValue. The resulting DIE migh be in another
/// CompileUnit which is stored into \p ReferencedCU.
/// \returns null if resolving fails for any reason.
const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
DWARFFormValue &RefValue, const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
uint64_t RefOffset = *RefValue.getAsReference(&Unit);
if ((RefCU = getUnitForOffset(RefOffset)))
if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
return RefDie;
reportWarning("could not find referenced DIE", &Unit, &DIE);
return nullptr;
}
/// \brief Report a warning to the user, optionaly including
/// information about a specific \p DIE related to the warning.
void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
const DWARFDebugInfoEntryMinimal *DIE) {
if (CurrentDebugObject)
errs() << Twine("while processing ") +
CurrentDebugObject->getObjectFilename() + ":\n";
errs() << Twine("warning: ") + Warning + "\n";
if (!Verbose || !DIE)
return;
errs() << " in DIE:\n";
DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
6 /* Indent */);
}
/// \brief Recursive helper to gather the child->parent relationships in the
/// original compile unit.
void GatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE, unsigned ParentIdx,
CompileUnit &CU) {
unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
CU.getInfo(MyIdx).ParentIdx = ParentIdx;
if (DIE->hasChildren())
for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
Child = Child->getSibling())
GatherDIEParents(Child, MyIdx, CU);
}
void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
Units.reserve(Dwarf.getNumCompileUnits());
NextValidReloc = 0;
}
void DwarfLinker::endDebugObject() {
Units.clear();
ValidRelocs.clear();
}
/// \brief Iterate over the relocations of the given \p Section and
/// store the ones that correspond to debug map entries into the
/// ValidRelocs array.
void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
const object::MachOObjectFile &Obj,
const DebugMapObject &DMO) {
StringRef Contents;
Section.getContents(Contents);
DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
for (const object::RelocationRef &Reloc : Section.relocations()) {
object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
uint64_t Offset64;
if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
reportWarning(" unsupported relocation in debug_info section.");
continue;
}
uint32_t Offset = Offset64;
// Mach-o uses REL relocations, the addend is at the relocation offset.
uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
auto Sym = Reloc.getSymbol();
if (Sym != Obj.symbol_end()) {
StringRef SymbolName;
if (Sym->getName(SymbolName)) {
reportWarning("error getting relocation symbol name.");
continue;
}
if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
} else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
// Do not store the addend. The addend was the address of the
// symbol in the object file, the address in the binary that is
// stored in the debug map doesn't need to be offseted.
ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
}
}
}
/// \brief Dispatch the valid relocation finding logic to the
/// appropriate handler depending on the object file format.
bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
const object::ObjectFile &Obj,
const DebugMapObject &DMO) {
// Dispatch to the right handler depending on the file type.
if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
findValidRelocsMachO(Section, *MachOObj, DMO);
else
reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
if (ValidRelocs.empty())
return false;
// Sort the relocations by offset. We will walk the DIEs linearly in
// the file, this allows us to just keep an index in the relocation
// array that we advance during our walk, rather than resorting to
// some associative container. See DwarfLinker::NextValidReloc.
std::sort(ValidRelocs.begin(), ValidRelocs.end());
return true;
}
/// \brief Look for relocations in the debug_info section that match
/// entries in the debug map. These relocations will drive the Dwarf
/// link by indicating which DIEs refer to symbols present in the
/// linked binary.
/// \returns wether there are any valid relocations in the debug info.
bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
const DebugMapObject &DMO) {
// Find the debug_info section.
for (const object::SectionRef &Section : Obj.sections()) {
StringRef SectionName;
Section.getName(SectionName);
SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
if (SectionName != "debug_info")
continue;
return findValidRelocs(Section, Obj, DMO);
}
return false;
}
bool DwarfLinker::link(const DebugMap &Map) {
if (Map.begin() == Map.end()) {
errs() << "Empty debug map.\n";
return false;
}
for (const auto &Obj : Map.objects()) {
CurrentDebugObject = Obj.get();
if (Verbose)
outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
if (std::error_code EC = ErrOrObj.getError()) {
reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
continue;
}
// Look for relocations that correspond to debug map entries.
if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
if (Verbose)
outs() << "No valid relocations found. Skipping.\n";
continue;
}
// Setup access to the debug info.
DWARFContextInMemory DwarfContext(*ErrOrObj);
startDebugObject(DwarfContext);
// In a first phase, just read in the debug info and store the DIE
// parent links that we will use during the next phase.
for (const auto &CU : DwarfContext.compile_units()) {
auto *CUDie = CU->getCompileUnitDIE(false);
if (Verbose) {
outs() << "Input compilation unit:";
CUDie->dump(outs(), CU.get(), 0);
}
Units.emplace_back(*CU);
GatherDIEParents(CUDie, 0, Units.back());
}
// Clean-up before starting working on the next object.
endDebugObject();
}
return true;
}
}
bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, bool Verbose) {
DwarfLinker Linker(OutputFilename, Verbose);
return Linker.link(DM);
}
}
}
<commit_msg>[dsymutil] Downcase a function name.<commit_after>//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Object/MachO.h"
#include <string>
namespace llvm {
namespace dsymutil {
namespace {
/// \brief Stores all information relating to a compile unit, be it in
/// its original instance in the object file to its brand new cloned
/// and linked DIE tree.
class CompileUnit {
public:
/// \brief Information gathered about a DIE in the object file.
struct DIEInfo {
uint32_t ParentIdx;
};
CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
Info.resize(OrigUnit.getNumDIEs());
}
DWARFUnit &getOrigUnit() const { return OrigUnit; }
DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
private:
DWARFUnit &OrigUnit;
std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
};
/// \brief The core of the Dwarf linking logic.
///
/// The link of the dwarf information from the object files will be
/// driven by the selection of 'root DIEs', which are DIEs that
/// describe variables or functions that are present in the linked
/// binary (and thus have entries in the debug map). All the debug
/// information that will be linked (the DIEs, but also the line
/// tables, ranges, ...) is derived from that set of root DIEs.
///
/// The root DIEs are identified because they contain relocations that
/// correspond to a debug map entry at specific places (the low_pc for
/// a function, the location for a variable). These relocations are
/// called ValidRelocs in the DwarfLinker and are gathered as a very
/// first step when we start processing a DebugMapObject.
class DwarfLinker {
public:
DwarfLinker(StringRef OutputFilename, bool Verbose)
: OutputFilename(OutputFilename), Verbose(Verbose), BinHolder(Verbose) {}
/// \brief Link the contents of the DebugMap.
bool link(const DebugMap &);
private:
/// \brief Called at the start of a debug object link.
void startDebugObject(DWARFContext &);
/// \brief Called at the end of a debug object link.
void endDebugObject();
/// \defgroup FindValidRelocations Translate debug map into a list
/// of relevant relocations
///
/// @{
struct ValidReloc {
uint32_t Offset;
uint32_t Size;
uint64_t Addend;
const DebugMapObject::DebugMapEntry *Mapping;
ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
const DebugMapObject::DebugMapEntry *Mapping)
: Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
};
/// \brief The valid relocations for the current DebugMapObject.
/// This vector is sorted by relocation offset.
std::vector<ValidReloc> ValidRelocs;
/// \brief Index into ValidRelocs of the next relocation to
/// consider. As we walk the DIEs in acsending file offset and as
/// ValidRelocs is sorted by file offset, keeping this index
/// uptodate is all we have to do to have a cheap lookup during the
/// root DIE selection.
unsigned NextValidReloc;
bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
const DebugMapObject &DMO);
bool findValidRelocs(const object::SectionRef &Section,
const object::ObjectFile &Obj,
const DebugMapObject &DMO);
void findValidRelocsMachO(const object::SectionRef &Section,
const object::MachOObjectFile &Obj,
const DebugMapObject &DMO);
/// @}
/// \defgroup Helpers Various helper methods.
///
/// @{
const DWARFDebugInfoEntryMinimal *
resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit *&ReferencedCU);
CompileUnit *getUnitForOffset(unsigned Offset);
void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
const DWARFDebugInfoEntryMinimal *DIE = nullptr);
/// @}
private:
std::string OutputFilename;
bool Verbose;
BinaryHolder BinHolder;
/// The units of the current debug map object.
std::vector<CompileUnit> Units;
/// The debug map object curently under consideration.
DebugMapObject *CurrentDebugObject;
};
/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
/// returning our CompileUnit object instead.
CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
auto CU =
std::upper_bound(Units.begin(), Units.end(), Offset,
[](uint32_t LHS, const CompileUnit &RHS) {
return LHS < RHS.getOrigUnit().getNextUnitOffset();
});
return CU != Units.end() ? &*CU : nullptr;
}
/// \brief Resolve the DIE attribute reference that has been
/// extracted in \p RefValue. The resulting DIE migh be in another
/// CompileUnit which is stored into \p ReferencedCU.
/// \returns null if resolving fails for any reason.
const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
DWARFFormValue &RefValue, const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
uint64_t RefOffset = *RefValue.getAsReference(&Unit);
if ((RefCU = getUnitForOffset(RefOffset)))
if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
return RefDie;
reportWarning("could not find referenced DIE", &Unit, &DIE);
return nullptr;
}
/// \brief Report a warning to the user, optionaly including
/// information about a specific \p DIE related to the warning.
void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
const DWARFDebugInfoEntryMinimal *DIE) {
if (CurrentDebugObject)
errs() << Twine("while processing ") +
CurrentDebugObject->getObjectFilename() + ":\n";
errs() << Twine("warning: ") + Warning + "\n";
if (!Verbose || !DIE)
return;
errs() << " in DIE:\n";
DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
6 /* Indent */);
}
/// \brief Recursive helper to gather the child->parent relationships in the
/// original compile unit.
static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
unsigned ParentIdx, CompileUnit &CU) {
unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
CU.getInfo(MyIdx).ParentIdx = ParentIdx;
if (DIE->hasChildren())
for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
Child = Child->getSibling())
gatherDIEParents(Child, MyIdx, CU);
}
void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
Units.reserve(Dwarf.getNumCompileUnits());
NextValidReloc = 0;
}
void DwarfLinker::endDebugObject() {
Units.clear();
ValidRelocs.clear();
}
/// \brief Iterate over the relocations of the given \p Section and
/// store the ones that correspond to debug map entries into the
/// ValidRelocs array.
void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
const object::MachOObjectFile &Obj,
const DebugMapObject &DMO) {
StringRef Contents;
Section.getContents(Contents);
DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
for (const object::RelocationRef &Reloc : Section.relocations()) {
object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
uint64_t Offset64;
if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
reportWarning(" unsupported relocation in debug_info section.");
continue;
}
uint32_t Offset = Offset64;
// Mach-o uses REL relocations, the addend is at the relocation offset.
uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
auto Sym = Reloc.getSymbol();
if (Sym != Obj.symbol_end()) {
StringRef SymbolName;
if (Sym->getName(SymbolName)) {
reportWarning("error getting relocation symbol name.");
continue;
}
if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
} else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
// Do not store the addend. The addend was the address of the
// symbol in the object file, the address in the binary that is
// stored in the debug map doesn't need to be offseted.
ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
}
}
}
/// \brief Dispatch the valid relocation finding logic to the
/// appropriate handler depending on the object file format.
bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
const object::ObjectFile &Obj,
const DebugMapObject &DMO) {
// Dispatch to the right handler depending on the file type.
if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
findValidRelocsMachO(Section, *MachOObj, DMO);
else
reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
if (ValidRelocs.empty())
return false;
// Sort the relocations by offset. We will walk the DIEs linearly in
// the file, this allows us to just keep an index in the relocation
// array that we advance during our walk, rather than resorting to
// some associative container. See DwarfLinker::NextValidReloc.
std::sort(ValidRelocs.begin(), ValidRelocs.end());
return true;
}
/// \brief Look for relocations in the debug_info section that match
/// entries in the debug map. These relocations will drive the Dwarf
/// link by indicating which DIEs refer to symbols present in the
/// linked binary.
/// \returns wether there are any valid relocations in the debug info.
bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
const DebugMapObject &DMO) {
// Find the debug_info section.
for (const object::SectionRef &Section : Obj.sections()) {
StringRef SectionName;
Section.getName(SectionName);
SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
if (SectionName != "debug_info")
continue;
return findValidRelocs(Section, Obj, DMO);
}
return false;
}
bool DwarfLinker::link(const DebugMap &Map) {
if (Map.begin() == Map.end()) {
errs() << "Empty debug map.\n";
return false;
}
for (const auto &Obj : Map.objects()) {
CurrentDebugObject = Obj.get();
if (Verbose)
outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
if (std::error_code EC = ErrOrObj.getError()) {
reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
continue;
}
// Look for relocations that correspond to debug map entries.
if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
if (Verbose)
outs() << "No valid relocations found. Skipping.\n";
continue;
}
// Setup access to the debug info.
DWARFContextInMemory DwarfContext(*ErrOrObj);
startDebugObject(DwarfContext);
// In a first phase, just read in the debug info and store the DIE
// parent links that we will use during the next phase.
for (const auto &CU : DwarfContext.compile_units()) {
auto *CUDie = CU->getCompileUnitDIE(false);
if (Verbose) {
outs() << "Input compilation unit:";
CUDie->dump(outs(), CU.get(), 0);
}
Units.emplace_back(*CU);
gatherDIEParents(CUDie, 0, Units.back());
}
// Clean-up before starting working on the next object.
endDebugObject();
}
return true;
}
}
bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, bool Verbose) {
DwarfLinker Linker(OutputFilename, Verbose);
return Linker.link(DM);
}
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iomanip>
#include <iostream>
#include <prjxray/xilinx/xc7series/frame_address.h>
namespace xc7series = prjxray::xilinx::xc7series;
void frame_address_decode(std::istream * input_stream) {
for (uint32_t frame_address_raw;
(*input_stream) >> std::setbase(0) >> frame_address_raw;) {
xc7series::FrameAddress frame_address(frame_address_raw);
std::cout << "[" << std::hex << std::showbase << std::setw(10)
<< frame_address_raw << "] "
<< (frame_address.is_bottom_half_rows() ? "BOTTOM"
: "TOP")
<< " Row=" << std::setw(2) << std::dec
<< static_cast<unsigned int>(frame_address.row())
<< " Column=" << std::setw(2) << std::dec
<< frame_address.column() << " Minor=" << std::setw(2)
<< std::dec
<< static_cast<unsigned int>(frame_address.minor())
<< " Type=" << frame_address.block_type()
<< std::endl;
}
}
int main(int argc, char* argv[]) {
if (argc > 1) {
std::ifstream file_stream(argv[1]);
if (file_stream) {
frame_address_decode(&file_stream);
return 0;
}
}
frame_address_decode(&std::cin);
return 0;
}
<commit_msg>Run make format.<commit_after>#include <fstream>
#include <iomanip>
#include <iostream>
#include <prjxray/xilinx/xc7series/frame_address.h>
namespace xc7series = prjxray::xilinx::xc7series;
void frame_address_decode(std::istream* input_stream) {
for (uint32_t frame_address_raw;
(*input_stream) >> std::setbase(0) >> frame_address_raw;) {
xc7series::FrameAddress frame_address(frame_address_raw);
std::cout << "[" << std::hex << std::showbase << std::setw(10)
<< frame_address_raw << "] "
<< (frame_address.is_bottom_half_rows() ? "BOTTOM"
: "TOP")
<< " Row=" << std::setw(2) << std::dec
<< static_cast<unsigned int>(frame_address.row())
<< " Column=" << std::setw(2) << std::dec
<< frame_address.column() << " Minor=" << std::setw(2)
<< std::dec
<< static_cast<unsigned int>(frame_address.minor())
<< " Type=" << frame_address.block_type()
<< std::endl;
}
}
int main(int argc, char* argv[]) {
if (argc > 1) {
std::ifstream file_stream(argv[1]);
if (file_stream) {
frame_address_decode(&file_stream);
return 0;
}
}
frame_address_decode(&std::cin);
return 0;
}
<|endoftext|> |
<commit_before>/*
contact: Boris.Polishchuk@cern.ch
link: see comments in the $ALICE_ROOT/PHOS/AliPHOSRcuDA1.cxx
reference run: /castor/cern.ch/alice/phos/2007/10/04/18/07000008249001.1000.root
run type: STANDALONE
DA type: MON
number of events needed: 1000
input files: RCU0.data RCU1.data RCU2.data RCU3.data
Output files: PHOS_Module2_LED.root
Trigger types used: CALIBRATION_EVENT
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include <TSystem.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSRcuDA1.h"
#include "AliPHOSRawFitterv0.h"
#include "AliCaloAltroMapping.h"
#include "AliCaloRawStreamV3.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* Retrieve mapping files from DAQ DB */
const char* mapFiles[4] = {"RCU0.data","RCU1.data","RCU2.data","RCU3.data"};
for(Int_t iFile=0; iFile<4; iFile++) {
int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);
if(failed) {
printf("Cannot retrieve file %s from DAQ DB. Exit.\n",mapFiles[iFile]);
return -1;
}
}
/* Open mapping files */
AliAltroMapping *mapping[4];
TString path = "./";
path += "RCU";
TString path2;
for(Int_t i = 0; i < 4; i++) {
path2 = path;
path2 += i;
path2 += ".data";
mapping[i] = new AliCaloAltroMapping(path2.Data());
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliRawReader *rawReader = NULL;
AliPHOSRcuDA1* dAs[5];
for(Int_t iMod=0; iMod<5; iMod++) {
dAs[iMod] = 0;
}
Float_t e[64][56][2];
Float_t t[64][56][2];
Int_t cellX = -1;
Int_t cellZ = -1;
Int_t nBunches = 0;
Int_t nFired = -1;
Int_t sigStart, sigLength;
Int_t caloFlag;
TH1I fFiredCells("fFiredCells","Number of fired cells per event",100,0,1000);
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
nFired = 0;
rawReader = new AliRawReaderDate((void*)event);
AliCaloRawStreamV3 stream(rawReader,"PHOS",mapping);
AliPHOSRawFitterv0 fitter;
fitter.SubtractPedestals(kTRUE); // assume that data is non-ZS
while (stream.NextDDL()) {
while (stream.NextChannel()) {
cellX = stream.GetCellX();
cellZ = stream.GetCellZ();
caloFlag = stream.GetCaloFlag(); // 0=LG, 1=HG, 2=TRU
// In case of oscillating signals with ZS, a channel can have several bunches
nBunches = 0;
while (stream.NextBunch()) {
nBunches++;
if (nBunches > 1) continue;
sigStart = stream.GetStartTimeBin();
sigLength = stream.GetBunchLength();
fitter.SetSamples(stream.GetSignals(),sigStart,sigLength);
} // End of NextBunch()
fitter.SetNBunches(nBunches);
fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag);
fitter.Eval();
if(nBunches>1) continue;
// if (nBunches>1 || caloFlag!=0 || caloFlag!=1 || fitter.GetSignalQuality()>1) continue;
e[cellX][cellZ][caloFlag] = fitter.GetEnergy();
t[cellX][cellZ][caloFlag] = fitter.GetTime();
if(caloFlag==1 && fitter.GetEnergy()>40)
nFired++;
}
if(dAs[stream.GetModule()])
dAs[stream.GetModule()]->FillHistograms(e,t);
else
dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0);
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
for(Int_t iGain=0; iGain<2; iGain++) {
e[iX][iZ][iGain] = 0.;
t[iX][iZ][iGain] = 0.;
}
}
}
}
fFiredCells.Fill(nFired);
delete rawReader;
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
for(Int_t i = 0; i < 4; i++) delete mapping[i];
/* Be sure that all histograms are saved */
const TH2F* h2=0;
const TH1F* h1=0;
char localfile[128];
Int_t nGood=0; // >10 entries in peak
Int_t nMax=-111; // max. number of entries in peak
Int_t iXmax=-1;
Int_t iZmax=-1;
Int_t iModMax=-1;
for(Int_t iMod=0; iMod<5; iMod++) {
if(!dAs[iMod]) continue;
printf("DA1 for module %d detected.\n",iMod);
sprintf(localfile,"PHOS_Module%d_LED.root",iMod);
TFile* f = new TFile(localfile,"recreate");
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
h1 = dAs[iMod]->GetHgLgRatioHistogram(iX,iZ); // High Gain/Low Gain ratio
if(h1) {
if(h1->GetMaximum()>10.) nGood++;
if(h1->GetMaximum()>nMax) {
nMax = (Int_t)h1->GetMaximum(); iXmax=iX; iZmax=iZ; iModMax=iMod;
}
h1->Write();
}
for(Int_t iGain=0; iGain<2; iGain++) {
h2 = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); // Time vs Energy
if(h2) h2->Write();
}
}
}
fFiredCells.Write();
f->Close();
/* Store output files to the File Exchange Server */
daqDA_FES_storeFile(localfile,"LED");
}
printf("%d physics events of %d total processed.\n",nevents_physics,nevents_total);
printf("%d histograms has >10 entries in maximum, max. is %d entries ",nGood,nMax);
printf("(module,iX,iZ)=(%d,%d,%d)",iModMax,iXmax,iZmax);
printf("\n");
return status;
}
<commit_msg>ZS parameters taking from the file in the DA working directory.<commit_after>/*
contact: Boris.Polishchuk@cern.ch
link: see comments in the $ALICE_ROOT/PHOS/AliPHOSRcuDA1.cxx
reference run: /castor/cern.ch/alice/phos/2007/10/04/18/07000008249001.1000.root
run type: STANDALONE
DA type: MON
number of events needed: 1000
input files: RCU0.data RCU1.data RCU2.data RCU3.data
Output files: PHOS_Module2_LED.root
Trigger types used: CALIBRATION_EVENT
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include <TSystem.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSRcuDA1.h"
#include "AliPHOSRawFitterv0.h"
#include "AliCaloAltroMapping.h"
#include "AliCaloRawStreamV3.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* Retrieve ZS parameters from DAQ DB */
const char* zsfile = "zs.txt";
int failZS = daqDA_DB_getFile(zsfile, zsfile);
Int_t offset,threshold;
if(!failZS) {
FILE *f = fopen(zsfile,"r");
int scan = fscanf(f,"%d %d",&offset,&threshold);
}
/* Retrieve mapping files from DAQ DB */
const char* mapFiles[4] = {"RCU0.data","RCU1.data","RCU2.data","RCU3.data"};
for(Int_t iFile=0; iFile<4; iFile++) {
int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);
if(failed) {
printf("Cannot retrieve file %s from DAQ DB. Exit.\n",mapFiles[iFile]);
return -1;
}
}
/* Open mapping files */
AliAltroMapping *mapping[4];
TString path = "./";
path += "RCU";
TString path2;
for(Int_t i = 0; i < 4; i++) {
path2 = path;
path2 += i;
path2 += ".data";
mapping[i] = new AliCaloAltroMapping(path2.Data());
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliRawReader *rawReader = NULL;
AliPHOSRcuDA1* dAs[5];
for(Int_t iMod=0; iMod<5; iMod++) {
dAs[iMod] = 0;
}
Float_t e[64][56][2];
Float_t t[64][56][2];
Int_t cellX = -1;
Int_t cellZ = -1;
Int_t nBunches = 0;
Int_t nFired = -1;
Int_t sigStart, sigLength;
Int_t caloFlag;
TH1I fFiredCells("fFiredCells","Number of fired cells per event",100,0,1000);
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
nFired = 0;
rawReader = new AliRawReaderDate((void*)event);
AliCaloRawStreamV3 stream(rawReader,"PHOS",mapping);
AliPHOSRawFitterv0 fitter;
fitter.SubtractPedestals(kTRUE); // assume that data is non-ZS
if(!failZS) {
fitter.SubtractPedestals(kFALSE);
fitter.SetAmpOffset(offset);
fitter.SetAmpThreshold(threshold);
}
while (stream.NextDDL()) {
while (stream.NextChannel()) {
cellX = stream.GetCellX();
cellZ = stream.GetCellZ();
caloFlag = stream.GetCaloFlag(); // 0=LG, 1=HG, 2=TRU
// In case of oscillating signals with ZS, a channel can have several bunches
nBunches = 0;
while (stream.NextBunch()) {
nBunches++;
if (nBunches > 1) continue;
sigStart = stream.GetStartTimeBin();
sigLength = stream.GetBunchLength();
fitter.SetSamples(stream.GetSignals(),sigStart,sigLength);
} // End of NextBunch()
fitter.SetNBunches(nBunches);
fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag);
fitter.Eval();
if(nBunches>1) continue;
// if (nBunches>1 || caloFlag!=0 || caloFlag!=1 || fitter.GetSignalQuality()>1) continue;
e[cellX][cellZ][caloFlag] = fitter.GetEnergy();
t[cellX][cellZ][caloFlag] = fitter.GetTime();
if(caloFlag==1 && fitter.GetEnergy()>40)
nFired++;
}
if(dAs[stream.GetModule()])
dAs[stream.GetModule()]->FillHistograms(e,t);
else
dAs[stream.GetModule()] = new AliPHOSRcuDA1(stream.GetModule(),-1,0);
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
for(Int_t iGain=0; iGain<2; iGain++) {
e[iX][iZ][iGain] = 0.;
t[iX][iZ][iGain] = 0.;
}
}
}
}
fFiredCells.Fill(nFired);
delete rawReader;
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
for(Int_t i = 0; i < 4; i++) delete mapping[i];
/* Be sure that all histograms are saved */
const TH2F* h2=0;
const TH1F* h1=0;
char localfile[128];
Int_t nGood=0; // >10 entries in peak
Int_t nMax=-111; // max. number of entries in peak
Int_t iXmax=-1;
Int_t iZmax=-1;
Int_t iModMax=-1;
for(Int_t iMod=0; iMod<5; iMod++) {
if(!dAs[iMod]) continue;
printf("DA1 for module %d detected.\n",iMod);
sprintf(localfile,"PHOS_Module%d_LED.root",iMod);
TFile* f = new TFile(localfile,"recreate");
for(Int_t iX=0; iX<64; iX++) {
for(Int_t iZ=0; iZ<56; iZ++) {
h1 = dAs[iMod]->GetHgLgRatioHistogram(iX,iZ); // High Gain/Low Gain ratio
if(h1) {
if(h1->GetMaximum()>10.) nGood++;
if(h1->GetMaximum()>nMax) {
nMax = (Int_t)h1->GetMaximum(); iXmax=iX; iZmax=iZ; iModMax=iMod;
}
h1->Write();
}
for(Int_t iGain=0; iGain<2; iGain++) {
h2 = dAs[iMod]->GetTimeEnergyHistogram(iX,iZ,iGain); // Time vs Energy
if(h2) h2->Write();
}
}
}
fFiredCells.Write();
f->Close();
/* Store output files to the File Exchange Server */
daqDA_FES_storeFile(localfile,"LED");
}
printf("%d physics events of %d total processed.\n",nevents_physics,nevents_total);
printf("%d histograms has >10 entries in maximum, max. is %d entries ",nGood,nMax);
printf("(module,iX,iZ)=(%d,%d,%d)",iModMax,iXmax,iZmax);
printf("\n");
return status;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Laura Schlimmer <laura@eventql.io>
* - Christian Parpart <christianparpart@gmail.com>
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "time.h"
#include "stringutil.h"
UnixTime WallClock::now() {
return UnixTime(WallClock::getUnixMicros());
}
uint64_t WallClock::unixSeconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
uint64_t WallClock::getUnixMillis() {
return unixMillis();
}
uint64_t WallClock::unixMillis() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}
uint64_t WallClock::getUnixMicros() {
return unixMicros();
}
uint64_t WallClock::unixMicros() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000llu + tv.tv_usec;
}
uint64_t MonotonicClock::now() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
logFatal("clock_gettime(CLOCK_MONOTONIC) failed");
abort();
} else {
return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
}
UnixTime::UnixTime() :
utc_micros_(WallClock::unixMicros()) {}
UnixTime& UnixTime::operator=(const UnixTime& other) {
utc_micros_ = other.utc_micros_;
return *this;
}
UnixTime UnixTime::now() {
return UnixTime(WallClock::unixMicros());
}
UnixTime UnixTime::daysFromNow(double days) {
return UnixTime(WallClock::unixMicros() + (days * kMicrosPerDay));
}
std::string UnixTime::toString(const char* fmt) const {
struct tm tm;
time_t tt = utc_micros_ / 1000000;
gmtime_r(&tt, &tm); // FIXPAUL
char buf[256]; // FIXPAUL
buf[0] = 0;
strftime(buf, sizeof(buf), fmt, &tm);
return std::string(buf);
}
template <>
std::string StringUtil::toString(UnixTime value) {
return value.toString();
}
UnixTime std::numeric_limits<UnixTime>::min() {
return UnixTime::epoch();
}
UnixTime std::numeric_limits<UnixTime>::max() {
return UnixTime(std::numeric_limits<uint64_t>::max());
}
<commit_msg>fix linux build<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Laura Schlimmer <laura@eventql.io>
* - Christian Parpart <christianparpart@gmail.com>
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "time.h"
#include "stringutil.h"
#include "logging.h"
UnixTime WallClock::now() {
return UnixTime(WallClock::getUnixMicros());
}
uint64_t WallClock::unixSeconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
uint64_t WallClock::getUnixMillis() {
return unixMillis();
}
uint64_t WallClock::unixMillis() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}
uint64_t WallClock::getUnixMicros() {
return unixMicros();
}
uint64_t WallClock::unixMicros() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000llu + tv.tv_usec;
}
uint64_t MonotonicClock::now() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
logFatal("clock_gettime(CLOCK_MONOTONIC) failed");
abort();
} else {
return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
}
UnixTime::UnixTime() :
utc_micros_(WallClock::unixMicros()) {}
UnixTime& UnixTime::operator=(const UnixTime& other) {
utc_micros_ = other.utc_micros_;
return *this;
}
UnixTime UnixTime::now() {
return UnixTime(WallClock::unixMicros());
}
UnixTime UnixTime::daysFromNow(double days) {
return UnixTime(WallClock::unixMicros() + (days * kMicrosPerDay));
}
std::string UnixTime::toString(const char* fmt) const {
struct tm tm;
time_t tt = utc_micros_ / 1000000;
gmtime_r(&tt, &tm); // FIXPAUL
char buf[256]; // FIXPAUL
buf[0] = 0;
strftime(buf, sizeof(buf), fmt, &tm);
return std::string(buf);
}
template <>
std::string StringUtil::toString(UnixTime value) {
return value.toString();
}
UnixTime std::numeric_limits<UnixTime>::min() {
return UnixTime::epoch();
}
UnixTime std::numeric_limits<UnixTime>::max() {
return UnixTime(std::numeric_limits<uint64_t>::max());
}
<|endoftext|> |
<commit_before>/**
* @file Singleton.hpp
* @brief Singleton class prototype.
* @author zer0
* @date 2016-04-04
*
* @remarks
* Singleton with double-checked locking pattern.
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/pattern/Observer.hpp>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <type_traits>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace pattern {
#ifndef SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN(__result_type, __atomic_instance, __mutex, __temp) \
__result_type * __temp = __atomic_instance.load(); \
if (__temp == nullptr) { \
std::lock_guard<std::mutex> guard(__mutex); \
__temp = __atomic_instance.load(); \
if (__temp == nullptr) { \
__temp = new (std::nothrow) __result_type(); \
__atomic_instance.store(__temp);
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_CLOSE(__temp) \
} \
} \
return __temp;
#define __SINGLETON_IMPL_OPEN(__r, __i, __m, __t) \
SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN(__r, __i, __m, __t)
#define __SINGLETON_IMPL_CLOSE(__t) \
SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_CLOSE(__t)
#endif // SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN
/**
* Don't use @c std::atexit function.
*
* @remarks
* Default variable is false.
*/
constexpr bool isManualRelease() noexcept
{
return false;
}
/**
* Singleton property template class.
*
* @author zer0
* @date 2016-04-22
*/
template <typename T>
struct SingletonProperty
{
public:
using BaseType = T;
protected:
static std::atomic<BaseType*> _instance;
static std::mutex _instance_lock;
};
template <typename T>
std::atomic<T*> SingletonProperty<T>::_instance{nullptr};
template <typename T>
std::mutex SingletonProperty<T>::_instance_lock;
/**
* SingletonLifeManager class prototype.
*
* @author zer0
* @date 2016-04-11
*
* @remarks
* Management of Singleton classes.
*/
class SingletonLifeManager
: public SingletonProperty<SingletonLifeManager>
, public Noncopyable
{
public:
using Observable = UnorderedObservable;
using Property = SingletonProperty<SingletonLifeManager>;
private:
Observable _observable;
protected:
SingletonLifeManager() {
__EMPTY_BLOCK__
}
public:
~SingletonLifeManager() {
this->_observable.notify();
}
public:
void add(std::function<void(void)> const & observer) {
this->_observable.add(observer);
}
public:
static void releaseInstance() {
SingletonLifeManager * temp = Property::_instance.load();
if (temp != nullptr) {
std::lock_guard<std::mutex> guard(Property::_instance_lock);
temp = Property::_instance.load();
if (temp != nullptr) {
delete temp; // Release, all singleton objects.
Property::_instance.store(nullptr);
}
}
}
public:
static SingletonLifeManager * getInstance() {
// @formatter:off
__SINGLETON_IMPL_OPEN(SingletonLifeManager, Property::_instance, Property::_instance_lock, temp);
{
if (!isManualRelease()) {
// Register release method.
std::atexit(&SingletonLifeManager::releaseInstance);
}
}
__SINGLETON_IMPL_CLOSE(temp);
// @formatter:on
}
};
/**
* Singleton template class.
*
* @author zer0
* @date 2016-04-22
*/
template <typename T>
class Singleton : public SingletonProperty<T>, public Noncopyable
{
public:
using BaseType = T;
using Property = SingletonProperty<BaseType>;
static_assert(std::is_same<BaseType, typename Property::BaseType>::value
, "Property::BaseType must be the same type as BaseType");
protected:
Singleton() {
__EMPTY_BLOCK__
}
virtual ~Singleton() {
__EMPTY_BLOCK__
}
private:
static void releaseInstance() {
BaseType * temp = Property::_instance.load();
if (temp != nullptr) {
std::lock_guard<std::mutex> guard(Property::_instance_lock);
temp = Property::_instance.load();
if (temp != nullptr) {
delete temp;
Property::_instance.store(nullptr);
}
}
}
public:
static BaseType * getInstance() {
// @formatter:off
__SINGLETON_IMPL_OPEN(BaseType, Property::_instance, Property::_instance_lock, temp);
{
using namespace libtbag::pattern;
SingletonLifeManager::getInstance()->add([](){
Singleton<BaseType>::releaseInstance();
});
}
__SINGLETON_IMPL_CLOSE(temp);
// @formatter:on
}
};
} // namespace pattern
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#ifndef SINGLETON_INHERITANCE
#define SINGLETON_INHERITANCE(class_name) \
public ::libtbag::pattern::Singleton<class_name>
#endif
#ifndef SINGLETON_RESTRICT
#define SINGLETON_RESTRICT(class_name) \
public: \
friend Singleton<class_name>; \
protected: \
class_name(){} \
public: \
virtual ~class_name(){} \
private: // default access modifier of class.
#endif
#ifndef SINGLETON_CLASS_OPEN
#define SINGLETON_CLASS_OPEN(class_name) \
class class_name : SINGLETON_INHERITANCE(class_name) \
{ \
public: \
SINGLETON_RESTRICT(class_name) \
private: // default access modifier of class.
#endif
#endif // __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
<commit_msg>Fix the SINGLETON_RESTRICT macro bug.<commit_after>/**
* @file Singleton.hpp
* @brief Singleton class prototype.
* @author zer0
* @date 2016-04-04
*
* @remarks
* Singleton with double-checked locking pattern.
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/pattern/Observer.hpp>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <type_traits>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace pattern {
#ifndef SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN(__result_type, __atomic_instance, __mutex, __temp) \
__result_type * __temp = __atomic_instance.load(); \
if (__temp == nullptr) { \
std::lock_guard<std::mutex> guard(__mutex); \
__temp = __atomic_instance.load(); \
if (__temp == nullptr) { \
__temp = new (std::nothrow) __result_type(); \
__atomic_instance.store(__temp);
#define SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_CLOSE(__temp) \
} \
} \
return __temp;
#define __SINGLETON_IMPL_OPEN(__r, __i, __m, __t) \
SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN(__r, __i, __m, __t)
#define __SINGLETON_IMPL_CLOSE(__t) \
SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_CLOSE(__t)
#endif // SINGLETON_WITH_DOUBLE_CHECKED_LOCKING_PATTERN_OPEN
/**
* Don't use @c std::atexit function.
*
* @remarks
* Default variable is false.
*/
constexpr bool isManualRelease() noexcept
{
return false;
}
/**
* Singleton property template class.
*
* @author zer0
* @date 2016-04-22
*/
template <typename T>
struct SingletonProperty
{
public:
using BaseType = T;
protected:
static std::atomic<BaseType*> _instance;
static std::mutex _instance_lock;
};
template <typename T>
std::atomic<T*> SingletonProperty<T>::_instance{nullptr};
template <typename T>
std::mutex SingletonProperty<T>::_instance_lock;
/**
* SingletonLifeManager class prototype.
*
* @author zer0
* @date 2016-04-11
*
* @remarks
* Management of Singleton classes.
*/
class SingletonLifeManager
: public SingletonProperty<SingletonLifeManager>
, public Noncopyable
{
public:
using Observable = UnorderedObservable;
using Property = SingletonProperty<SingletonLifeManager>;
private:
Observable _observable;
protected:
SingletonLifeManager() {
__EMPTY_BLOCK__
}
public:
~SingletonLifeManager() {
this->_observable.notify();
}
public:
void add(std::function<void(void)> const & observer) {
this->_observable.add(observer);
}
public:
static void releaseInstance() {
SingletonLifeManager * temp = Property::_instance.load();
if (temp != nullptr) {
std::lock_guard<std::mutex> guard(Property::_instance_lock);
temp = Property::_instance.load();
if (temp != nullptr) {
delete temp; // Release, all singleton objects.
Property::_instance.store(nullptr);
}
}
}
public:
static SingletonLifeManager * getInstance() {
// @formatter:off
__SINGLETON_IMPL_OPEN(SingletonLifeManager, Property::_instance, Property::_instance_lock, temp);
{
if (!isManualRelease()) {
// Register release method.
std::atexit(&SingletonLifeManager::releaseInstance);
}
}
__SINGLETON_IMPL_CLOSE(temp);
// @formatter:on
}
};
/**
* Singleton template class.
*
* @author zer0
* @date 2016-04-22
*/
template <typename T>
class Singleton : public SingletonProperty<T>, public Noncopyable
{
public:
using BaseType = T;
using Property = SingletonProperty<BaseType>;
static_assert(std::is_same<BaseType, typename Property::BaseType>::value
, "Property::BaseType must be the same type as BaseType");
protected:
Singleton() {
__EMPTY_BLOCK__
}
virtual ~Singleton() {
__EMPTY_BLOCK__
}
private:
static void releaseInstance() {
BaseType * temp = Property::_instance.load();
if (temp != nullptr) {
std::lock_guard<std::mutex> guard(Property::_instance_lock);
temp = Property::_instance.load();
if (temp != nullptr) {
delete temp;
Property::_instance.store(nullptr);
}
}
}
public:
static BaseType * getInstance() {
// @formatter:off
__SINGLETON_IMPL_OPEN(BaseType, Property::_instance, Property::_instance_lock, temp);
{
using namespace libtbag::pattern;
SingletonLifeManager::getInstance()->add([](){
Singleton<BaseType>::releaseInstance();
});
}
__SINGLETON_IMPL_CLOSE(temp);
// @formatter:on
}
};
} // namespace pattern
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#ifndef SINGLETON_INHERITANCE
#define SINGLETON_INHERITANCE(class_name) \
public ::libtbag::pattern::Singleton<class_name>
#endif
#ifndef SINGLETON_RESTRICT
#define SINGLETON_RESTRICT(class_name) \
public: \
friend libtbag::pattern::Singleton<class_name>; \
protected: \
class_name(){} \
public: \
virtual ~class_name(){} \
private: // default access modifier of class.
#endif
#endif // __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
<|endoftext|> |
<commit_before>/** @file
*
* @ingroup dspLibrary
*
* @brief Container object that holds some audio in a chunk of memory.
*
* @see TTMatrix, TTAudioSignal
*
* @authors Timothy Place & Nathan Wolek
*
* @copyright Copyright © 2003-2012, Timothy Place & Nathan Wolek @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSampleMatrix.h"
#define thisTTClass TTSampleMatrix
#define thisTTClassName "samplematrix"
#define thisTTClassTags "audio, buffer"
TTObjectPtr TTSampleMatrix::instantiate(TTSymbol& name, TTValue& arguments)
{
return new TTSampleMatrix(arguments);
}
extern "C" void TTSampleMatrix::registerClass()
{
TTClassRegister(thisTTClassName, thisTTClassTags, TTSampleMatrix::instantiate);
}
TTSampleMatrix::TTSampleMatrix(TTValue& arguments) :
TTMatrix(arguments),
mSampleRate(44100.0)
{
this->setTypeWithoutResize(kTypeFloat64);
this->setElementCountWithoutResize(1);
this->resize();
addAttributeWithGetterAndSetter(NumChannels, kTypeInt32);
addAttributeWithGetterAndSetter(Length, kTypeFloat64);
addAttributeWithGetterAndSetter(LengthInSamples, kTypeInt32);
addAttribute(SampleRate, kTypeFloat64);
addMessage(normalize);
addMessageWithArguments(fill);
addMessageWithArguments(getValueAtIndex);
registerMessage("peek", (TTMethod)&TTSampleMatrix::getValueAtIndex);
registerMessage("peeki", (TTMethod)&TTSampleMatrix::getValueAtIndex);
addMessageWithArguments(setValueAtIndex);
registerMessage("poke", (TTMethod)&TTSampleMatrix::setValueAtIndex);
// TODO: more messages to implement
// "readFile" (requires libsndfile straightening-out)
// "writeFile" (requires libsndfile straightening-out)
// a way to query attributes: for example what is the sr and bpm of an AIFF file?
}
TTSampleMatrix::~TTSampleMatrix()
{
;
}
TTErr TTSampleMatrix::setNumChannels(const TTValue& newNumChannels)
{
return setColumnCount(newNumChannels);
}
TTErr TTSampleMatrix::getNumChannels(TTValue& returnedChannelCount)
{
returnedChannelCount = mNumChannels;
return kTTErrNone;
}
TTErr TTSampleMatrix::setLength(const TTValue& newLength)
{
TTValue newLengthInSamples = TTFloat64(newLength) * mSampleRate * 0.001;
return setRowCount(newLengthInSamples);
}
TTErr TTSampleMatrix::getLength(TTValue& returnedLength)
{
returnedLength = (mLengthInSamples / mSampleRate) * 1000.0;
return kTTErrNone;
}
TTErr TTSampleMatrix::setLengthInSamples(const TTValue& newLengthInSamples)
{
return setRowCount(newLengthInSamples);
}
TTErr TTSampleMatrix::getLengthInSamples(TTValue& returnedLengthInSamples)
{
returnedLengthInSamples = mLengthInSamples;
return kTTErrNone;
}
TTErr TTSampleMatrix::getValueAtIndex(const TTValue& index, TTValue &output)
{
TTUInt32 sampleIndex;
TTUInt16 sampleChannel = 0;
TTSampleValue sampleValue;
TTUInt8 i = 0;
TTErr err;
index.get(i++, sampleIndex);
if (index.getSize() > 2) // TODO: sure would be nice to change the name of this method to "size" or something...
index.get(i++, sampleChannel);
err = peek(sampleIndex, sampleChannel, sampleValue);
if (!err)
output.set(i++, sampleValue);
return err;
}
TTErr TTSampleMatrix::peek(const TTUInt64 index, const TTUInt16 channel, TTSampleValue& value)
{
TTRowID p_index = index;
TTColumnID p_channel = channel;
//makeInBounds(p_index, p_channel);
get2d(p_index, p_channel, value);
return kTTErrNone;
}
// a first attempt at interpolation for the SampleMatrix. should be viewed as temporary.
// needs to be fleshed out with different options...
TTErr TTSampleMatrix::peeki(const TTFloat64 index, const TTUInt16 channel, TTSampleValue& value)
{
// variables needed
TTUInt64 indexThisInteger = TTUInt64(index);
TTUInt64 indexNextInteger = indexThisInteger + 1;
TTFloat64 indexFractionalPart = index - indexThisInteger;
TTSampleValue valueThisInteger, valueNextInteger;
// TODO: perhaps we should range check the input here first...
get2d(indexThisInteger, channel, valueThisInteger);
get2d(indexNextInteger, channel, valueNextInteger);
// simple linear interpolation adapted from TTDelay
value = (valueNextInteger * (1.0 - indexFractionalPart)) + (valueThisInteger * indexFractionalPart);
return kTTErrNone;
}
/** Set the sample value for a given index.
The first number passed in the index parameter will be interpreted as the sample index.
If there are three numbers passed, then the second number, if passed, will designate the channel index (defaults to zero).
The final value will be used as the sample value that will be copied to the designated index.
*/
TTErr TTSampleMatrix::setValueAtIndex(const TTValue& index, TTValue& unusedOutput)
{
TTUInt32 sampleIndex;
TTUInt16 sampleChannel = 0;
TTSampleValue sampleValue;
TTUInt8 i = 0;
index.get(i++, sampleIndex);
if (index.getSize() > 2)
index.get(i++, sampleChannel);
index.get(i++, sampleValue);
return poke(sampleIndex, sampleChannel, sampleValue);
}
TTErr TTSampleMatrix::poke(const TTUInt64 index, const TTUInt16 channel, const TTSampleValue value)
{
// TODO: perhaps we should range check the input here first...
set2d(index, channel, value);
return kTTErrNone;
}
TTErr TTSampleMatrix::fill(const TTValue& value, TTValue& unusedOutput)
{
TTSymbol fillAlgorithm = value;
if (fillAlgorithm == kTTSym_sine) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))));
}
}
else if (fillAlgorithm == kTTSym_sineMod) { // (modulator version: ranges from 0.0 to 1.0, rather than -1.0 to 1.0)
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, 0.5 + (0.5 * sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))));
}
}
else if (fillAlgorithm == kTTSym_cosine) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))));
}
}
else if (fillAlgorithm == kTTSym_cosineMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, 0.5 + (0.5 * cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))));
}
}
else if (fillAlgorithm == kTTSym_ramp) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples)));
}
}
else if (fillAlgorithm == kTTSym_rampMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, float(i) / mLengthInSamples);
}
}
else if (fillAlgorithm == kTTSym_sawtooth) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(mLengthInSamples-i, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples)));
}
}
else if (fillAlgorithm == kTTSym_sawtoothMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(mLengthInSamples-i, channel+1, float(i) / mLengthInSamples);
}
}
else if (fillAlgorithm == kTTSym_triangle) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt32 i=0; i < mLengthInSamples/2; i++) {
set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
}
}
}
else if (fillAlgorithm == kTTSym_triangleMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt32 i=0; i < mLengthInSamples/2; i++) {
set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
}
}
}
return kTTErrNone;
}
TTErr TTSampleMatrix::normalize(const TTValue& aValue)
{
TTFloat64 normalizeTo = 1.0;
TTRowID m = mLengthInSamples; // mFrameLength
TTColumnID n = mNumChannels; // mNumChannels
TTSampleValuePtr samples = (TTSampleValuePtr)getLockedPointer();
TTFloat64 peakValue = 0.0;
TTFloat64 scalar;
if (aValue.getSize() && TTFloat64(aValue) > 0.0)
normalizeTo = aValue;
for (int k=0; k<m*n; k++) {
TTFloat64 magnitude = abs(samples[k]);
if (magnitude > peakValue)
peakValue = magnitude;
}
scalar = normalizeTo / peakValue;
for (int k=0; k<m*n; k++)
samples[k] *= scalar;
releaseLockedPointer();
return kTTErrNone;
}
<commit_msg>SampleMatrix:peek, peeki & poke methods now use range checking<commit_after>/** @file
*
* @ingroup dspLibrary
*
* @brief Container object that holds some audio in a chunk of memory.
*
* @see TTMatrix, TTAudioSignal
*
* @authors Timothy Place & Nathan Wolek
*
* @copyright Copyright © 2003-2012, Timothy Place & Nathan Wolek @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSampleMatrix.h"
#define thisTTClass TTSampleMatrix
#define thisTTClassName "samplematrix"
#define thisTTClassTags "audio, buffer"
TTObjectPtr TTSampleMatrix::instantiate(TTSymbol& name, TTValue& arguments)
{
return new TTSampleMatrix(arguments);
}
extern "C" void TTSampleMatrix::registerClass()
{
TTClassRegister(thisTTClassName, thisTTClassTags, TTSampleMatrix::instantiate);
}
TTSampleMatrix::TTSampleMatrix(TTValue& arguments) :
TTMatrix(arguments),
mSampleRate(44100.0)
{
this->setTypeWithoutResize(kTypeFloat64);
this->setElementCountWithoutResize(1);
this->resize();
addAttributeWithGetterAndSetter(NumChannels, kTypeInt32);
addAttributeWithGetterAndSetter(Length, kTypeFloat64);
addAttributeWithGetterAndSetter(LengthInSamples, kTypeInt32);
addAttribute(SampleRate, kTypeFloat64);
addMessage(normalize);
addMessageWithArguments(fill);
addMessageWithArguments(getValueAtIndex);
registerMessage("peek", (TTMethod)&TTSampleMatrix::getValueAtIndex);
registerMessage("peeki", (TTMethod)&TTSampleMatrix::getValueAtIndex);
addMessageWithArguments(setValueAtIndex);
registerMessage("poke", (TTMethod)&TTSampleMatrix::setValueAtIndex);
// TODO: more messages to implement
// "readFile" (requires libsndfile straightening-out)
// "writeFile" (requires libsndfile straightening-out)
// a way to query attributes: for example what is the sr and bpm of an AIFF file?
}
TTSampleMatrix::~TTSampleMatrix()
{
;
}
TTErr TTSampleMatrix::setNumChannels(const TTValue& newNumChannels)
{
return setColumnCount(newNumChannels);
}
TTErr TTSampleMatrix::getNumChannels(TTValue& returnedChannelCount)
{
returnedChannelCount = mNumChannels;
return kTTErrNone;
}
TTErr TTSampleMatrix::setLength(const TTValue& newLength)
{
TTValue newLengthInSamples = TTFloat64(newLength) * mSampleRate * 0.001;
return setRowCount(newLengthInSamples);
}
TTErr TTSampleMatrix::getLength(TTValue& returnedLength)
{
returnedLength = (mLengthInSamples / mSampleRate) * 1000.0;
return kTTErrNone;
}
TTErr TTSampleMatrix::setLengthInSamples(const TTValue& newLengthInSamples)
{
return setRowCount(newLengthInSamples);
}
TTErr TTSampleMatrix::getLengthInSamples(TTValue& returnedLengthInSamples)
{
returnedLengthInSamples = mLengthInSamples;
return kTTErrNone;
}
TTErr TTSampleMatrix::getValueAtIndex(const TTValue& index, TTValue &output)
{
TTUInt32 sampleIndex;
TTUInt16 sampleChannel = 0;
TTSampleValue sampleValue;
TTUInt8 i = 0;
TTErr err;
index.get(i++, sampleIndex);
if (index.getSize() > 2) // TODO: sure would be nice to change the name of this method to "size" or something...
index.get(i++, sampleChannel);
err = peek(sampleIndex, sampleChannel, sampleValue);
if (!err)
output.set(i++, sampleValue);
return err;
}
TTErr TTSampleMatrix::peek(const TTUInt64 index, const TTUInt16 channel, TTSampleValue& value)
{
TTRowID p_index = index;
TTColumnID p_channel = channel;
makeInBounds(p_index, p_channel); // out of range values are clipped
get2d(p_index, p_channel, value);
return kTTErrNone;
}
// a first attempt at interpolation for the SampleMatrix. should be viewed as temporary.
// needs to be fleshed out with different options...
TTErr TTSampleMatrix::peeki(const TTFloat64 index, const TTUInt16 channel, TTSampleValue& value)
{
// variables needed
TTColumnID p_channel = channel;
TTRowID indexThisInteger = TTRowID(index);
TTFloat64 indexFractionalPart = index - indexThisInteger; // before makeInBounds to get the right value!
makeInBounds(indexThisInteger, p_channel); // out of range values are clipped
TTRowID indexNextInteger = indexThisInteger + 1;
makeRowIDInBounds(indexNextInteger, outOfBoundsWrap); //if we went beyond the mRowCount, go back to 0th sample
TTSampleValue valueThisInteger, valueNextInteger;
get2d(indexThisInteger, p_channel, valueThisInteger);
get2d(indexNextInteger, p_channel, valueNextInteger);
// simple linear interpolation adapted from TTDelay
value = (valueNextInteger * (1.0 - indexFractionalPart)) + (valueThisInteger * indexFractionalPart);
return kTTErrNone;
}
/** Set the sample value for a given index.
The first number passed in the index parameter will be interpreted as the sample index.
If there are three numbers passed, then the second number, if passed, will designate the channel index (defaults to zero).
The final value will be used as the sample value that will be copied to the designated index.
*/
TTErr TTSampleMatrix::setValueAtIndex(const TTValue& index, TTValue& unusedOutput)
{
TTUInt32 sampleIndex;
TTUInt16 sampleChannel = 0;
TTSampleValue sampleValue;
TTUInt8 i = 0;
index.get(i++, sampleIndex);
if (index.getSize() > 2)
index.get(i++, sampleChannel);
index.get(i++, sampleValue);
return poke(sampleIndex, sampleChannel, sampleValue);
}
TTErr TTSampleMatrix::poke(const TTUInt64 index, const TTUInt16 channel, const TTSampleValue value)
{
TTRowID p_index = index;
TTColumnID p_channel = channel;
TTBoolean weAreNotInBounds = makeInBounds(p_index,p_channel);
if (weAreNotInBounds)
{
// don't go poking around out of bounds
return kTTErrInvalidValue;
} else {
set2d(p_index, p_channel, value);
return kTTErrNone;
}
}
TTErr TTSampleMatrix::fill(const TTValue& value, TTValue& unusedOutput)
{
TTSymbol fillAlgorithm = value;
if (fillAlgorithm == kTTSym_sine) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))));
}
}
else if (fillAlgorithm == kTTSym_sineMod) { // (modulator version: ranges from 0.0 to 1.0, rather than -1.0 to 1.0)
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, 0.5 + (0.5 * sin(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))));
}
}
else if (fillAlgorithm == kTTSym_cosine) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0))));
}
}
else if (fillAlgorithm == kTTSym_cosineMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, 0.5 + (0.5 * cos(kTTTwoPi * (i / (TTFloat64(mLengthInSamples) - 1.0)))));
}
}
else if (fillAlgorithm == kTTSym_ramp) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples)));
}
}
else if (fillAlgorithm == kTTSym_rampMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(i+1, channel+1, float(i) / mLengthInSamples);
}
}
else if (fillAlgorithm == kTTSym_sawtooth) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(mLengthInSamples-i, channel+1, -1.0 + (2.0 * (float(i) / mLengthInSamples)));
}
}
else if (fillAlgorithm == kTTSym_sawtoothMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt64 i=0; i<mLengthInSamples; i++)
set2d(mLengthInSamples-i, channel+1, float(i) / mLengthInSamples);
}
}
else if (fillAlgorithm == kTTSym_triangle) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt32 i=0; i < mLengthInSamples/2; i++) {
set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
}
}
}
else if (fillAlgorithm == kTTSym_triangleMod) {
for (TTUInt16 channel=0; channel<mNumChannels; channel++) {
for (TTUInt32 i=0; i < mLengthInSamples/2; i++) {
set2d(i+1, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
set2d(mLengthInSamples-i, channel+1, -1.0 + (4.0 * (float(i) / mLengthInSamples)));
}
}
}
return kTTErrNone;
}
TTErr TTSampleMatrix::normalize(const TTValue& aValue)
{
TTFloat64 normalizeTo = 1.0;
TTRowID m = mLengthInSamples; // mFrameLength
TTColumnID n = mNumChannels; // mNumChannels
TTSampleValuePtr samples = (TTSampleValuePtr)getLockedPointer();
TTFloat64 peakValue = 0.0;
TTFloat64 scalar;
if (aValue.getSize() && TTFloat64(aValue) > 0.0)
normalizeTo = aValue;
for (int k=0; k<m*n; k++) {
TTFloat64 magnitude = abs(samples[k]);
if (magnitude > peakValue)
peakValue = magnitude;
}
scalar = normalizeTo / peakValue;
for (int k=0; k<m*n; k++)
samples[k] *= scalar;
releaseLockedPointer();
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/**
* @file opencv_sanity.cpp
* @brief Sanity test for the OpenCV libraries
* @author Paolo D'Apice
*/
#define BOOST_TEST_MODULE sanity
#include <boost/test/unit_test.hpp>
#include "utils/matrix.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#define argc boost::unit_test::framework::master_test_suite().argc
#define argv boost::unit_test::framework::master_test_suite().argv
using namespace cv;
using namespace std;
BOOST_AUTO_TEST_CASE(lena) {
Mat image = imread(argv[1]);
BOOST_WARN_MESSAGE(!image.data, "No image data");
BOOST_CHECK_EQUAL(Size(512, 512), image.size());
BOOST_CHECK_EQUAL(512, image.rows);
BOOST_CHECK_EQUAL(512, image.cols);
BOOST_CHECK_EQUAL(2, image.dims);
BOOST_CHECK_EQUAL(3, image.channels());
if (argc > 2) {
imshow("Display image", image);
cout << "Press a key to continue" << endl;
waitKey(0);
}
}
#define print(X) cout << #X << ": " << X << endl;
BOOST_AUTO_TEST_CASE(opencv_traits) {
float data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Mat mat(3,3, CV_32F, data);
BOOST_CHECK(CV_32F == DataType<float>::type);
BOOST_CHECK(mat.depth() == DataType<float>::type);
}
BOOST_AUTO_TEST_CASE(matrix_push_back) {
Mat row = Mat::ones(2, 3, CV_32F);
Mat mat;
for (int i = 1; i <= 3; i++) {
mat.push_back( Mat(row*i) );
}
Mat expected = (Mat_<float>(6, 3) << 1, 1, 1,
1, 1, 1,
2, 2, 2,
2, 2, 2,
3, 3, 3,
3, 3, 3);
BOOST_CHECK(vis::equals(expected, mat));
}
<commit_msg>Added test for OpenCV serialization<commit_after>/**
* @file opencv_sanity.cpp
* @brief Sanity test for the OpenCV libraries
* @author Paolo D'Apice
*/
#define BOOST_TEST_MODULE sanity
#include <boost/test/unit_test.hpp>
#include "utils/matrix.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#define argc boost::unit_test::framework::master_test_suite().argc
#define argv boost::unit_test::framework::master_test_suite().argv
using namespace cv;
using namespace std;
BOOST_AUTO_TEST_CASE(lena) {
Mat image = imread(argv[1]);
BOOST_WARN_MESSAGE(!image.data, "No image data");
BOOST_CHECK_EQUAL(Size(512, 512), image.size());
BOOST_CHECK_EQUAL(512, image.rows);
BOOST_CHECK_EQUAL(512, image.cols);
BOOST_CHECK_EQUAL(2, image.dims);
BOOST_CHECK_EQUAL(3, image.channels());
if (argc > 2) {
imshow("Display image", image);
cout << "Press a key to continue" << endl;
waitKey(0);
}
}
#define print(X) cout << #X << ": " << X << endl;
BOOST_AUTO_TEST_CASE(opencv_traits) {
float data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Mat mat(3,3, CV_32F, data);
BOOST_CHECK(CV_32F == DataType<float>::type);
BOOST_CHECK(mat.depth() == DataType<float>::type);
}
BOOST_AUTO_TEST_CASE(matrix_push_back) {
Mat row = Mat::ones(2, 3, CV_32F);
Mat mat;
for (int i = 1; i <= 3; i++) {
mat.push_back( Mat(row*i) );
}
Mat expected = (Mat_<float>(6, 3) << 1, 1, 1,
1, 1, 1,
2, 2, 2,
2, 2, 2,
3, 3, 3,
3, 3, 3);
BOOST_CHECK(vis::equals(expected, mat));
}
BOOST_AUTO_TEST_CASE(serialization) {
Mat mat(4, 4, CV_32F);
randu(mat, Scalar(0), Scalar(255));
cout << mat << endl;
{
FileStorage fs("test_serialization.yml", FileStorage::WRITE);
BOOST_CHECK(fs.isOpened());
fs << "matrix" << mat;
fs.release();
BOOST_CHECK(not fs.isOpened());
}
{
FileStorage fs;
fs.open("test_serialization.yml", FileStorage::READ);
BOOST_CHECK(fs.isOpened());
Mat loaded;
fs["matrix"] >> loaded;
cout << loaded << endl;
BOOST_CHECK(vis::equals(mat, loaded));
fs.release();
BOOST_CHECK(not fs.isOpened());
}
}
<|endoftext|> |
<commit_before>#include <graphics/gltexture.h>
#include <graphics/exceptions.h>
namespace graphics {
GLuint GLTexture::activeTexture = 0;
GLTexture::GLTexture(const std::string &fname) : id(0) {
std::vector<unsigned char> image_data;
unsigned int width, height;
if (unsigned int error = lodepng::decode(image_data, width, height, "texture.png")) {
throw TextureCreationError(std::string("Error loading texture: ") + lodepng_error_text(error ^ 1));
}
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
// set image format
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// put data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image_data[0]);
// set tex parameters I like
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // necessary for wall/floor
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
}
<commit_msg>I'm an idiot<commit_after>#include <graphics/gltexture.h>
#include <graphics/exceptions.h>
namespace graphics {
GLuint GLTexture::activeTexture = 0;
GLTexture::GLTexture(const std::string &fname) : id(0) {
std::vector<unsigned char> image_data;
unsigned int width, height;
if (unsigned int error = lodepng::decode(image_data, width, height, fname)) {
throw TextureCreationError(std::string("Error loading texture: ") + lodepng_error_text(error ^ 1));
}
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
// set image format
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// put data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image_data[0]);
// set tex parameters I like
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // necessary for wall/floor
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/SimpleTagHDF5.hpp>
#include <nix/hdf5/RepresentationHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
SimpleTagHDF5::SimpleTagHDF5(const SimpleTagHDF5 &tag)
: EntityWithSourcesHDF5(tag.file(), tag.block(), tag.group(), tag.id()),
references_list(tag.group(), "references")
{
representation_group = tag.representation_group;
}
SimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,
const string &id)
: EntityWithSourcesHDF5(file, block, group, id), references_list(group, "references")
{
representation_group = group.openGroup("representations");
}
SimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,
const string &id, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, time), references_list(group, "references")
{
representation_group = group.openGroup("representations");
}
vector<string> SimpleTagHDF5::units() const {
vector<string> units;
group().getData("units", units);
return units;
}
void SimpleTagHDF5::units(vector<string> &units) {
group().setData("units", units);
}
void SimpleTagHDF5::units(const none_t t) {
if(group().hasAttr("units")) {
group().removeAttr("units");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::position() const {
vector<double> position;
group().getData("position", position);
return position;
}
void SimpleTagHDF5::position(const vector<double> &position) {
group().setData("position", position);
}
vector<double> SimpleTagHDF5::extent() const {
vector<double> extent;
group().getData("extent", extent);
return extent;
}
void SimpleTagHDF5::extent(const vector<double> &extent) {
group().setData("extent", extent);
}
void SimpleTagHDF5::extent(const none_t t) {
if(group().hasAttr("extent")) {
group().removeAttr("extent");
}
forceUpdatedAt();
}
// Methods concerning references.
bool SimpleTagHDF5::hasReference(const DataArray &reference) const {
return references_list.has(reference.id());
}
bool SimpleTagHDF5::hasReference(const std::string &id) const {
return references_list.has(id);
}
size_t SimpleTagHDF5::referenceCount() const {
return references_list.count();
}
DataArray SimpleTagHDF5::getReference(const std::string &id) const {
if (hasReference(id)) {
return block().getDataArray(id);
} else {
throw runtime_error("No reference with id: " + id);
}
}
DataArray SimpleTagHDF5::getReference(size_t index) const {
std::vector<std::string> refs = references_list.get();
std::string id;
// get reference id
if(index < refs.size()) {
id = refs[index];
} else {
throw runtime_error("No data array index: " + index);
}
// get referenced array
if(block().hasDataArray(id)) {
return block().getDataArray(id);
} else {
throw runtime_error("No data array id: " + id);
}
}
void SimpleTagHDF5::addReference(const DataArray &reference) {
string reference_id = reference.id();
if (block().hasDataArray(reference_id)) {
throw runtime_error("Unable to find data array with reference_id " +
reference_id + " on block " + block().id());
}
references_list.add(reference_id);
}
bool SimpleTagHDF5::removeReference(const DataArray &reference) {
return references_list.remove(reference.id());
}
void SimpleTagHDF5::references(const std::vector<DataArray> &references) {
vector<string> ids(references.size());
for (size_t i = 0; i < references.size(); i++) {
ids[i] = references[i].id();
}
references_list.set(ids);
}
// Methods concerning representations.
bool SimpleTagHDF5::hasRepresentation(const string &id) const {
return representation_group.hasGroup(id);
}
size_t SimpleTagHDF5::representationCount() const {
return representation_group.objectCount();
}
Representation SimpleTagHDF5::getRepresentation(const std::string &id) const {
Group rep_g = representation_group.openGroup(id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, id));
return Representation(tmp);
}
Representation SimpleTagHDF5::getRepresentation(size_t index) const{
string rep_id = representation_group.objectName(index);
Group rep_g = representation_group.openGroup(rep_id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, rep_id));
return Representation(tmp);
}
Representation SimpleTagHDF5::createRepresentation(DataArray data, LinkType link_type){
string rep_id = util::createId("representation");
while(representation_group.hasObject(rep_id))
rep_id = util::createId("representation");
Group rep_g = representation_group.openGroup(rep_id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, rep_id));
tmp->linkType(link_type);
tmp->data(data);
return Representation(tmp);
}
bool SimpleTagHDF5::deleteRepresentation(const string &id){
if (representation_group.hasGroup(id)) {
representation_group.removeGroup(id);
return true;
} else {
return false;
}
}
// Other methods and functions
void SimpleTagHDF5::swap(SimpleTagHDF5 &other) {
using std::swap;
EntityWithSourcesHDF5::swap(other);
swap(representation_group, other.representation_group);
swap(references_list, other.references_list);
}
SimpleTagHDF5& SimpleTagHDF5::operator=(const SimpleTagHDF5 &other) {
if (*this != other) {
SimpleTagHDF5 tmp(other);
swap(tmp);
}
return *this;
}
ostream& operator<<(ostream &out, const SimpleTagHDF5 &ent) {
out << "SimpleTag: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
SimpleTagHDF5::~SimpleTagHDF5()
{
// TODO Auto-generated destructor stub
}
} // namespace hdf5
} // namespace nix
<commit_msg>SimpleTagHDF5: Use new OutOfBound exception<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/SimpleTagHDF5.hpp>
#include <nix/hdf5/RepresentationHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>
#include <nix/Exception.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
SimpleTagHDF5::SimpleTagHDF5(const SimpleTagHDF5 &tag)
: EntityWithSourcesHDF5(tag.file(), tag.block(), tag.group(), tag.id()),
references_list(tag.group(), "references")
{
representation_group = tag.representation_group;
}
SimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,
const string &id)
: EntityWithSourcesHDF5(file, block, group, id), references_list(group, "references")
{
representation_group = group.openGroup("representations");
}
SimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,
const string &id, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, time), references_list(group, "references")
{
representation_group = group.openGroup("representations");
}
vector<string> SimpleTagHDF5::units() const {
vector<string> units;
group().getData("units", units);
return units;
}
void SimpleTagHDF5::units(vector<string> &units) {
group().setData("units", units);
}
void SimpleTagHDF5::units(const none_t t) {
if(group().hasAttr("units")) {
group().removeAttr("units");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::position() const {
vector<double> position;
group().getData("position", position);
return position;
}
void SimpleTagHDF5::position(const vector<double> &position) {
group().setData("position", position);
}
vector<double> SimpleTagHDF5::extent() const {
vector<double> extent;
group().getData("extent", extent);
return extent;
}
void SimpleTagHDF5::extent(const vector<double> &extent) {
group().setData("extent", extent);
}
void SimpleTagHDF5::extent(const none_t t) {
if(group().hasAttr("extent")) {
group().removeAttr("extent");
}
forceUpdatedAt();
}
// Methods concerning references.
bool SimpleTagHDF5::hasReference(const DataArray &reference) const {
return references_list.has(reference.id());
}
bool SimpleTagHDF5::hasReference(const std::string &id) const {
return references_list.has(id);
}
size_t SimpleTagHDF5::referenceCount() const {
return references_list.count();
}
DataArray SimpleTagHDF5::getReference(const std::string &id) const {
if (hasReference(id)) {
return block().getDataArray(id);
} else {
throw runtime_error("No reference with id: " + id);
}
}
DataArray SimpleTagHDF5::getReference(size_t index) const {
std::vector<std::string> refs = references_list.get();
std::string id;
// get reference id
if(index < refs.size()) {
id = refs[index];
} else {
throw OutOfBounds("No data array at given index", index);
}
// get referenced array
if(block().hasDataArray(id)) {
return block().getDataArray(id);
} else {
throw runtime_error("No data array id: " + id);
}
}
void SimpleTagHDF5::addReference(const DataArray &reference) {
string reference_id = reference.id();
if (block().hasDataArray(reference_id)) {
throw runtime_error("Unable to find data array with reference_id " +
reference_id + " on block " + block().id());
}
references_list.add(reference_id);
}
bool SimpleTagHDF5::removeReference(const DataArray &reference) {
return references_list.remove(reference.id());
}
void SimpleTagHDF5::references(const std::vector<DataArray> &references) {
vector<string> ids(references.size());
for (size_t i = 0; i < references.size(); i++) {
ids[i] = references[i].id();
}
references_list.set(ids);
}
// Methods concerning representations.
bool SimpleTagHDF5::hasRepresentation(const string &id) const {
return representation_group.hasGroup(id);
}
size_t SimpleTagHDF5::representationCount() const {
return representation_group.objectCount();
}
Representation SimpleTagHDF5::getRepresentation(const std::string &id) const {
Group rep_g = representation_group.openGroup(id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, id));
return Representation(tmp);
}
Representation SimpleTagHDF5::getRepresentation(size_t index) const{
string rep_id = representation_group.objectName(index);
Group rep_g = representation_group.openGroup(rep_id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, rep_id));
return Representation(tmp);
}
Representation SimpleTagHDF5::createRepresentation(DataArray data, LinkType link_type){
string rep_id = util::createId("representation");
while(representation_group.hasObject(rep_id))
rep_id = util::createId("representation");
Group rep_g = representation_group.openGroup(rep_id, false);
shared_ptr<RepresentationHDF5> tmp(new RepresentationHDF5(file(), block(), rep_g, rep_id));
tmp->linkType(link_type);
tmp->data(data);
return Representation(tmp);
}
bool SimpleTagHDF5::deleteRepresentation(const string &id){
if (representation_group.hasGroup(id)) {
representation_group.removeGroup(id);
return true;
} else {
return false;
}
}
// Other methods and functions
void SimpleTagHDF5::swap(SimpleTagHDF5 &other) {
using std::swap;
EntityWithSourcesHDF5::swap(other);
swap(representation_group, other.representation_group);
swap(references_list, other.references_list);
}
SimpleTagHDF5& SimpleTagHDF5::operator=(const SimpleTagHDF5 &other) {
if (*this != other) {
SimpleTagHDF5 tmp(other);
swap(tmp);
}
return *this;
}
ostream& operator<<(ostream &out, const SimpleTagHDF5 &ent) {
out << "SimpleTag: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
SimpleTagHDF5::~SimpleTagHDF5()
{
// TODO Auto-generated destructor stub
}
} // namespace hdf5
} // namespace nix
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#include "otbParserConditionDataNodeFeatureFunction.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbVectorDataFileWriter.h"
#include "itkPreOrderTreeIterator.h"
int otbParserConditionDataNodeFeatureFunctionNew(int argc, char* argv[])
{
typedef double CoordRepType;
typedef double PrecisionType;
typedef otb::VectorImage<double, 2> ImageType;
typedef otb::ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>
ParserConditionDataNodeFeaturefunctionType;
ParserConditionDataNodeFeaturefunctionType::Pointer
ParserConditionFeature = ParserConditionDataNodeFeaturefunctionType::New();
std::cout << ParserConditionFeature << std::endl;
return EXIT_SUCCESS;
}
int otbParserConditionDataNodeFeatureFunction(int argc, char* argv[])
{
const char * inputVD = argv[1];
const char * inputImg = argv[2];
const char * DEMDir = argv[3];
const char * outputVD = argv[4];
const char * expression = argv[5];
int DisplayWarnings = atoi(argv[6]);
typedef double CoordRepType;
typedef double PrecisionType;
typedef otb::VectorImage<PrecisionType> ImageType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef otb::VectorData<CoordRepType, 2, PrecisionType> VectorDataType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, ImageType> VectorDataReProjFilter;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType> TreeIteratorType;
typedef otb::ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>
ParserConditionDataNodeFeaturefunctionType;
typedef ParserConditionDataNodeFeaturefunctionType::OutputType ParserConditionFeatureOutputType;
ImageReaderType::Pointer imgReader = ImageReaderType::New();
VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
VectorDataReProjFilter::Pointer vdReProjFilter = VectorDataReProjFilter::New();
VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();
ParserConditionDataNodeFeaturefunctionType::Pointer
ParserConditionFeatureFunction = ParserConditionDataNodeFeaturefunctionType::New();
if (!DisplayWarnings)
{
imgReader->SetGlobalWarningDisplay(0);
}
vdReader->SetFileName(inputVD);
vdReader->Update();
imgReader->SetFileName(inputImg);
imgReader->UpdateOutputInformation();
imgReader->Update(); //Needed to set m_EndIndex, m_StartIndex in otbDataNodeImageFunction
vdReProjFilter->SetInputImage(imgReader->GetOutput());
vdReProjFilter->SetInputVectorData(vdReader->GetOutput());
vdReProjFilter->SetDEMDirectory(DEMDir);
vdReProjFilter->SetUseOutputSpacingAndOriginFromImage(true);
vdReProjFilter->Update();
ParserConditionFeatureFunction->SetExpression("ndvi(b3,b4) > 0.047");
ParserConditionFeatureFunction->SetInputImage(imgReader->GetOutput());
// Output
VectorDataType::Pointer outVD = VectorDataType::New();
// Retrieving root node
DataNodeType::Pointer root = outVD->GetDataTree()->GetRoot()->Get();
// Create the document node
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
// Adding the layer to the data tree
outVD->GetDataTree()->Add(document, root);
// Create the folder node
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
// Adding the layer to the data tree
outVD->GetDataTree()->Add(folder, document);
TreeIteratorType itVector(vdReProjFilter->GetOutput()->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (itVector.Get()->IsLineFeature() || itVector.Get()->IsPolygonFeature())
{
const DataNodeType::Pointer currentGeometry = itVector.Get();
ParserConditionFeatureOutputType currentResult;
currentResult = ParserConditionFeatureFunction->Evaluate(*(currentGeometry.GetPointer()));
currentGeometry->SetFieldAsDouble("NDVI", (double) (currentResult[0]));
outVD->GetDataTree()->Add(currentGeometry, folder);
}
++itVector;
}
vdWriter->SetInput(outVD);
vdWriter->SetFileName(outputVD);
vdWriter->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: use the expression passed in arguments<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#include "otbParserConditionDataNodeFeatureFunction.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbVectorDataFileWriter.h"
#include "itkPreOrderTreeIterator.h"
int otbParserConditionDataNodeFeatureFunctionNew(int argc, char* argv[])
{
typedef double CoordRepType;
typedef double PrecisionType;
typedef otb::VectorImage<double, 2> ImageType;
typedef otb::ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>
ParserConditionDataNodeFeaturefunctionType;
ParserConditionDataNodeFeaturefunctionType::Pointer
ParserConditionFeature = ParserConditionDataNodeFeaturefunctionType::New();
std::cout << ParserConditionFeature << std::endl;
return EXIT_SUCCESS;
}
int otbParserConditionDataNodeFeatureFunction(int argc, char* argv[])
{
const char * inputVD = argv[1];
const char * inputImg = argv[2];
const char * DEMDir = argv[3];
const char * outputVD = argv[4];
const char * expression = argv[5];
int DisplayWarnings = atoi(argv[6]);
typedef double CoordRepType;
typedef double PrecisionType;
typedef otb::VectorImage<PrecisionType> ImageType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef otb::VectorData<CoordRepType, 2, PrecisionType> VectorDataType;
typedef VectorDataType::DataNodeType DataNodeType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, ImageType> VectorDataReProjFilter;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef itk::PreOrderTreeIterator<VectorDataType::DataTreeType> TreeIteratorType;
typedef otb::ParserConditionDataNodeFeatureFunction<ImageType, CoordRepType, PrecisionType>
ParserConditionDataNodeFeaturefunctionType;
typedef ParserConditionDataNodeFeaturefunctionType::OutputType ParserConditionFeatureOutputType;
ImageReaderType::Pointer imgReader = ImageReaderType::New();
VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
VectorDataReProjFilter::Pointer vdReProjFilter = VectorDataReProjFilter::New();
VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();
ParserConditionDataNodeFeaturefunctionType::Pointer
ParserConditionFeatureFunction = ParserConditionDataNodeFeaturefunctionType::New();
if (!DisplayWarnings)
{
imgReader->SetGlobalWarningDisplay(0);
}
vdReader->SetFileName(inputVD);
vdReader->Update();
imgReader->SetFileName(inputImg);
imgReader->UpdateOutputInformation();
imgReader->Update(); //Needed to set m_EndIndex, m_StartIndex in otbDataNodeImageFunction
vdReProjFilter->SetInputImage(imgReader->GetOutput());
vdReProjFilter->SetInputVectorData(vdReader->GetOutput());
vdReProjFilter->SetDEMDirectory(DEMDir);
vdReProjFilter->SetUseOutputSpacingAndOriginFromImage(true);
vdReProjFilter->Update();
ParserConditionFeatureFunction->SetExpression(expression);
ParserConditionFeatureFunction->SetInputImage(imgReader->GetOutput());
// Output
VectorDataType::Pointer outVD = VectorDataType::New();
// Retrieving root node
DataNodeType::Pointer root = outVD->GetDataTree()->GetRoot()->Get();
// Create the document node
DataNodeType::Pointer document = DataNodeType::New();
document->SetNodeType(otb::DOCUMENT);
// Adding the layer to the data tree
outVD->GetDataTree()->Add(document, root);
// Create the folder node
DataNodeType::Pointer folder = DataNodeType::New();
folder->SetNodeType(otb::FOLDER);
// Adding the layer to the data tree
outVD->GetDataTree()->Add(folder, document);
TreeIteratorType itVector(vdReProjFilter->GetOutput()->GetDataTree());
itVector.GoToBegin();
while (!itVector.IsAtEnd())
{
if (itVector.Get()->IsLineFeature() || itVector.Get()->IsPolygonFeature())
{
const DataNodeType::Pointer currentGeometry = itVector.Get();
ParserConditionFeatureOutputType currentResult;
currentResult = ParserConditionFeatureFunction->Evaluate(*(currentGeometry.GetPointer()));
currentGeometry->SetFieldAsDouble("NDVI", (double) (currentResult[0]));
outVD->GetDataTree()->Add(currentGeometry, folder);
}
++itVector;
}
vdWriter->SetInput(outVD);
vdWriter->SetFileName(outputVD);
vdWriter->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2016 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "repo_maker_selection_tree.h"
#include "../../core/model/bson/repo_node_reference.h"
#include "../modeloptimizer/repo_optimizer_ifc.h"
using namespace repo::manipulator::modelutility;
const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState";
const static std::string REPO_VISIBILITY_STATE_SHOW = "visible";
const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible";
const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible";
SelectionTreeMaker::SelectionTreeMaker(
const repo::core::model::RepoScene *scene)
: scene(scene)
{
}
repo::lib::PropertyTree SelectionTreeMaker::generatePTree(
const repo::core::model::RepoNode *currentNode,
std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps,
std::vector<std::pair<std::string, std::string>> &sharedIDToUniqueID,
repo::lib::PropertyTree &idToMeshesTree,
const std::string ¤tPath,
bool &hiddenOnDefault,
std::vector<std::string> &hiddenNode,
std::vector<std::string> &meshIds) const
{
repo::lib::PropertyTree tree;
if (currentNode)
{
std::string idString = currentNode->getUniqueID().toString();
repo::lib::RepoUUID sharedID = currentNode->getSharedID();
std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString;
auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID);
std::vector<repo::lib::PropertyTree> childrenTrees;
std::vector<repo::core::model::RepoNode*> childrenTypes[2];
std::vector<repo::lib::RepoUUID> metaIDs;
for (const auto &child : children)
{
//Ensure IFC Space (if any) are put into the tree first.
if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos)
childrenTypes[0].push_back(child);
else if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA)
{
metaIDs.push_back(child->getUniqueID());
}
else
childrenTypes[1].push_back(child);
}
bool hasHiddenChildren = false;
for (const auto &childrenSet : childrenTypes)
{
for (const auto &child : childrenSet)
{
if (child)
{
switch (child->getTypeAsEnum())
{
case repo::core::model::NodeType::MESH:
meshIds.push_back(child->getUniqueID().toString());
case repo::core::model::NodeType::TRANSFORMATION:
case repo::core::model::NodeType::CAMERA:
case repo::core::model::NodeType::REFERENCE:
{
bool hiddenChild = false;
std::vector<std::string> childrenMeshes;
childrenTrees.push_back(generatePTree(child, idMaps, sharedIDToUniqueID, idToMeshesTree, childPath, hiddenChild, hiddenNode, childrenMeshes));
hasHiddenChildren = hasHiddenChildren || hiddenChild;
meshIds.insert(meshIds.end(), childrenMeshes.begin(), childrenMeshes.end());
}
}
}
else
{
repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath;
repoError << "Unexpected error at selection tree generation, the tree may not be complete.";
}
}
}
std::string name = currentNode->getName();
if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum())
{
if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode))
{
auto refDb = refNode->getDatabaseName();
name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName();
}
}
tree.addToTree("account", scene->getDatabaseName());
tree.addToTree("project", scene->getProjectName());
tree.addToTree("type", currentNode->getType());
if (!name.empty())
tree.addToTree("name", name);
tree.addToTree("path", childPath);
tree.addToTree("_id", idString);
tree.addToTree("shared_id", sharedID.toString());
tree.addToTree("children", childrenTrees);
if (metaIDs.size())
tree.addToTree("meta", metaIDs);
if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos
&& currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH)
{
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN);
hiddenOnDefault = true;
hiddenNode.push_back(idString);
}
else if (hiddenOnDefault || hasHiddenChildren)
{
hiddenOnDefault = (hiddenOnDefault || hasHiddenChildren);
repoDebug << "Setting " << name << " to half hidden... hiddenOnDefault: " << hiddenOnDefault << " hasHiddenChildren: " << hasHiddenChildren;
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN);
}
else
{
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW);
}
idMaps[idString] = { name, childPath };
sharedIDToUniqueID.push_back({ idString, sharedID.toString() });
if (meshIds.size())
idToMeshesTree.addToTree(idString, meshIds);
else if (currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH){
std::vector<repo::lib::RepoUUID> self = { currentNode->getUniqueID() };
idToMeshesTree.addToTree(idString, self);
}
}
else
{
repoDebug << "Null pointer at generatePTree, current path : " << currentPath;
repoError << "Unexpected error at selection tree generation, the tree may not be complete.";
}
return tree;
}
std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const
{
auto trees = getSelectionTreeAsPropertyTree();
std::map<std::string, std::vector<uint8_t>> buffer;
for (const auto &tree : trees)
{
std::stringstream ss;
tree.second.write_json(ss);
std::string jsonString = ss.str();
if (!jsonString.empty())
{
size_t byteLength = jsonString.size() * sizeof(*jsonString.data());
buffer[tree.first] = std::vector<uint8_t>();
buffer[tree.first].resize(byteLength);
memcpy(buffer[tree.first].data(), jsonString.data(), byteLength);
}
else
{
repoError << "Failed to write selection tree into the buffer: JSON string is empty.";
}
}
return buffer;
}
std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const
{
std::map<std::string, repo::lib::PropertyTree> trees;
repo::core::model::RepoNode *root;
if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT)))
{
std::unordered_map< std::string, std::pair<std::string, std::string>> map;
std::vector<std::string> hiddenNodes, childrenMeshes;
bool dummy = false;
repo::lib::PropertyTree tree, settingsTree, treePathTree, shareIDToUniqueIDMap, idToMeshes;
std::vector<std::pair<std::string, std::string>> sharedIDToUniqueID;
tree.mergeSubTree("nodes", generatePTree(root, map, sharedIDToUniqueID, idToMeshes, "", dummy, hiddenNodes, childrenMeshes));
for (const auto pair : map)
{
//if there's an entry in maps it must have an entry in paths
tree.addToTree("idToName." + pair.first, pair.second.first);
treePathTree.addToTree("idToPath." + pair.first, pair.second.second);
}
for (const auto pair : sharedIDToUniqueID)
{
shareIDToUniqueIDMap.addToTree("idMap." + pair.first, pair.second);
}
trees["fulltree.json"] = tree;
trees["tree_path.json"] = treePathTree;
trees["idMap.json"] = shareIDToUniqueIDMap;
trees["idToMeshes.json"] = idToMeshes;
if (hiddenNodes.size())
{
settingsTree.addToTree("hiddenNodes", hiddenNodes);
trees["modelProperties.json"] = settingsTree;
}
}
else
{
repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded";
}
return trees;
}
SelectionTreeMaker::~SelectionTreeMaker()
{
}<commit_msg>ISSUE #230 fix where IFC space is not getting metadata<commit_after>/**
* Copyright (C) 2016 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "repo_maker_selection_tree.h"
#include "../../core/model/bson/repo_node_reference.h"
#include "../modeloptimizer/repo_optimizer_ifc.h"
using namespace repo::manipulator::modelutility;
const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState";
const static std::string REPO_VISIBILITY_STATE_SHOW = "visible";
const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible";
const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible";
SelectionTreeMaker::SelectionTreeMaker(
const repo::core::model::RepoScene *scene)
: scene(scene)
{
}
repo::lib::PropertyTree SelectionTreeMaker::generatePTree(
const repo::core::model::RepoNode *currentNode,
std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps,
std::vector<std::pair<std::string, std::string>> &sharedIDToUniqueID,
repo::lib::PropertyTree &idToMeshesTree,
const std::string ¤tPath,
bool &hiddenOnDefault,
std::vector<std::string> &hiddenNode,
std::vector<std::string> &meshIds) const
{
repo::lib::PropertyTree tree;
if (currentNode)
{
std::string idString = currentNode->getUniqueID().toString();
repo::lib::RepoUUID sharedID = currentNode->getSharedID();
std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString;
auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID);
std::vector<repo::lib::PropertyTree> childrenTrees;
std::vector<repo::core::model::RepoNode*> childrenTypes[2];
std::vector<repo::lib::RepoUUID> metaIDs;
for (const auto &child : children)
{
if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA)
{
metaIDs.push_back(child->getUniqueID());
}
else
{
//Ensure IFC Space (if any) are put into the tree first.
if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos)
childrenTypes[0].push_back(child);
else
childrenTypes[1].push_back(child);
}
}
bool hasHiddenChildren = false;
for (const auto &childrenSet : childrenTypes)
{
for (const auto &child : childrenSet)
{
if (child)
{
switch (child->getTypeAsEnum())
{
case repo::core::model::NodeType::MESH:
meshIds.push_back(child->getUniqueID().toString());
case repo::core::model::NodeType::TRANSFORMATION:
case repo::core::model::NodeType::CAMERA:
case repo::core::model::NodeType::REFERENCE:
{
bool hiddenChild = false;
std::vector<std::string> childrenMeshes;
childrenTrees.push_back(generatePTree(child, idMaps, sharedIDToUniqueID, idToMeshesTree, childPath, hiddenChild, hiddenNode, childrenMeshes));
hasHiddenChildren = hasHiddenChildren || hiddenChild;
meshIds.insert(meshIds.end(), childrenMeshes.begin(), childrenMeshes.end());
}
}
}
else
{
repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath;
repoError << "Unexpected error at selection tree generation, the tree may not be complete.";
}
}
}
std::string name = currentNode->getName();
if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum())
{
if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode))
{
auto refDb = refNode->getDatabaseName();
name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName();
}
}
tree.addToTree("account", scene->getDatabaseName());
tree.addToTree("project", scene->getProjectName());
tree.addToTree("type", currentNode->getType());
if (!name.empty())
tree.addToTree("name", name);
tree.addToTree("path", childPath);
tree.addToTree("_id", idString);
tree.addToTree("shared_id", sharedID.toString());
tree.addToTree("children", childrenTrees);
if (metaIDs.size())
tree.addToTree("meta", metaIDs);
if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos
&& currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH)
{
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN);
hiddenOnDefault = true;
hiddenNode.push_back(idString);
}
else if (hiddenOnDefault || hasHiddenChildren)
{
hiddenOnDefault = (hiddenOnDefault || hasHiddenChildren);
repoDebug << "Setting " << name << " to half hidden... hiddenOnDefault: " << hiddenOnDefault << " hasHiddenChildren: " << hasHiddenChildren;
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN);
}
else
{
tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW);
}
idMaps[idString] = { name, childPath };
sharedIDToUniqueID.push_back({ idString, sharedID.toString() });
if (meshIds.size())
idToMeshesTree.addToTree(idString, meshIds);
else if (currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH){
std::vector<repo::lib::RepoUUID> self = { currentNode->getUniqueID() };
idToMeshesTree.addToTree(idString, self);
}
}
else
{
repoDebug << "Null pointer at generatePTree, current path : " << currentPath;
repoError << "Unexpected error at selection tree generation, the tree may not be complete.";
}
return tree;
}
std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const
{
auto trees = getSelectionTreeAsPropertyTree();
std::map<std::string, std::vector<uint8_t>> buffer;
for (const auto &tree : trees)
{
std::stringstream ss;
tree.second.write_json(ss);
std::string jsonString = ss.str();
if (!jsonString.empty())
{
size_t byteLength = jsonString.size() * sizeof(*jsonString.data());
buffer[tree.first] = std::vector<uint8_t>();
buffer[tree.first].resize(byteLength);
memcpy(buffer[tree.first].data(), jsonString.data(), byteLength);
}
else
{
repoError << "Failed to write selection tree into the buffer: JSON string is empty.";
}
}
return buffer;
}
std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const
{
std::map<std::string, repo::lib::PropertyTree> trees;
repo::core::model::RepoNode *root;
if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT)))
{
std::unordered_map< std::string, std::pair<std::string, std::string>> map;
std::vector<std::string> hiddenNodes, childrenMeshes;
bool dummy = false;
repo::lib::PropertyTree tree, settingsTree, treePathTree, shareIDToUniqueIDMap, idToMeshes;
std::vector<std::pair<std::string, std::string>> sharedIDToUniqueID;
tree.mergeSubTree("nodes", generatePTree(root, map, sharedIDToUniqueID, idToMeshes, "", dummy, hiddenNodes, childrenMeshes));
for (const auto pair : map)
{
//if there's an entry in maps it must have an entry in paths
tree.addToTree("idToName." + pair.first, pair.second.first);
treePathTree.addToTree("idToPath." + pair.first, pair.second.second);
}
for (const auto pair : sharedIDToUniqueID)
{
shareIDToUniqueIDMap.addToTree("idMap." + pair.first, pair.second);
}
trees["fulltree.json"] = tree;
trees["tree_path.json"] = treePathTree;
trees["idMap.json"] = shareIDToUniqueIDMap;
trees["idToMeshes.json"] = idToMeshes;
if (hiddenNodes.size())
{
settingsTree.addToTree("hiddenNodes", hiddenNodes);
trees["modelProperties.json"] = settingsTree;
}
}
else
{
repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded";
}
return trees;
}
SelectionTreeMaker::~SelectionTreeMaker()
{
}<|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:
//
// 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 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 AUTHOR ``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 AUTHOR 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.
// The file contains the implementation of the File methods specific to
// POSIX platforms.
#include "kml/base/file.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
namespace kmlbase {
// Internal to the POSIX File class.
static bool StatFile(const char* path, struct stat* stat_data) {
struct stat tmp;
if (stat(path, &tmp) !=0) {
return false;
}
*stat_data = tmp;
return true;
}
bool File::Exists(const string& full_path) {
struct stat stat_data;
if (!StatFile(full_path.c_str(), &stat_data)) {
return false;
}
return S_ISREG(stat_data.st_mode);
}
bool File::Delete(const string& filepath) {
return unlink(filepath.c_str()) == 0;
}
bool File::CreateNewTempFile(string* path) {
if (!path) {
return false;
}
char temp_path[] = "/tmp/libkmlXXXXXX";
int fd = mkstemp(temp_path);
if (fd == -1) {
return false;
}
close(fd);
path->assign(temp_path, strlen(temp_path));
return true;
}
} // end namespace kmlbase
<commit_msg>Another crosstool fix -- unistd.h must be included for unlink, close methods in some compilers.<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:
//
// 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 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 AUTHOR ``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 AUTHOR 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.
// The file contains the implementation of the File methods specific to
// POSIX platforms.
#include "kml/base/file.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> // For unlink, close.
namespace kmlbase {
// Internal to the POSIX File class.
static bool StatFile(const char* path, struct stat* stat_data) {
struct stat tmp;
if (stat(path, &tmp) !=0) {
return false;
}
*stat_data = tmp;
return true;
}
bool File::Exists(const string& full_path) {
struct stat stat_data;
if (!StatFile(full_path.c_str(), &stat_data)) {
return false;
}
return S_ISREG(stat_data.st_mode);
}
bool File::Delete(const string& filepath) {
return unlink(filepath.c_str()) == 0;
}
bool File::CreateNewTempFile(string* path) {
if (!path) {
return false;
}
char temp_path[] = "/tmp/libkmlXXXXXX";
int fd = mkstemp(temp_path);
if (fd == -1) {
return false;
}
close(fd);
path->assign(temp_path, strlen(temp_path));
return true;
}
} // end namespace kmlbase
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.