text
stringlengths
54
60.6k
<commit_before>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "org/xtreemfs/client.h" #include "main.h" using namespace org::xtreemfs::client; #include "yield.h" #include <iostream> using std::cout; using std::endl; namespace org { namespace xtreemfs { namespace client { class argvInputStream : public YIELD::StructuredInputStream { public: argvInputStream( int argc, char** argv ) : argc( argc ), argv( argv ) { next_arg_i = 0; } bool readBool( const Declaration& decl ) { const char* value = readValue( decl ); return value && ( strcmp( value, "true" ) == 0 || strcmp( value, "t" ) == 0 ); } double readDouble( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atof( value ); else return 0; } int64_t readInt64( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atol( value ); else return 0; } YIELD::Object* readObject( const Declaration& decl, YIELD::Object* s = NULL ) { if ( s ) { switch ( s->get_general_type() ) { case YIELD::Object::STRING: readString( decl, static_cast<YIELD::String&>( *s ) ); break; case YIELD::Object::STRUCT: s->deserialize( *this ); break; } } return s; } void readString( const Declaration& decl, std::string& str ) { const char* value = readValue( decl ); if ( value ) str = value; } uint64_t readUint64( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atol( value ); else return 0; } private: int argc; char** argv; int next_arg_i; const char* readValue( const Declaration& decl ) { if ( next_arg_i < argc ) return argv[next_arg_i++]; else return NULL; } }; class xtfs_send : public Main { public: xtfs_send() : Main( "xtfs_send", "send RPCs to an XtreemFS server", "[oncrpc[s]://]<host>[:port]/<rpc operation name> [rpc operation parameters]" ) { org::xtreemfs::interfaces::DIRInterface().registerObjectFactories( object_factories ); org::xtreemfs::interfaces::MRCInterface().registerObjectFactories( object_factories ); org::xtreemfs::interfaces::OSDInterface().registerObjectFactories( object_factories ); proxy = NULL; } ~xtfs_send() { YIELD::Object::decRef( proxy ); } private: YIELD::ObjectFactories object_factories; YIELD::auto_Object<YIELD::Request> request; YIELD::EventTarget* proxy; // xtfs_bin int _main( int, char** ) { proxy->send( request.get()->incRef() ); YIELD::Event& resp = request.get()->waitForDefaultResponse( get_timeout_ms() ); std::cout << resp.get_type_name() << "( "; YIELD::PrettyPrintOutputStream output_stream( std::cout ); resp.serialize( output_stream ); std::cout << " )" << std::endl; YIELD::Object::decRef( resp ); return 0; } void parseFiles( int files_count, char** files ) { if ( files_count >= 1 ) { std::auto_ptr<YIELD::URI> rpc_uri = parseURI( files[0] ); if ( strlen( rpc_uri.get()->get_resource() ) > 1 ) { std::string request_type_name( rpc_uri.get()->get_resource() + 1 ); request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::MRCInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createMRCProxy( *rpc_uri.get() ).release(); else { request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::DIRInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createDIRProxy( *rpc_uri.get() ).release(); else { request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::OSDInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createOSDProxy( *rpc_uri.get() ).release(); else throw YIELD::Exception( "unknown operation" ); } } if ( files_count > 1 ) { argvInputStream argv_input_stream( files_count - 1, files+1 ); request.get()->deserialize( argv_input_stream ); } } else throw YIELD::Exception( "RPC URI must include an operation name" ); } else throw YIELD::Exception( "must specify RPC URI" ); } }; }; }; }; int main( int argc, char** argv ) { return xtfs_send().main( argc, argv ); } <commit_msg>client: xtfs_send: Linux fix<commit_after>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "org/xtreemfs/client.h" #include "main.h" using namespace org::xtreemfs::client; #include "yield.h" #include <iostream> using std::cout; using std::endl; namespace org { namespace xtreemfs { namespace client { class argvInputStream : public YIELD::StructuredInputStream { public: argvInputStream( int argc, char** argv ) : argc( argc ), argv( argv ) { next_arg_i = 0; } bool readBool( const Declaration& decl ) { const char* value = readValue( decl ); return value && ( strcmp( value, "true" ) == 0 || strcmp( value, "t" ) == 0 ); } double readDouble( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atof( value ); else return 0; } int64_t readInt64( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atol( value ); else return 0; } YIELD::Object* readObject( const Declaration& decl, YIELD::Object* s = NULL ) { if ( s ) { switch ( s->get_general_type() ) { case YIELD::Object::STRING: readString( decl, static_cast<YIELD::String&>( *s ) ); break; case YIELD::Object::STRUCT: s->deserialize( *this ); break; } } return s; } void readString( const Declaration& decl, std::string& str ) { const char* value = readValue( decl ); if ( value ) str = value; } uint64_t readUint64( const Declaration& decl ) { const char* value = readValue( decl ); if ( value ) return atol( value ); else return 0; } private: int argc; char** argv; int next_arg_i; const char* readValue( const Declaration& decl ) { if ( next_arg_i < argc ) return argv[next_arg_i++]; else return NULL; } }; class xtfs_send : public Main { public: xtfs_send() : Main( "xtfs_send", "send RPCs to an XtreemFS server", "[oncrpc[s]://]<host>[:port]/<rpc operation name> [rpc operation parameters]" ) { org::xtreemfs::interfaces::DIRInterface().registerObjectFactories( object_factories ); org::xtreemfs::interfaces::MRCInterface().registerObjectFactories( object_factories ); org::xtreemfs::interfaces::OSDInterface().registerObjectFactories( object_factories ); proxy = NULL; } ~xtfs_send() { YIELD::Object::decRef( proxy ); } private: YIELD::ObjectFactories object_factories; YIELD::auto_Object<YIELD::Request> request; YIELD::EventTarget* proxy; // xtfs_bin int _main( int, char** ) { proxy->send( request.get()->incRef() ); YIELD::Event& resp = request.get()->waitForDefaultResponse( static_cast<uint64_t>( -1 ) ); // get_timeout_ms() ); std::cout << resp.get_type_name() << "( "; YIELD::PrettyPrintOutputStream output_stream( std::cout ); resp.serialize( output_stream ); std::cout << " )" << std::endl; YIELD::Object::decRef( resp ); return 0; } void parseFiles( int files_count, char** files ) { if ( files_count >= 1 ) { std::auto_ptr<YIELD::URI> rpc_uri = parseURI( files[0] ); if ( strlen( rpc_uri.get()->get_resource() ) > 1 ) { std::string request_type_name( rpc_uri.get()->get_resource() + 1 ); request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::MRCInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createMRCProxy( *rpc_uri.get() ).release(); else { request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::DIRInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createDIRProxy( *rpc_uri.get() ).release(); else { request = static_cast<YIELD::Request*>( object_factories.createObject( "org::xtreemfs::interfaces::OSDInterface::" + request_type_name + "SyncRequest" ) ); if ( request.get() != NULL ) proxy = createOSDProxy( *rpc_uri.get() ).release(); else throw YIELD::Exception( "unknown operation" ); } } if ( files_count > 1 ) { argvInputStream argv_input_stream( files_count - 1, files+1 ); request.get()->deserialize( argv_input_stream ); } } else throw YIELD::Exception( "RPC URI must include an operation name" ); } else throw YIELD::Exception( "must specify RPC URI" ); } }; }; }; }; int main( int argc, char** argv ) { return xtfs_send().main( argc, argv ); } <|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4 * * Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2008-2009 Nokia Corporation * * 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 */ #include <TelepathyQt4/Client/DBusProxy> #include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <TelepathyQt4/Constants> #include <QTimer> #include <QDBusConnection> #include <QDBusConnectionInterface> #include <QDBusError> namespace Telepathy { namespace Client { // ==== DBusProxy ====================================================== /** * \class DBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object available over D-Bus. * * All TelepathyQt4 client convenience classes that wrap Telepathy interfaces * inherit from this class in order to provide basic D-Bus interface * information. * */ /** * \enum DBusProxy::InterfaceSupportedChecking * * Specifies if the interface being supported by the remote object should be * checked by optionalInterface() and the convenience functions for it. * * \value CheckInterfaceSupported Don't return an interface instance unless it * can be guaranteed that the remote object * actually implements the interface. * \value BypassInterfaceCheck Return an interface instance even if it can't * be verified that the remote object supports the * interface. * \sa optionalInterface() */ // Features in TpProxy but not here: // * tracking which interfaces we have (in tpqt4, subclasses do that) // * being Introspectable, a Peer and a Properties implementation // * disconnecting from signals when invalidated (probably has to be in the // generated code) // * making methods always raise an error when called after invalidated // (has to be in the generated code) class DBusProxy::Private { public: QDBusConnection dbusConnection; QString busName; QString objectPath; QString invalidationReason; QString invalidationMessage; Private(const QDBusConnection &, const QString &, const QString &); }; DBusProxy::Private::Private(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath) : dbusConnection(dbusConnection), busName(busName), objectPath(objectPath) { debug() << "Creating new DBusProxy"; } /** * Constructor */ DBusProxy::DBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &path, QObject *parent) : QObject(parent), mPriv(new Private(dbusConnection, busName, path)) { if (!dbusConnection.isConnected()) { invalidate("org.freedesktop.DBus.Error.Disconnected", "DBus connection disconnected"); } } /** * Destructor */ DBusProxy::~DBusProxy() { delete mPriv; } /** * Returns the D-Bus connection through which the remote object is * accessed. * * \return The connection the object is associated with. */ QDBusConnection DBusProxy::dbusConnection() const { return mPriv->dbusConnection; } /** * Returns the D-Bus object path of the remote object within the service. * * \return The object path the object is associated with. */ QString DBusProxy::objectPath() const { return mPriv->objectPath; } /** * Returns the D-Bus bus name (either a unique name or a well-known * name) of the service that provides the remote object. * * \return The service name the object is associated with. */ QString DBusProxy::busName() const { return mPriv->busName; } /** * Sets the D-Bus bus name. This is used by subclasses after converting * well-known names to unique names. */ void DBusProxy::setBusName(const QString &busName) { mPriv->busName = busName; } /** * If this object is usable (has not emitted #invalidated()), returns * <code>true</code>. Otherwise returns <code>false</code>. * * \return <code>true</code> if this object is still fully usable */ bool DBusProxy::isValid() const { return mPriv->invalidationReason.isEmpty(); } /** * If this object is no longer usable (has emitted #invalidated()), * returns the error name indicating the reason it became invalid in a * machine-readable way. Otherwise, returns a null QString. * * \return A D-Bus error name, or QString() if this object is still valid */ QString DBusProxy::invalidationReason() const { return mPriv->invalidationReason; } /** * If this object is no longer usable (has emitted #invalidated()), * returns a debugging message indicating the reason it became invalid. * Otherwise, returns a null QString. * * \return A debugging message, or QString() if this object is still valid */ QString DBusProxy::invalidationMessage() const { return mPriv->invalidationMessage; } /** * \signal invalidated * * Emitted when this object is no longer usable. * * After this signal is emitted, any D-Bus method calls on the object * will fail, but it may be possible to retrieve information that has * already been retrieved and cached. * * \param proxy This proxy * \param errorName A D-Bus error name (a string in a subset * of ASCII, prefixed with a reversed domain name) * \param errorMessage A debugging message associated with the error */ /** * Called by subclasses when the DBusProxy should become invalid. * * This method takes care of setting the invalidationReason, * invalidationMessage, and emitting the invalidated signal. */ void DBusProxy::invalidate(const QString &reason, const QString &message) { if (!isValid()) { debug().nospace() << "Already invalidated by " << mPriv->invalidationReason << ", not replacing with " << reason << " \"" << message << "\""; return; } Q_ASSERT(!reason.isEmpty()); debug().nospace() << "proxy invalidated: " << reason << ": " << message; mPriv->invalidationReason = reason; mPriv->invalidationMessage = message; Q_ASSERT(!isValid()); // Defer emitting the invalidated signal until we next // return to the mainloop. QTimer::singleShot(0, this, SLOT(emitInvalidated())); } void DBusProxy::invalidate(const QDBusError &error) { invalidate(error.name(), error.message()); } void DBusProxy::emitInvalidated() { Q_ASSERT(!isValid()); emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage); } // ==== StatefulDBusProxy ============================================== /** * \class StatefulDBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object whose API is stateful. These * objects do not remain useful if the service providing them exits or * crashes, so they emit #invalidated() if this happens. * * Examples in Telepathy include the Connection and Channel. */ StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent), mPriv(0) { QString uniqueName = busName; connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)), this, SLOT(onServiceOwnerChanged(QString, QString, QString))); if (!busName.startsWith(QChar(':'))) { // For a stateful interface, it makes no sense to follow name-owner // changes, so we want to bind to the unique name. QDBusReply<QString> reply = dbusConnection.interface()->serviceOwner( busName); if (reply.isValid()) { uniqueName = reply.value(); } else { invalidate(reply.error()); } } setBusName(uniqueName); } StatefulDBusProxy::~StatefulDBusProxy() { } void StatefulDBusProxy::onServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) { // We only want to invalidate this object if it is not already invalidated, // and its (not any other object's) name owner changed signal is emitted. if (isValid() && name == busName() && newOwner == "") { invalidate(TELEPATHY_DBUS_ERROR_NAME_HAS_NO_OWNER, "Name owner lost (service crashed?)"); } } // ==== StatelessDBusProxy ============================================= /** * \class StatelessDBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object whose API is basically stateless. * These objects can remain valid even if the service providing them exits * and is restarted. * * Examples in Telepathy include the AccountManager, Account and * ConnectionManager. */ /** * Constructor */ StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent), mPriv(0) { if (busName.startsWith(QChar(':'))) { warning() << "Using StatelessDBusProxy for a unique name does not make sense"; } } /** * Destructor */ StatelessDBusProxy::~StatelessDBusProxy() { } } } <commit_msg>DBusProxy: format enum documentation the way doxygen wants it<commit_after>/* * This file is part of TelepathyQt4 * * Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2008-2009 Nokia Corporation * * 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 */ #include <TelepathyQt4/Client/DBusProxy> #include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <TelepathyQt4/Constants> #include <QTimer> #include <QDBusConnection> #include <QDBusConnectionInterface> #include <QDBusError> namespace Telepathy { namespace Client { // ==== DBusProxy ====================================================== /** * \class DBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object available over D-Bus. * * All TelepathyQt4 client convenience classes that wrap Telepathy interfaces * inherit from this class in order to provide basic D-Bus interface * information. * */ /** * \enum DBusProxy::InterfaceSupportedChecking * * Specifies if the interface being supported by the remote object should be * checked by optionalInterface() and the convenience functions for it. * * \sa optionalInterface() */ /** * \var DBusProxy::InterfaceSupportedChecking DBusProxy::CheckInterfaceSupported * Don't return an interface instance unless it can be guaranteed that the * remote object actually implements the interface. */ /** * \var DBusProxy::InterfaceSupportedChecking DBusProxy::BypassInterfaceCheck * Return an interface instance even if it can't be verified that the remote * object supports the interface. */ // Features in TpProxy but not here: // * tracking which interfaces we have (in tpqt4, subclasses do that) // * being Introspectable, a Peer and a Properties implementation // * disconnecting from signals when invalidated (probably has to be in the // generated code) // * making methods always raise an error when called after invalidated // (has to be in the generated code) class DBusProxy::Private { public: QDBusConnection dbusConnection; QString busName; QString objectPath; QString invalidationReason; QString invalidationMessage; Private(const QDBusConnection &, const QString &, const QString &); }; DBusProxy::Private::Private(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath) : dbusConnection(dbusConnection), busName(busName), objectPath(objectPath) { debug() << "Creating new DBusProxy"; } /** * Constructor */ DBusProxy::DBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &path, QObject *parent) : QObject(parent), mPriv(new Private(dbusConnection, busName, path)) { if (!dbusConnection.isConnected()) { invalidate("org.freedesktop.DBus.Error.Disconnected", "DBus connection disconnected"); } } /** * Destructor */ DBusProxy::~DBusProxy() { delete mPriv; } /** * Returns the D-Bus connection through which the remote object is * accessed. * * \return The connection the object is associated with. */ QDBusConnection DBusProxy::dbusConnection() const { return mPriv->dbusConnection; } /** * Returns the D-Bus object path of the remote object within the service. * * \return The object path the object is associated with. */ QString DBusProxy::objectPath() const { return mPriv->objectPath; } /** * Returns the D-Bus bus name (either a unique name or a well-known * name) of the service that provides the remote object. * * \return The service name the object is associated with. */ QString DBusProxy::busName() const { return mPriv->busName; } /** * Sets the D-Bus bus name. This is used by subclasses after converting * well-known names to unique names. */ void DBusProxy::setBusName(const QString &busName) { mPriv->busName = busName; } /** * If this object is usable (has not emitted #invalidated()), returns * <code>true</code>. Otherwise returns <code>false</code>. * * \return <code>true</code> if this object is still fully usable */ bool DBusProxy::isValid() const { return mPriv->invalidationReason.isEmpty(); } /** * If this object is no longer usable (has emitted #invalidated()), * returns the error name indicating the reason it became invalid in a * machine-readable way. Otherwise, returns a null QString. * * \return A D-Bus error name, or QString() if this object is still valid */ QString DBusProxy::invalidationReason() const { return mPriv->invalidationReason; } /** * If this object is no longer usable (has emitted #invalidated()), * returns a debugging message indicating the reason it became invalid. * Otherwise, returns a null QString. * * \return A debugging message, or QString() if this object is still valid */ QString DBusProxy::invalidationMessage() const { return mPriv->invalidationMessage; } /** * \signal invalidated * * Emitted when this object is no longer usable. * * After this signal is emitted, any D-Bus method calls on the object * will fail, but it may be possible to retrieve information that has * already been retrieved and cached. * * \param proxy This proxy * \param errorName A D-Bus error name (a string in a subset * of ASCII, prefixed with a reversed domain name) * \param errorMessage A debugging message associated with the error */ /** * Called by subclasses when the DBusProxy should become invalid. * * This method takes care of setting the invalidationReason, * invalidationMessage, and emitting the invalidated signal. */ void DBusProxy::invalidate(const QString &reason, const QString &message) { if (!isValid()) { debug().nospace() << "Already invalidated by " << mPriv->invalidationReason << ", not replacing with " << reason << " \"" << message << "\""; return; } Q_ASSERT(!reason.isEmpty()); debug().nospace() << "proxy invalidated: " << reason << ": " << message; mPriv->invalidationReason = reason; mPriv->invalidationMessage = message; Q_ASSERT(!isValid()); // Defer emitting the invalidated signal until we next // return to the mainloop. QTimer::singleShot(0, this, SLOT(emitInvalidated())); } void DBusProxy::invalidate(const QDBusError &error) { invalidate(error.name(), error.message()); } void DBusProxy::emitInvalidated() { Q_ASSERT(!isValid()); emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage); } // ==== StatefulDBusProxy ============================================== /** * \class StatefulDBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object whose API is stateful. These * objects do not remain useful if the service providing them exits or * crashes, so they emit #invalidated() if this happens. * * Examples in Telepathy include the Connection and Channel. */ StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent), mPriv(0) { QString uniqueName = busName; connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)), this, SLOT(onServiceOwnerChanged(QString, QString, QString))); if (!busName.startsWith(QChar(':'))) { // For a stateful interface, it makes no sense to follow name-owner // changes, so we want to bind to the unique name. QDBusReply<QString> reply = dbusConnection.interface()->serviceOwner( busName); if (reply.isValid()) { uniqueName = reply.value(); } else { invalidate(reply.error()); } } setBusName(uniqueName); } StatefulDBusProxy::~StatefulDBusProxy() { } void StatefulDBusProxy::onServiceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) { // We only want to invalidate this object if it is not already invalidated, // and its (not any other object's) name owner changed signal is emitted. if (isValid() && name == busName() && newOwner == "") { invalidate(TELEPATHY_DBUS_ERROR_NAME_HAS_NO_OWNER, "Name owner lost (service crashed?)"); } } // ==== StatelessDBusProxy ============================================= /** * \class StatelessDBusProxy * \ingroup FIXME: what group is it in? * \headerfile TelepathyQt4/Client/dbus-proxy.h <TelepathyQt4/Client/DBusProxy> * * Base class representing a remote object whose API is basically stateless. * These objects can remain valid even if the service providing them exits * and is restarted. * * Examples in Telepathy include the AccountManager, Account and * ConnectionManager. */ /** * Constructor */ StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection &dbusConnection, const QString &busName, const QString &objectPath, QObject *parent) : DBusProxy(dbusConnection, busName, objectPath, parent), mPriv(0) { if (busName.startsWith(QChar(':'))) { warning() << "Using StatelessDBusProxy for a unique name does not make sense"; } } /** * Destructor */ StatelessDBusProxy::~StatelessDBusProxy() { } } } <|endoftext|>
<commit_before>/** * This file is part of TelepathyQt4 * * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2011 Nokia Corporation * @license LGPL 2.1 * * 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 */ #include <TelepathyQt4/ContactMessenger> #include "TelepathyQt4/_gen/contact-messenger.moc.hpp" #include <TelepathyQt4/Account> #include <TelepathyQt4/PendingSendMessage> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ContactMessenger::Private { Private(const AccountPtr &account, const QString &contactIdentifier) : account(account), contactIdentifier(contactIdentifier) { } AccountPtr account; QString contactIdentifier; }; ContactMessengerPtr ContactMessenger::create(const AccountPtr &account, const QString &contactIdentifier) { if (contactIdentifier.isEmpty()) { return ContactMessengerPtr(); } return ContactMessengerPtr(new ContactMessenger(account, contactIdentifier)); } ContactMessenger::ContactMessenger(const AccountPtr &account, const QString &contactIdentifier) : mPriv(new Private(account, contactIdentifier)) { } ContactMessenger::~ContactMessenger() { delete mPriv; } AccountPtr ContactMessenger::account() const { return mPriv->account; } QString ContactMessenger::contactIdentifier() const { return mPriv->contactIdentifier; } PendingSendMessage *ContactMessenger::sendMessage(const QString &text, ChannelTextMessageType type, MessageSendingFlags flags) { return NULL; } PendingSendMessage *ContactMessenger::sendMessage(const MessageContentPartList &parts, MessageSendingFlags flags) { return NULL; } } // Tp <commit_msg>ContactMessenger: Use SimpleTextObserver.<commit_after>/** * This file is part of TelepathyQt4 * * @copyright Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2011 Nokia Corporation * @license LGPL 2.1 * * 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 */ #include <TelepathyQt4/ContactMessenger> #include "TelepathyQt4/_gen/contact-messenger.moc.hpp" #include <TelepathyQt4/Account> #include <TelepathyQt4/ClientRegistrar> #include <TelepathyQt4/PendingSendMessage> #include <TelepathyQt4/SimpleTextObserver> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ContactMessenger::Private { Private(const AccountPtr &account, const QString &contactIdentifier) : account(account), contactIdentifier(contactIdentifier) { } AccountPtr account; QString contactIdentifier; SimpleTextObserverPtr observer; }; ContactMessengerPtr ContactMessenger::create(const AccountPtr &account, const QString &contactIdentifier) { if (contactIdentifier.isEmpty()) { return ContactMessengerPtr(); } return ContactMessengerPtr(new ContactMessenger(account, contactIdentifier)); } ContactMessenger::ContactMessenger(const AccountPtr &account, const QString &contactIdentifier) : mPriv(new Private(account, contactIdentifier)) { mPriv->observer = SimpleTextObserver::create(account, contactIdentifier); connect(mPriv->observer.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString,Tp::TextChannelPtr)), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString,Tp::TextChannelPtr))); connect(mPriv->observer.data(), SIGNAL(messageReceived(Tp::ReceivedMessage,Tp::TextChannelPtr)), SIGNAL(messageReceived(Tp::ReceivedMessage,Tp::TextChannelPtr))); } ContactMessenger::~ContactMessenger() { delete mPriv; } AccountPtr ContactMessenger::account() const { return mPriv->account; } QString ContactMessenger::contactIdentifier() const { return mPriv->contactIdentifier; } PendingSendMessage *ContactMessenger::sendMessage(const QString &text, ChannelTextMessageType type, MessageSendingFlags flags) { return NULL; } PendingSendMessage *ContactMessenger::sendMessage(const MessageContentPartList &parts, MessageSendingFlags flags) { return NULL; } } // Tp <|endoftext|>
<commit_before>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include "Simulation.h" #include "Setup.h" //For setup object #include "NumLib.h" #include "EnergyTypes.h" #include <iostream> #include <iomanip> #include "CUDAMemoryManager.cuh" #include "GOMCEventsProfile.h" #define EPSILON 0.001 Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim): ms(multisim) { GOMC_EVENT_START(1, GomcProfileEvent::INITIALIZE); startStep = 0; GOMC_EVENT_START(1, GomcProfileEvent::READ_INPUT_FILES); set.Init(configFileName, multisim); GOMC_EVENT_STOP(1, GomcProfileEvent::READ_INPUT_FILES); totalSteps = set.config.sys.step.total; staticValues = new StaticVals(set); system = new System(*staticValues, set, multisim); staticValues->Init(set, *system); system->Init(set, startStep); //recalc Init for static value for initializing ewald since ewald is //initialized in system staticValues->InitOver(set, *system); cpu = new CPUSide(*system, *staticValues, set); cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil, totalSteps, startStep); if(totalSteps == 0) { frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name); } #if GOMC_LIB_MPI // set.config.sys.step.parallelTemp is a boolean for enabling/disabling parallel tempering PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange) : NULL; exchangeResults.resize(ms->worldSize, false); #endif GOMC_EVENT_STOP(1, GomcProfileEvent::INITIALIZE); } Simulation::~Simulation() { GOMC_EVENT_START(1, GomcProfileEvent::DESTRUCTION); delete cpu; delete system; delete staticValues; #ifdef GOMC_CUDA CUDAMemoryManager::isFreed(); #endif GOMC_EVENT_STOP(1, GomcProfileEvent::DESTRUCTION); } void Simulation::RunSimulation(void) { GOMC_EVENT_START(1, GomcProfileEvent::MC_RUN); double startEnergy = system->potential.totalEnergy.total; if(totalSteps == 0) { for(int i = 0; i < (int) frameSteps.size(); i++) { if(i == 0) { cpu->Output(frameSteps[0] - 1); continue; } system->RecalculateTrajectory(set, i + 1); cpu->Output(frameSteps[i] - 1); } } for (ulong step = startStep; step < totalSteps; step++) { system->moveSettings.AdjustMoves(step); system->ChooseAndRunMove(step); cpu->Output(step); if((step + 1) == cpu->equilSteps) { double currEnergy = system->potential.totalEnergy.total; if(std::abs(currEnergy - startEnergy) > 1.0e+10) { printf("Info: Recalculating the total energies to insure the accuracy" " of the computed \n" " running energies.\n\n"); system->calcEwald->UpdateVectorsAndRecipTerms(true); system->potential = system->calcEnergy.SystemTotal(); } } #if GOMC_LIB_MPI // if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0) { int maxSwap = 0; /* Number of rounds of exchanges needed to deal with any multiple * exchanges. */ /* Where each replica ends up after the exchange attempt(s). */ /* The order in which multiple exchanges will occur. */ bool bThisReplicaExchanged = false; system->potential = system->calcEnergy.SystemTotal(); PTUtils->evaluateExchangeCriteria(step); PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged); PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged); system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup); if (staticValues->forcefield.ewald) { for(int box = 0; box < BOX_TOTAL; box++) { system->calcEwald->BoxReciprocalSums(box, system->coordinates, false); system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box, false); system->calcEwald->UpdateRecip(box); } } system->potential = system->calcEnergy.SystemTotal(); } #endif #ifndef NDEBUG if((step + 1) % 1000 == 0) RecalculateAndCheck(); #endif } GOMC_EVENT_STOP(1, GomcProfileEvent::MC_RUN); if(!RecalculateAndCheck()) { std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n"; } system->PrintAcceptance(); system->PrintTime(); #if GOMC_LIB_MPI if (staticValues->simEventFreq.parallelTemp) PTUtils->print_replica_exchange_statistics(ms->fplog); #endif } bool Simulation::RecalculateAndCheck(void) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); bool compare = true; compare &= num::approximatelyEqual(system->potential.totalEnergy.intraBond, pot.totalEnergy.intraBond, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.intraNonbond, pot.totalEnergy.intraNonbond, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.inter, pot.totalEnergy.inter, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.tc, pot.totalEnergy.tc, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.real, pot.totalEnergy.real, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.self, pot.totalEnergy.self, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.correction, pot.totalEnergy.correction, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.recip, pot.totalEnergy.recip, EPSILON); if(!compare) { std::cout << "=================================================================\n" << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } return compare; }<commit_msg>init over system<commit_after>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include "Simulation.h" #include "Setup.h" //For setup object #include "NumLib.h" #include "EnergyTypes.h" #include <iostream> #include <iomanip> #include "CUDAMemoryManager.cuh" #include "GOMCEventsProfile.h" #define EPSILON 0.001 Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim): ms(multisim) { GOMC_EVENT_START(1, GomcProfileEvent::INITIALIZE); startStep = 0; GOMC_EVENT_START(1, GomcProfileEvent::READ_INPUT_FILES); set.Init(configFileName, multisim); GOMC_EVENT_STOP(1, GomcProfileEvent::READ_INPUT_FILES); totalSteps = set.config.sys.step.total; staticValues = new StaticVals(set); system = new System(*staticValues, set, multisim); staticValues->Init(set, *system); system->Init(set, startStep); //recalc Init for static value for initializing ewald since ewald is //initialized in system staticValues->InitOver(set, *system); system->InitOver(set, staticValues->mol); cpu = new CPUSide(*system, *staticValues, set); cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil, totalSteps, startStep); if(totalSteps == 0) { frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name); } #if GOMC_LIB_MPI // set.config.sys.step.parallelTemp is a boolean for enabling/disabling parallel tempering PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange) : NULL; exchangeResults.resize(ms->worldSize, false); #endif GOMC_EVENT_STOP(1, GomcProfileEvent::INITIALIZE); } Simulation::~Simulation() { GOMC_EVENT_START(1, GomcProfileEvent::DESTRUCTION); delete cpu; delete system; delete staticValues; #ifdef GOMC_CUDA CUDAMemoryManager::isFreed(); #endif GOMC_EVENT_STOP(1, GomcProfileEvent::DESTRUCTION); } void Simulation::RunSimulation(void) { GOMC_EVENT_START(1, GomcProfileEvent::MC_RUN); double startEnergy = system->potential.totalEnergy.total; if(totalSteps == 0) { for(int i = 0; i < (int) frameSteps.size(); i++) { if(i == 0) { cpu->Output(frameSteps[0] - 1); continue; } system->RecalculateTrajectory(set, i + 1); cpu->Output(frameSteps[i] - 1); } } for (ulong step = startStep; step < totalSteps; step++) { system->moveSettings.AdjustMoves(step); system->ChooseAndRunMove(step); cpu->Output(step); if((step + 1) == cpu->equilSteps) { double currEnergy = system->potential.totalEnergy.total; if(std::abs(currEnergy - startEnergy) > 1.0e+10) { printf("Info: Recalculating the total energies to insure the accuracy" " of the computed \n" " running energies.\n\n"); system->calcEwald->UpdateVectorsAndRecipTerms(true); system->potential = system->calcEnergy.SystemTotal(); } } #if GOMC_LIB_MPI // if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0) { int maxSwap = 0; /* Number of rounds of exchanges needed to deal with any multiple * exchanges. */ /* Where each replica ends up after the exchange attempt(s). */ /* The order in which multiple exchanges will occur. */ bool bThisReplicaExchanged = false; system->potential = system->calcEnergy.SystemTotal(); PTUtils->evaluateExchangeCriteria(step); PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged); PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged); system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup); if (staticValues->forcefield.ewald) { for(int box = 0; box < BOX_TOTAL; box++) { system->calcEwald->BoxReciprocalSums(box, system->coordinates, false); system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box, false); system->calcEwald->UpdateRecip(box); } } system->potential = system->calcEnergy.SystemTotal(); } #endif #ifndef NDEBUG if((step + 1) % 1000 == 0) RecalculateAndCheck(); #endif } GOMC_EVENT_STOP(1, GomcProfileEvent::MC_RUN); if(!RecalculateAndCheck()) { std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n"; } system->PrintAcceptance(); system->PrintTime(); #if GOMC_LIB_MPI if (staticValues->simEventFreq.parallelTemp) PTUtils->print_replica_exchange_statistics(ms->fplog); #endif } bool Simulation::RecalculateAndCheck(void) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); bool compare = true; compare &= num::approximatelyEqual(system->potential.totalEnergy.intraBond, pot.totalEnergy.intraBond, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.intraNonbond, pot.totalEnergy.intraNonbond, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.inter, pot.totalEnergy.inter, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.tc, pot.totalEnergy.tc, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.real, pot.totalEnergy.real, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.self, pot.totalEnergy.self, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.correction, pot.totalEnergy.correction, EPSILON); compare &= num::approximatelyEqual(system->potential.totalEnergy.recip, pot.totalEnergy.recip, EPSILON); if(!compare) { std::cout << "=================================================================\n" << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } return compare; }<|endoftext|>
<commit_before>// SolidTools.cpp // Copyright (c) 2010, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "SolidTools.h" #include "MarkedList.h" #include "HeeksConfig.h" #include "HeeksFrame.h" void GetSolidMenuTools(std::list<Tool*>* t_list){ // Tools for multiple selected items. bool solids_in_marked_list = false; // check to see what types have been marked std::list<HeeksObj*>::const_iterator It; for(It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++){ HeeksObj* object = *It; switch(object->GetType()){ case SolidType: case StlSolidType: solids_in_marked_list = true; } } if(solids_in_marked_list) { t_list->push_back(new SaveSolids); } } void SaveSolids::Run(){ std::list<HeeksObj*> objects; for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++){ HeeksObj* object = *It; switch(object->GetType()) { case SolidType: case StlSolidType: { objects.push_back(object); } break; } } if(objects.size() > 0) { wxString filepath(_T("")); { // get last used filepath HeeksConfig config; config.Read(_T("SolidExportFilepath"), &filepath, _T("")); } wxFileDialog fd(wxGetApp().m_frame, _("Save solid file"), wxEmptyString, filepath, wxString(_("Solid Files")) + _T(" |*.igs;*.iges;*.stp;*.step;*.stl;*.cpp;*.py|") + _("IGES files") + _T(" (*.igs *.iges)|*.igs;*.iges|") + _("STEP files") + _T(" (*.stp *.step)|*.stp;*.step|") + _("STL files") + _T(" (*.stl)|*.stl|") + _("CPP files") + _T(" (*.cpp)|*.cpp|") + _("OpenCAMLib python files") + _T(" (*.py)|*.py"), wxSAVE|wxOVERWRITE_PROMPT); fd.SetFilterIndex(1); if (fd.ShowModal() == wxID_CANCEL)return; filepath = fd.GetPath(); wxString wf(filepath); wf.LowerCase(); if(wf.EndsWith(_T(".stl"))) { wxGetApp().SaveSTLFile(objects, filepath); } else if(wf.EndsWith(_T(".cpp"))) { wxGetApp().SaveCPPFile(objects, filepath); } else if(wf.EndsWith(_T(".py"))) { wxGetApp().SavePyFile(objects, filepath); } else if(CShape::ExportSolidsFile(objects, filepath)) { } else { wxMessageBox(_("Invalid solid file type chosen")); return; } { // save last used filepath HeeksConfig config; config.Write(_T("SolidExportFilepath"), filepath); } } } <commit_msg>"Save Solids" dialog was showing "IGES files" intially, but it should have been showing "Solid Files".<commit_after>// SolidTools.cpp // Copyright (c) 2010, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "SolidTools.h" #include "MarkedList.h" #include "HeeksConfig.h" #include "HeeksFrame.h" void GetSolidMenuTools(std::list<Tool*>* t_list){ // Tools for multiple selected items. bool solids_in_marked_list = false; // check to see what types have been marked std::list<HeeksObj*>::const_iterator It; for(It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++){ HeeksObj* object = *It; switch(object->GetType()){ case SolidType: case StlSolidType: solids_in_marked_list = true; } } if(solids_in_marked_list) { t_list->push_back(new SaveSolids); } } void SaveSolids::Run(){ std::list<HeeksObj*> objects; for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++){ HeeksObj* object = *It; switch(object->GetType()) { case SolidType: case StlSolidType: { objects.push_back(object); } break; } } if(objects.size() > 0) { wxString filepath(_T("")); { // get last used filepath HeeksConfig config; config.Read(_T("SolidExportFilepath"), &filepath, _T("")); } wxFileDialog fd(wxGetApp().m_frame, _("Save solid file"), wxEmptyString, filepath, wxString(_("Solid Files")) + _T(" |*.igs;*.iges;*.stp;*.step;*.stl;*.cpp;*.py|") + _("IGES files") + _T(" (*.igs *.iges)|*.igs;*.iges|") + _("STEP files") + _T(" (*.stp *.step)|*.stp;*.step|") + _("STL files") + _T(" (*.stl)|*.stl|") + _("CPP files") + _T(" (*.cpp)|*.cpp|") + _("OpenCAMLib python files") + _T(" (*.py)|*.py"), wxSAVE|wxOVERWRITE_PROMPT); fd.SetFilterIndex(0); if (fd.ShowModal() == wxID_CANCEL)return; filepath = fd.GetPath(); wxString wf(filepath); wf.LowerCase(); if(wf.EndsWith(_T(".stl"))) { wxGetApp().SaveSTLFile(objects, filepath); } else if(wf.EndsWith(_T(".cpp"))) { wxGetApp().SaveCPPFile(objects, filepath); } else if(wf.EndsWith(_T(".py"))) { wxGetApp().SavePyFile(objects, filepath); } else if(CShape::ExportSolidsFile(objects, filepath)) { } else { wxMessageBox(_("Invalid solid file type chosen")); return; } { // save last used filepath HeeksConfig config; config.Write(_T("SolidExportFilepath"), filepath); } } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <Syncs/GameAgent.h> #include <Syncs/Interface.h> #include <Tasks/BasicTask.h> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10; agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10; agent.Process(agent.GetPlayer1(), BasicTask::DrawTask( Cards::GetInstance()->FindCardByName("Fiery War Axe"))); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); agent.Process(agent.GetPlayer2(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze"))); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); agent.Process( agent.GetPlayer1(), BasicTask::PlayCardTask(0)); EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, true); agent.Process( agent.GetPlayer2(), BasicTask::PlayCardTask(0, 0)); EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, false); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10; agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10; agent.Process(agent.GetPlayer1(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze"))); agent.Process(agent.GetPlayer1(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Ancestral Healing"))); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); auto minion = dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); minion->health -= 1; EXPECT_EQ(minion->health, 1); agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, 1)); EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); EXPECT_EQ(minion->health, 2); }<commit_msg>Comment some tests for merging<commit_after>#include "gtest/gtest.h" #include <Syncs/GameAgent.h> #include <Syncs/Interface.h> #include <Tasks/BasicTask.h> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10; agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10; agent.Process(agent.GetPlayer1(), BasicTask::DrawTask( Cards::GetInstance()->FindCardByName("Fiery War Axe"))); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); agent.Process(agent.GetPlayer2(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze"))); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); agent.Process( agent.GetPlayer1(), BasicTask::PlayCardTask(0)); EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, true); agent.Process( agent.GetPlayer2(), BasicTask::PlayCardTask(0, 0)); EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, false); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10; agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10; agent.Process(agent.GetPlayer1(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze"))); agent.Process(agent.GetPlayer1(), BasicTask::DrawTask(Cards::GetInstance()->FindCardByName( "Ancestral Healing"))); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); auto minion = dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); minion->health -= 1; EXPECT_EQ(minion->health, 1); agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, 1)); // EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); // EXPECT_EQ(minion->health, 2); }<|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/DoubleVertexRemover.hpp> #include <vlCore/Time.hpp> using namespace vl; namespace { class LessCompare { public: LessCompare(const Geometry* geom) { if (geom->vertexArray()) mAttribs.push_back(geom->vertexArray()); if (geom->normalArray()) mAttribs.push_back(geom->normalArray()); if (geom->colorArray()) mAttribs.push_back(geom->colorArray()); if (geom->secondaryColorArray()) mAttribs.push_back(geom->secondaryColorArray()); if (geom->fogCoordArray()) mAttribs.push_back(geom->fogCoordArray()); for(int i=0; i<VL_MAX_TEXTURE_UNITS; ++i) if (geom->texCoordArray(i)) mAttribs.push_back(geom->texCoordArray(i)); for(int i=0; i<geom->vertexAttribArrays()->size(); ++i) mAttribs.push_back(geom->vertexAttribArrays()->at(i)->data()); } bool operator()(u32 a, u32 b) const { for(unsigned i=0; i<mAttribs.size(); ++i) { int val = mAttribs[i]->compare(a,b); if (val != 0) return val < 0; } return false; } protected: std::vector< const ArrayAbstract* > mAttribs; }; class EqualsCompare { public: EqualsCompare(const Geometry* geom) { if (geom->vertexArray()) mAttribs.push_back(geom->vertexArray()); if (geom->normalArray()) mAttribs.push_back(geom->normalArray()); if (geom->colorArray()) mAttribs.push_back(geom->colorArray()); if (geom->secondaryColorArray()) mAttribs.push_back(geom->secondaryColorArray()); if (geom->fogCoordArray()) mAttribs.push_back(geom->fogCoordArray()); for(int i=0; i<VL_MAX_TEXTURE_UNITS; ++i) if (geom->texCoordArray(i)) mAttribs.push_back(geom->texCoordArray(i)); for(int i=0; i<geom->vertexAttribArrays()->size(); ++i) mAttribs.push_back(geom->vertexAttribArrays()->at(i)->data()); } bool operator()(u32 a, u32 b) const { for(unsigned i=0; i<mAttribs.size(); ++i) { if (mAttribs[i]->compare(a,b) != 0) return false; } return true; } protected: std::vector< const ArrayAbstract* > mAttribs; }; } //----------------------------------------------------------------------------- template<class T> ref<ArrayAbstract> VertexMapper::regenerateT(ArrayAbstract* data, const std::vector<u32>& map_new_to_old) const { ref<T> in_data = cast<T>(data); if (in_data) { ref<T> out_data = new T; out_data->resize(map_new_to_old.size()); for(unsigned i=0; i<map_new_to_old.size(); ++i) out_data->at(i) = in_data->at(map_new_to_old[i]); return out_data; } return NULL; } //----------------------------------------------------------------------------- ref<ArrayAbstract> VertexMapper::regenerate(ArrayAbstract* data, const std::vector<u32>& map_new_to_old) const { ref<ArrayAbstract> out_data; if ( (out_data = regenerateT<ArrayInt4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort4>(data, map_new_to_old)) ) return out_data; return NULL; } //----------------------------------------------------------------------------- void DoubleVertexRemover::removeDoubles(Geometry* geom) { Time timer; timer.start(); mMapNewToOld.clear(); mMapOldToNew.clear(); u32 vert_count = (u32)(geom->vertexArray() ? geom->vertexArray()->size() : geom->vertexAttribArray(VA_Position) ? geom->vertexAttribArray(VA_Position)->data()->size() : 0); VL_CHECK(vert_count); if (!vert_count) return; std::vector<u32> verti; verti.resize(vert_count); mMapOldToNew.resize(vert_count); for(u32 i=0; i<verti.size(); ++i) { verti[i] = i; mMapOldToNew[i] = 0xFFFFFFFF; } std::sort(verti.begin(), verti.end(), LessCompare(geom)); EqualsCompare equal_vertex(geom); mMapNewToOld.reserve(vert_count); u32 unique_vert_idx = 0; for(unsigned i=1; i<verti.size(); ++i) { if ( !equal_vertex(verti[unique_vert_idx], verti[i]) ) { for(unsigned j=unique_vert_idx; j<i; ++j) mMapOldToNew[verti[j]] = (u32)mMapNewToOld.size(); mMapNewToOld.push_back(verti[unique_vert_idx]); unique_vert_idx = i; } } for(unsigned j=unique_vert_idx; j<verti.size(); ++j) { mMapOldToNew[verti[j]] = (u32)mMapNewToOld.size(); mMapNewToOld.push_back(verti[unique_vert_idx]); } // regenerate vertices geom->regenerateVertices(mMapNewToOld); // regenerate DrawCall std::vector< ref<DrawCall> > draw_cmd; for(int idraw=0; idraw<geom->drawCalls()->size(); ++idraw) draw_cmd.push_back( geom->drawCalls()->at(idraw) ); geom->drawCalls()->clear(); for(u32 idraw=0; idraw<draw_cmd.size(); ++idraw) { ref<DrawElementsUInt> de = new DrawElementsUInt( draw_cmd[idraw]->primitiveType() ); geom->drawCalls()->push_back(de.get()); const u32 idx_count = draw_cmd[idraw]->countIndices(); de->indexBuffer()->resize(idx_count); u32 i=0; for(IndexIterator it = draw_cmd[idraw]->indexIterator(); it.hasNext(); it.next(), ++i) de->indexBuffer()->at(i) = mMapOldToNew[it.index()]; } Log::debug( Say("DoubleVertexRemover : time=%.2ns, verts=%n/%n, saved=%n, shrink=%.2n\n") << timer.elapsed() << mMapNewToOld.size() << verti.size() << verti.size() - mMapNewToOld.size() << (float)mMapNewToOld.size()/verti.size() ); } //----------------------------------------------------------------------------- <commit_msg>"shrink" -> "ratio"<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/DoubleVertexRemover.hpp> #include <vlCore/Time.hpp> using namespace vl; namespace { class LessCompare { public: LessCompare(const Geometry* geom) { if (geom->vertexArray()) mAttribs.push_back(geom->vertexArray()); if (geom->normalArray()) mAttribs.push_back(geom->normalArray()); if (geom->colorArray()) mAttribs.push_back(geom->colorArray()); if (geom->secondaryColorArray()) mAttribs.push_back(geom->secondaryColorArray()); if (geom->fogCoordArray()) mAttribs.push_back(geom->fogCoordArray()); for(int i=0; i<VL_MAX_TEXTURE_UNITS; ++i) if (geom->texCoordArray(i)) mAttribs.push_back(geom->texCoordArray(i)); for(int i=0; i<geom->vertexAttribArrays()->size(); ++i) mAttribs.push_back(geom->vertexAttribArrays()->at(i)->data()); } bool operator()(u32 a, u32 b) const { for(unsigned i=0; i<mAttribs.size(); ++i) { int val = mAttribs[i]->compare(a,b); if (val != 0) return val < 0; } return false; } protected: std::vector< const ArrayAbstract* > mAttribs; }; class EqualsCompare { public: EqualsCompare(const Geometry* geom) { if (geom->vertexArray()) mAttribs.push_back(geom->vertexArray()); if (geom->normalArray()) mAttribs.push_back(geom->normalArray()); if (geom->colorArray()) mAttribs.push_back(geom->colorArray()); if (geom->secondaryColorArray()) mAttribs.push_back(geom->secondaryColorArray()); if (geom->fogCoordArray()) mAttribs.push_back(geom->fogCoordArray()); for(int i=0; i<VL_MAX_TEXTURE_UNITS; ++i) if (geom->texCoordArray(i)) mAttribs.push_back(geom->texCoordArray(i)); for(int i=0; i<geom->vertexAttribArrays()->size(); ++i) mAttribs.push_back(geom->vertexAttribArrays()->at(i)->data()); } bool operator()(u32 a, u32 b) const { for(unsigned i=0; i<mAttribs.size(); ++i) { if (mAttribs[i]->compare(a,b) != 0) return false; } return true; } protected: std::vector< const ArrayAbstract* > mAttribs; }; } //----------------------------------------------------------------------------- template<class T> ref<ArrayAbstract> VertexMapper::regenerateT(ArrayAbstract* data, const std::vector<u32>& map_new_to_old) const { ref<T> in_data = cast<T>(data); if (in_data) { ref<T> out_data = new T; out_data->resize(map_new_to_old.size()); for(unsigned i=0; i<map_new_to_old.size(); ++i) out_data->at(i) = in_data->at(map_new_to_old[i]); return out_data; } return NULL; } //----------------------------------------------------------------------------- ref<ArrayAbstract> VertexMapper::regenerate(ArrayAbstract* data, const std::vector<u32>& map_new_to_old) const { ref<ArrayAbstract> out_data; if ( (out_data = regenerateT<ArrayInt4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayFloat1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayDouble1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUInt1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayInt1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort1>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUByte4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayByte4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayShort4>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort2>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort3>(data, map_new_to_old)) ) return out_data; else if ( (out_data = regenerateT<ArrayUShort4>(data, map_new_to_old)) ) return out_data; return NULL; } //----------------------------------------------------------------------------- void DoubleVertexRemover::removeDoubles(Geometry* geom) { Time timer; timer.start(); mMapNewToOld.clear(); mMapOldToNew.clear(); u32 vert_count = (u32)(geom->vertexArray() ? geom->vertexArray()->size() : geom->vertexAttribArray(VA_Position) ? geom->vertexAttribArray(VA_Position)->data()->size() : 0); VL_CHECK(vert_count); if (!vert_count) return; std::vector<u32> verti; verti.resize(vert_count); mMapOldToNew.resize(vert_count); for(u32 i=0; i<verti.size(); ++i) { verti[i] = i; mMapOldToNew[i] = 0xFFFFFFFF; } std::sort(verti.begin(), verti.end(), LessCompare(geom)); EqualsCompare equal_vertex(geom); mMapNewToOld.reserve(vert_count); u32 unique_vert_idx = 0; for(unsigned i=1; i<verti.size(); ++i) { if ( !equal_vertex(verti[unique_vert_idx], verti[i]) ) { for(unsigned j=unique_vert_idx; j<i; ++j) mMapOldToNew[verti[j]] = (u32)mMapNewToOld.size(); mMapNewToOld.push_back(verti[unique_vert_idx]); unique_vert_idx = i; } } for(unsigned j=unique_vert_idx; j<verti.size(); ++j) { mMapOldToNew[verti[j]] = (u32)mMapNewToOld.size(); mMapNewToOld.push_back(verti[unique_vert_idx]); } // regenerate vertices geom->regenerateVertices(mMapNewToOld); // regenerate DrawCall std::vector< ref<DrawCall> > draw_cmd; for(int idraw=0; idraw<geom->drawCalls()->size(); ++idraw) draw_cmd.push_back( geom->drawCalls()->at(idraw) ); geom->drawCalls()->clear(); for(u32 idraw=0; idraw<draw_cmd.size(); ++idraw) { ref<DrawElementsUInt> de = new DrawElementsUInt( draw_cmd[idraw]->primitiveType() ); geom->drawCalls()->push_back(de.get()); const u32 idx_count = draw_cmd[idraw]->countIndices(); de->indexBuffer()->resize(idx_count); u32 i=0; for(IndexIterator it = draw_cmd[idraw]->indexIterator(); it.hasNext(); it.next(), ++i) de->indexBuffer()->at(i) = mMapOldToNew[it.index()]; } Log::debug( Say("DoubleVertexRemover : time=%.2ns, verts=%n/%n, saved=%n, ratio=%.2n\n") << timer.elapsed() << mMapNewToOld.size() << verti.size() << verti.size() - mMapNewToOld.size() << (float)mMapNewToOld.size()/verti.size() ); } //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xalanc/XercesParserLiaison/XercesParserLiaison.hpp> #include <xalanc/XercesParserLiaison/XercesDOMSupport.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp> // HARNESS HEADERS... #include "xalanc/Harness/XalanXMLFileReporter.hpp" #include "xalanc/Harness/XalanFileUtility.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion(const XalanDOMString& currentFile) { MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (equals(currentFile, XalanDOMString(excludeStylesheets[i], mgr))) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString tmp("Failed to parse source document. ", mgr); tmp.append(xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, tmp ); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport(mgr); XercesParserLiaison theParserLiaison(mgr); int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( mgr, theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId(), mgr)); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString resultString("Failed to parse source document. ", mgr); resultString.append( xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, resultString); } return theResult; } int runTests( int argc, char* argv[]) { int theResult = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); try { XalanFileUtility h(mgr); // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan; // Get drive designation for final analysis and generate Unique name for results log. // XalanDOMString drive( mgr); // This is used to get stylesheet for final analysis h.getDrive(drive); const XalanDOMString resultFilePrefix("conf", mgr); // This & UniqRunid used for log file name. XalanDOMString UniqRunid( mgr); h.generateUniqRunid(UniqRunid); XalanDOMString resultsFile(drive, mgr); resultsFile += h.args.output; resultsFile += resultFilePrefix; resultsFile += UniqRunid; resultsFile += XalanFileUtility::s_xmlSuffix; // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(mgr, resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet", mgr); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; FileNameVectorType dirs(mgr); h.getDirectoryNames(h.args.base, dirs); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // XalanDOMString theOutputDir(mgr); theOutputDir = h.args.output; theOutputDir += currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; FileNameVectorType files(mgr); h.getTestFileNames(h.args.base, currentDir, true, files); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs(mgr); const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile)) continue; h.data.testOrFile = currentFile; XalanDOMString theXSLFile( h.args.base, mgr); theXSLFile += currentDir; theXSLFile += XalanFileUtility::s_pathSep; theXSLFile += currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; XalanDOMString theXMLFile(mgr); h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile(h.args.gold, mgr); theGoldFile += currentDir; theGoldFile += XalanFileUtility::s_pathSep; theGoldFile += currentFile; h.generateFileName(theGoldFile, "out", theGoldFile); XalanDOMString outbase (h.args.output, mgr); outbase += currentDir; outbase += XalanFileUtility::s_pathSep; outbase += currentFile; XalanDOMString theOutputFile(mgr); h.generateFileName(outbase, "out", theOutputFile); const XSLTInputSource xslInputSource(theXSLFile, mgr); const XSLTInputSource xmlInputSource(theXMLFile, mgr); const XSLTResultTarget resultFile(theOutputFile, mgr); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // cout << "Failed to parse stylesheet for " << currentFile << endl; h.data.fail += 1; XalanDOMString tmp("Failed to parse stylesheet. ", mgr); tmp += XalanDOMString(xalan.getLastError(), mgr); logFile.logErrorResult(currentFile, mgr); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { CharVectorType vect(mgr); TranscodeToLocalCodePage(h.args.sub, vect); cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize(); XalanTransformer::initialize(); theResult = runTests(argc, argv); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <commit_msg>Fix for building conf with fixed APIs<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xalanc/XercesParserLiaison/XercesParserLiaison.hpp> #include <xalanc/XercesParserLiaison/XercesDOMSupport.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp> // HARNESS HEADERS... #include "xalanc/Harness/XalanXMLFileReporter.hpp" #include "xalanc/Harness/XalanFileUtility.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion(const XalanDOMString& currentFile) { MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (equals(currentFile, XalanDOMString(excludeStylesheets[i], mgr))) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString tmp("Failed to parse source document. ", mgr); tmp.append(xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, tmp ); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport(mgr); XercesParserLiaison theParserLiaison(mgr); int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId(), mgr), mgr); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString resultString("Failed to parse source document. ", mgr); resultString.append( xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, resultString); } return theResult; } int runTests( int argc, char* argv[]) { int theResult = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); try { XalanFileUtility h(mgr); // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan; // Get drive designation for final analysis and generate Unique name for results log. // XalanDOMString drive( mgr); // This is used to get stylesheet for final analysis h.getDrive(drive); const XalanDOMString resultFilePrefix("conf", mgr); // This & UniqRunid used for log file name. XalanDOMString UniqRunid( mgr); h.generateUniqRunid(UniqRunid); XalanDOMString resultsFile(drive, mgr); resultsFile += h.args.output; resultsFile += resultFilePrefix; resultsFile += UniqRunid; resultsFile += XalanFileUtility::s_xmlSuffix; // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(mgr, resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet", mgr); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; FileNameVectorType dirs(mgr); h.getDirectoryNames(h.args.base, dirs); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // XalanDOMString theOutputDir(mgr); theOutputDir = h.args.output; theOutputDir += currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; FileNameVectorType files(mgr); h.getTestFileNames(h.args.base, currentDir, true, files); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs(mgr); const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile)) continue; h.data.testOrFile = currentFile; XalanDOMString theXSLFile( h.args.base, mgr); theXSLFile += currentDir; theXSLFile += XalanFileUtility::s_pathSep; theXSLFile += currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; XalanDOMString theXMLFile(mgr); h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile(h.args.gold, mgr); theGoldFile += currentDir; theGoldFile += XalanFileUtility::s_pathSep; theGoldFile += currentFile; h.generateFileName(theGoldFile, "out", theGoldFile); XalanDOMString outbase (h.args.output, mgr); outbase += currentDir; outbase += XalanFileUtility::s_pathSep; outbase += currentFile; XalanDOMString theOutputFile(mgr); h.generateFileName(outbase, "out", theOutputFile); const XSLTInputSource xslInputSource(theXSLFile, mgr); const XSLTInputSource xmlInputSource(theXMLFile, mgr); const XSLTResultTarget resultFile(theOutputFile, mgr); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // cout << "Failed to parse stylesheet for " << currentFile << endl; h.data.fail += 1; XalanDOMString tmp("Failed to parse stylesheet. ", mgr); tmp += XalanDOMString(xalan.getLastError(), mgr); logFile.logErrorResult(currentFile, mgr); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { CharVectorType vect(mgr); TranscodeToLocalCodePage(h.args.sub, vect); cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize(); XalanTransformer::initialize(); theResult = runTests(argc, argv); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 18029 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPlanarAngle.h" #include "mitkGeometry2D.h" mitk::PlanarAngle::PlanarAngle() : FEATURE_ID_ANGLE( this->AddFeature( "Angle", "deg" ) ) { // Start with two control points this->ResetNumberOfControlPoints( 2 ); this->SetNumberOfPolyLines(1); this->SetNumberOfHelperPolyLines(1); //m_PolyLines->InsertElement( 0, VertexContainerType::New()); //m_HelperPolyLines->InsertElement( 0, VertexContainerType::New()); m_HelperPolyLinesToBePainted->InsertElement( 0, false ); } mitk::PlanarAngle::~PlanarAngle() { } //void mitk::PlanarAngle::Initialize() //{ // // Default initialization of line control points // // mitk::Geometry2D *geometry2D = // dynamic_cast< mitk::Geometry2D * >( this->GetGeometry( 0 ) ); // // if ( geometry2D == NULL ) // { // MITK_ERROR << "Missing Geometry2D for PlanarLine"; // return; // } // // mitk::ScalarType width = geometry2D->GetBounds()[1]; // mitk::ScalarType height = geometry2D->GetBounds()[3]; // // mitk::Point2D &startPoint = m_ControlPoints->ElementAt( 0 ); // mitk::Point2D &endPoint = m_ControlPoints->ElementAt( 1 ); // // startPoint[0] = width / 2.0; // startPoint[1] = height / 2.0; // // endPoint[0] = startPoint[0] + 20.0; // endPoint[1] = startPoint[1] + 20.0; //} void mitk::PlanarAngle::GeneratePolyLine() { // Generate poly-line for angle for ( int i=0; i<this->GetNumberOfControlPoints(); i++ ) { mitk::PlanarFigure::PolyLineElement element( this->GetControlPoint( i ), i ); this->AppendPointToPolyLine( 0, element ); } //m_PolyLines->ElementAt( 0 )->Reserve( m_ControlPoints->Size() ); //for ( unsigned int i = 0; i < m_ControlPoints->Size(); ++i ) //{ // m_PolyLines->ElementAt( 0 )->ElementAt( i ) = m_ControlPoints->ElementAt( i ); //} } void mitk::PlanarAngle::GenerateHelperPolyLine(double mmPerDisplayUnit, unsigned int displayHeight) { // Generate helper-poly-line for angle if ( this->GetNumberOfControlPoints() < 3) { m_HelperPolyLinesToBePainted->SetElement(0, false); return; //We do not need to draw an angle as there are no two arms yet } m_HelperPolyLines->ElementAt( 0 )->Reserve( 3 ); const Point2D centerPoint = this->GetControlPoint( 1 ); const Point2D boundaryPointOne = this->GetControlPoint( 0 ); const Point2D boundaryPointTwo = this->GetControlPoint( 2 ); double radius = centerPoint.EuclideanDistanceTo( boundaryPointOne ); if ( radius > centerPoint.EuclideanDistanceTo( boundaryPointTwo ) ) { radius = centerPoint.EuclideanDistanceTo( boundaryPointTwo ); } //Fixed size radius depending on screen size for the angle double nonScalingRadius = displayHeight * mmPerDisplayUnit * 0.05; if (nonScalingRadius > radius) { m_HelperPolyLinesToBePainted->SetElement(0, false); return; //if the arc has a radius that is longer than the shortest arm it should not be painted } m_HelperPolyLinesToBePainted->SetElement(0, true); radius = nonScalingRadius; double angle = this->GetQuantity( FEATURE_ID_ANGLE ); //Determine from which arm the angle should be drawn Vector2D v0 = boundaryPointOne - centerPoint; Vector2D v1 = boundaryPointTwo - centerPoint; Vector2D v2; v2[0] = 1.0; v2[1] = 0.0; v0[0] = v0[0] * cos( 0.001 ) - v0[1] * sin( 0.001 ); //rotate one arm a bit v0[1] = v0[0] * sin( 0.001 ) + v0[1] * cos( 0.001 ); v0.Normalize(); v1.Normalize(); double testAngle = acos( v0 * v1 ); //if the rotated arm is closer to the other arm than before it is the one from which we start drawing //else we start drawing from the other arm (we want to draw in the mathematically positive direction) if( angle > testAngle ) { v1[0] = v0[0] * cos( -0.001 ) - v0[1] * sin( -0.001 ); v1[1] = v0[0] * sin( -0.001 ) + v0[1] * cos( -0.001 ); //We determine if the arm is mathematically forward or backward //assuming we rotate between -pi and pi if ( acos( v0 * v2 ) > acos ( v1 * v2 )) { testAngle = acos( v1 * v2 ); } else { testAngle = -acos( v1 * v2 ); } } else { v0[0] = v1[0] * cos( -0.001 ) - v1[1] * sin( -0.001 ); v0[1] = v1[0] * sin( -0.001 ) + v1[1] * cos( -0.001 ); //We determine if the arm is mathematically forward or backward //assuming we rotate between -pi and pi if ( acos( v0 * v2 ) < acos ( v1 * v2 )) { testAngle = acos( v1 * v2 ); } else { testAngle = -acos( v1 * v2 ); } } // Generate poly-line with 16 segments m_HelperPolyLines->ElementAt( 0 )->Reserve( 16 ); for ( int t = 0; t < 16; ++t ) { double alpha = (double) t * angle / 15.0 + testAngle; m_HelperPolyLines->ElementAt( 0 )->ElementAt( t )[0] = centerPoint[0] + radius * cos( alpha ); m_HelperPolyLines->ElementAt( 0 )->ElementAt( t )[1] = centerPoint[1] + radius * sin( alpha ); } } void mitk::PlanarAngle::EvaluateFeaturesInternal() { if ( this->GetNumberOfControlPoints() < 3 ) { // Angle not yet complete. return; } // Calculate angle between lines const Point2D &p0 = this->GetControlPoint( 0 ); const Point2D &p1 = this->GetControlPoint( 1 ); const Point2D &p2 = this->GetControlPoint( 2 ); Vector2D v0 = p1 - p0; Vector2D v1 = p1 - p2; v0.Normalize(); v1.Normalize(); double angle = acos( v0 * v1 ); this->SetQuantity( FEATURE_ID_ANGLE, angle ); } void mitk::PlanarAngle::PrintSelf( std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); } <commit_msg>adapting PlanarAngle to new point containers<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 18029 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPlanarAngle.h" #include "mitkGeometry2D.h" mitk::PlanarAngle::PlanarAngle() : FEATURE_ID_ANGLE( this->AddFeature( "Angle", "deg" ) ) { // Start with two control points this->ResetNumberOfControlPoints( 2 ); this->SetNumberOfPolyLines(1); this->SetNumberOfHelperPolyLines(1); m_HelperPolyLinesToBePainted->InsertElement( 0, false ); } mitk::PlanarAngle::~PlanarAngle() { } void mitk::PlanarAngle::GeneratePolyLine() { this->ClearPolyLines(); // Generate poly-line for angle for ( int i=0; i<this->GetNumberOfControlPoints(); i++ ) { mitk::PlanarFigure::PolyLineElement element( this->GetControlPoint( i ), i ); this->AppendPointToPolyLine( 0, element ); } } void mitk::PlanarAngle::GenerateHelperPolyLine(double mmPerDisplayUnit, unsigned int displayHeight) { // Generate helper-poly-line for angle if ( this->GetNumberOfControlPoints() < 3) { m_HelperPolyLinesToBePainted->SetElement(0, false); return; //We do not need to draw an angle as there are no two arms yet } this->ClearHelperPolyLines(); const Point2D centerPoint = this->GetControlPoint( 1 ); const Point2D boundaryPointOne = this->GetControlPoint( 0 ); const Point2D boundaryPointTwo = this->GetControlPoint( 2 ); double radius = centerPoint.EuclideanDistanceTo( boundaryPointOne ); if ( radius > centerPoint.EuclideanDistanceTo( boundaryPointTwo ) ) { radius = centerPoint.EuclideanDistanceTo( boundaryPointTwo ); } //Fixed size radius depending on screen size for the angle double nonScalingRadius = displayHeight * mmPerDisplayUnit * 0.05; if (nonScalingRadius > radius) { m_HelperPolyLinesToBePainted->SetElement(0, false); return; //if the arc has a radius that is longer than the shortest arm it should not be painted } m_HelperPolyLinesToBePainted->SetElement(0, true); radius = nonScalingRadius; double angle = this->GetQuantity( FEATURE_ID_ANGLE ); //Determine from which arm the angle should be drawn Vector2D v0 = boundaryPointOne - centerPoint; Vector2D v1 = boundaryPointTwo - centerPoint; Vector2D v2; v2[0] = 1.0; v2[1] = 0.0; v0[0] = v0[0] * cos( 0.001 ) - v0[1] * sin( 0.001 ); //rotate one arm a bit v0[1] = v0[0] * sin( 0.001 ) + v0[1] * cos( 0.001 ); v0.Normalize(); v1.Normalize(); double testAngle = acos( v0 * v1 ); //if the rotated arm is closer to the other arm than before it is the one from which we start drawing //else we start drawing from the other arm (we want to draw in the mathematically positive direction) if( angle > testAngle ) { v1[0] = v0[0] * cos( -0.001 ) - v0[1] * sin( -0.001 ); v1[1] = v0[0] * sin( -0.001 ) + v0[1] * cos( -0.001 ); //We determine if the arm is mathematically forward or backward //assuming we rotate between -pi and pi if ( acos( v0 * v2 ) > acos ( v1 * v2 )) { testAngle = acos( v1 * v2 ); } else { testAngle = -acos( v1 * v2 ); } } else { v0[0] = v1[0] * cos( -0.001 ) - v1[1] * sin( -0.001 ); v0[1] = v1[0] * sin( -0.001 ) + v1[1] * cos( -0.001 ); //We determine if the arm is mathematically forward or backward //assuming we rotate between -pi and pi if ( acos( v0 * v2 ) < acos ( v1 * v2 )) { testAngle = acos( v1 * v2 ); } else { testAngle = -acos( v1 * v2 ); } } // Generate poly-line with 16 segments for ( int t = 0; t < 16; ++t ) { double alpha = (double) t * angle / 15.0 + testAngle; Point2D polyLinePoint; polyLinePoint[0] = centerPoint[0] + radius * cos( alpha ); polyLinePoint[1] = centerPoint[1] + radius * sin( alpha ); AppendPointToHelperPolyLine( 0, PolyLineElement( polyLinePoint, t ) ); } } void mitk::PlanarAngle::EvaluateFeaturesInternal() { if ( this->GetNumberOfControlPoints() < 3 ) { // Angle not yet complete. return; } // Calculate angle between lines const Point2D &p0 = this->GetControlPoint( 0 ); const Point2D &p1 = this->GetControlPoint( 1 ); const Point2D &p2 = this->GetControlPoint( 2 ); Vector2D v0 = p1 - p0; Vector2D v1 = p1 - p2; v0.Normalize(); v1.Normalize(); double angle = acos( v0 * v1 ); this->SetQuantity( FEATURE_ID_ANGLE, angle ); } void mitk::PlanarAngle::PrintSelf( std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); } <|endoftext|>
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <glog/logging.h> #include "common/file/recordio/record_io.h" RecordWriter::RecordWriter() {} RecordWriter::~RecordWriter() {} bool RecordWriter::Reset(FileStream *file) { DCHECK(file != NULL); m_file = file; return true; } bool RecordWriter::WriteMessage(const ::google::protobuf::Message& message) { std::string output; if (!message.IsInitialized()) { LOG(WARNING) << "Missing required fields." << message.InitializationErrorString(); return false; } if (!message.AppendToString(&output)) { return false; } if (!WriteRecord(output.data(), output.size())) { return false; } return true; } bool RecordWriter::WriteRecord(const char *data, uint32_t size) { if (!Write(reinterpret_cast<char*>(&size), sizeof(size))) { return false; } if (!Write(data, size)) { return false; } return true; } bool RecordWriter::WriteRecord(const std::string& data) { return WriteRecord(data.data(), data.size()); } bool RecordWriter::Write(const char *data, uint32_t size) { uint32_t write_size = 0; while (write_size < size) { int32_t ret = m_file->Write(data + write_size, size - write_size); if (ret == -1) { LOG(ERROR) << "RecordWriter error."; return false; } write_size += ret; } m_file->Flush(); return true; } RecordReader::RecordReader() : m_buffer_size(1 * 1024 * 1024) { m_buffer.reset(new char[m_buffer_size]); } RecordReader::~RecordReader() { } bool RecordReader::Reset(FileStream *file) { DCHECK(file != NULL); m_file = file; if (-1 == m_file->Seek(0, SEEK_END)) { LOG(ERROR) << "RecordReader Reset error."; return false; } m_file_size = m_file->Tell(); if (-1 == m_file->Seek(0, SEEK_SET)) { LOG(ERROR) << "RecordReader Reset error."; return false; } return true; } int RecordReader::Next() { // read size int64_t ret = m_file->Tell(); if (ret == -1) { LOG(ERROR) << "Tell error."; return -1; } if (ret == m_file_size) { return 0; } else if (m_file_size - ret >= static_cast<int64_t>(sizeof(m_data_size))) { // NO_LINT if (!Read(reinterpret_cast<char*>(&m_data_size), sizeof(m_data_size))) { LOG(ERROR) << "Read size error."; return -1; } } // read data ret = m_file->Tell(); if (ret == -1) { LOG(ERROR) << "Tell error."; return -1; } if (ret >= m_file_size && m_data_size != 0) { LOG(ERROR) << "read error."; return -1; } else if (m_file_size - ret >= m_data_size) { // NO_LINT if (m_data_size > m_buffer_size) { while (m_data_size > m_buffer_size) { m_buffer_size *= 2; } m_buffer.reset(new char[m_buffer_size]); } if (!Read(m_buffer.get(), m_data_size)) { LOG(ERROR) << "Read data error."; return -1; } } return 1; } bool RecordReader::ReadMessage(::google::protobuf::Message *message) { std::string str(m_buffer.get(), m_data_size); if (!message->ParseFromArray(m_buffer.get(), m_data_size)) { LOG(WARNING) << "Missing required fields."; return false; } return true; } bool RecordReader::ReadNextMessage(::google::protobuf::Message *message) { while (Next() == 1) { std::string str(m_buffer.get(), m_data_size); if (message->ParseFromArray(m_buffer.get(), m_data_size)) { return true; } } return false; } bool RecordReader::ReadRecord(const char **data, uint32_t *size) { *data = m_buffer.get(); *size = m_data_size; return true; } bool RecordReader::ReadRecord(std::string *data) { data->assign(m_buffer.get()); return true; } bool RecordReader::Read(char *data, uint32_t size) { // Read uint32_t read_size = 0; while (read_size < size) { int64_t ret = m_file->Read(data + read_size, size - read_size); if (ret == -1) { LOG(ERROR) << "Read error."; return false; } read_size += ret; } return true; } <commit_msg>fix bug of record_io: check invalid size of data recrod<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <glog/logging.h> #include "common/file/recordio/record_io.h" RecordWriter::RecordWriter() {} RecordWriter::~RecordWriter() {} bool RecordWriter::Reset(FileStream *file) { DCHECK(file != NULL); m_file = file; return true; } bool RecordWriter::WriteMessage(const ::google::protobuf::Message& message) { std::string output; if (!message.IsInitialized()) { LOG(WARNING) << "Missing required fields." << message.InitializationErrorString(); return false; } if (!message.AppendToString(&output)) { return false; } if (!WriteRecord(output.data(), output.size())) { return false; } return true; } bool RecordWriter::WriteRecord(const char *data, uint32_t size) { if (!Write(reinterpret_cast<char*>(&size), sizeof(size))) { return false; } if (!Write(data, size)) { return false; } return true; } bool RecordWriter::WriteRecord(const std::string& data) { return WriteRecord(data.data(), data.size()); } bool RecordWriter::Write(const char *data, uint32_t size) { uint32_t write_size = 0; while (write_size < size) { int32_t ret = m_file->Write(data + write_size, size - write_size); if (ret == -1) { LOG(ERROR) << "RecordWriter error."; return false; } write_size += ret; } m_file->Flush(); return true; } RecordReader::RecordReader() : m_buffer_size(1 * 1024 * 1024) { m_buffer.reset(new char[m_buffer_size]); } RecordReader::~RecordReader() { } bool RecordReader::Reset(FileStream *file) { DCHECK(file != NULL); m_file = file; if (-1 == m_file->Seek(0, SEEK_END)) { LOG(ERROR) << "RecordReader Reset error."; return false; } m_file_size = m_file->Tell(); if (-1 == m_file->Seek(0, SEEK_SET)) { LOG(ERROR) << "RecordReader Reset error."; return false; } return true; } int RecordReader::Next() { // read size int64_t ret = m_file->Tell(); if (ret == -1) { LOG(ERROR) << "Tell error."; return -1; } if (ret == m_file_size) { return 0; } else if (m_file_size - ret >= static_cast<int64_t>(sizeof(m_data_size))) { // NO_LINT if (!Read(reinterpret_cast<char*>(&m_data_size), sizeof(m_data_size))) { LOG(ERROR) << "Read size error."; return -1; } } // read data ret = m_file->Tell(); if (ret == -1) { LOG(ERROR) << "Tell error."; return -1; } if (ret >= m_file_size && m_data_size != 0) { LOG(ERROR) << "read error."; return -1; } else if (m_file_size - ret >= m_data_size) { // NO_LINT if (m_data_size > m_buffer_size) { while (m_data_size > m_buffer_size) { m_buffer_size *= 2; } m_buffer.reset(new char[m_buffer_size]); } if (!Read(m_buffer.get(), m_data_size)) { LOG(ERROR) << "Read data error."; return -1; } } else { LOG(ERROR) << "m_data_size of current record is invalid: " << m_data_size << " bigger than " << (m_file_size - ret); return -1; } return 1; } bool RecordReader::ReadMessage(::google::protobuf::Message *message) { std::string str(m_buffer.get(), m_data_size); if (!message->ParseFromArray(m_buffer.get(), m_data_size)) { LOG(WARNING) << "Missing required fields."; return false; } return true; } bool RecordReader::ReadNextMessage(::google::protobuf::Message *message) { while (Next() == 1) { std::string str(m_buffer.get(), m_data_size); if (message->ParseFromArray(m_buffer.get(), m_data_size)) { return true; } } return false; } bool RecordReader::ReadRecord(const char **data, uint32_t *size) { *data = m_buffer.get(); *size = m_data_size; return true; } bool RecordReader::ReadRecord(std::string *data) { data->assign(m_buffer.get()); return true; } bool RecordReader::Read(char *data, uint32_t size) { // Read uint32_t read_size = 0; while (read_size < size) { int64_t ret = m_file->Read(data + read_size, size - read_size); if (ret == -1) { LOG(ERROR) << "Read error."; return false; } read_size += ret; } return true; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of meegotouch-controlpanelsoundsettingsapplet. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "alerttoneappletwidget.h" #include "profilewidgetcontainer.h" #include <QSet> #include <QVariant> #include <MGConfItem> #include <MLabel> #include <QGraphicsLinearLayout> #include <MSeparator> #include <MApplicationPage> #include <QSystemDeviceInfo> #include <QTimer> using namespace QtMobility; #include "soundsettingsutils.h" #include "alerttonewidget.h" #include "gconfstringcombo.h" #include "profileintcombo.h" #include "profiledatainterface.h" #include "profilecontainer.h" static const QString keyboardGConfKey ("/meegotouch/settings/has_keyboard"); #include <MWidgetCreator> M_REGISTER_WIDGET_NO_CREATE(AlertToneAppletWidget) #include "../styles.h" //#define DEBUG #define WARNING #include "../debug.h" #include <time.h> /****************************************************************************** * Helper functions. */ static MWidgetController * createEmptyContainer( QGraphicsWidget *parent, QGraphicsLinearLayout **layout) { MWidgetController *container = new MWidgetController (parent); container->setContentsMargins (0., 0., 0., 0.); (*layout) = new QGraphicsLinearLayout (Qt::Vertical); (*layout)->setContentsMargins (0., 0., 0., 0.); container->setLayout (*layout); return container; } static void addSubTitle ( QGraphicsWidget *parent, QGraphicsLinearLayout *targetLayout, const QString &subTitle) { MWidgetController *container; QGraphicsLinearLayout *layout; MLabel *label; MSeparator *separator; container = new MWidgetController (parent); container->setContentsMargins (0., 0., 0., 0.); container->setStyleName (SUBTITLE_PANEL_STYLE_NAME); layout = new QGraphicsLinearLayout (Qt::Horizontal); layout->setContentsMargins (0., 0., 0., 0.); layout->setSpacing (0.); /* * */ separator = new MSeparator; separator->setStyleName (SUBTITLE_DIVIDER_STYLE_NAME); /* * */ label = new MLabel (subTitle); label->setStyleName (SUBTITLE_LABEL_STYLE_NAME); layout->addItem (separator); layout->setStretchFactor (separator, 2); layout->addItem (label); layout->setAlignment (label, Qt::AlignLeft); layout->setStretchFactor (label, 0); container->setLayout (layout); targetLayout->addItem (container); } static MLabel * addTitleLabel ( QGraphicsWidget *parent, QGraphicsLinearLayout *targetLayout, const char *labelStyleName) { Q_UNUSED (parent); MLabel *label; label = new MLabel; label->setStyleName (labelStyleName); targetLayout->addItem (label); return label; } /****************************************************************************** * AlertToneAppletWidget implementation */ AlertToneAppletWidget::AlertToneAppletWidget ( QList<AlertTone *> alertTones, QGraphicsWidget *parent): DcpStylableWidget (parent), m_alertTones(alertTones), m_ProfileIf (new ProfileDataInterface), m_tones (0), m_feedback (0), m_profileWidget (0) { setContentsMargins (0., 0., 0., 0.); /* * This should be called later, not from the constructor. */ createContents (); } AlertToneAppletWidget::~AlertToneAppletWidget () { /* * Removing the unused files. This is not the best place, but we have no * business-logic, so we do it here. */ QSet<QString> files; for (int n = 0; n < m_alertTones.size(); ++n) { files += m_alertTones[n]->fileName(); } SoundSettings::removeUnusedFiles (files); delete m_ProfileIf; m_ProfileIf = 0; } void AlertToneAppletWidget::delayedInit () { DEBUG_CLOCK_START; m_profileWidget->init (); DEBUG_CLOCK_END("Initializing slider."); } void AlertToneAppletWidget::createContents () { DEBUG_CLOCK_START; QGraphicsLinearLayout *layout; MLabel *label; setContentsMargins (0., 0., 0., 0); layout = new QGraphicsLinearLayout (Qt::Vertical); layout->setContentsMargins (0., 0., 0., 0.); layout->setSpacing (0.); setLayout (layout); /* * The main title */ #ifndef MEEGO label = addTitleLabel ( this, layout, APP_TITLE_LABEL_STYLE_NAME); //% "Alert tones" label->setText(qtTrId("qtn_sond_sounds")); #endif DEBUG_CLOCK_END("First widgets."); SYS_DEBUG ("%s: constructing volumeExtension", SYS_TIME_STR); m_profileWidget = new ProfileWidgetContainer (this); layout->addItem (m_profileWidget); SYS_DEBUG ("%s DONE: constructing volumeExtension", SYS_TIME_STR); DEBUG_CLOCK_END("volume extension"); /* * A subtitle that shows 'Profile vibration' */ addSubTitle ( this, layout, //% "Vibration profile" qtTrId("qtn_prof_vibration")); /* * Add the profie vibration switches... */ createProfileSwitches (layout, this); /* * A secondary title, it says 'Tones' */ addSubTitle ( this, layout, //% "Alert tones" qtTrId("qtn_sond_event_tones")); /* * A list with the sound file setting widgets. */ m_tones = createAlertTonesList (this); layout->addItem (m_tones); /* * An other secondary title, that says 'Feedback'. */ addSubTitle ( this, layout, //% "Feedback" qtTrId("qtn_sond_feedback")); /* * The list with the feedback setting widgets. */ m_feedback = createFeedbackList (this); layout->addItem (m_feedback); retranslateUi (); DEBUG_CLOCK_END("Whole content"); } void AlertToneAppletWidget::createProfileSwitches ( QGraphicsLinearLayout *layout, QGraphicsWidget *parent) { Q_UNUSED (parent); QList<ProfileDataInterface::ProfileData> profileDataList = m_ProfileIf->getProfilesData(); for (int i = 0; i < profileDataList.size(); ++i) { ProfileDataInterface::ProfileData d = profileDataList[i]; ProfileContainer *widget; widget = new ProfileContainer ( d.profileId, d.profileName, d.vibrationEnabled); // For testability driver: set some object name... widget->setObjectName (ProfileDataInterface::mapId (d.profileId)); connect (widget, SIGNAL (toggled(bool)), this, SLOT (vibrationChanged(bool))); layout->addItem (widget); } } void AlertToneAppletWidget::vibrationChanged ( bool enabled) { //NOTE: MButton->isChecked() method returns the state before the // press at this point ProfileContainer *profile = static_cast<ProfileContainer*> (this->sender ()); m_ProfileIf->setVibration (profile->id (), enabled); } MWidgetController * AlertToneAppletWidget::createFeedbackList( QGraphicsWidget *parent) { MWidgetController *container; QGraphicsLinearLayout *layout; container = createEmptyContainer (parent, &layout); ProfileIntCombo *picombo = 0; MGConfItem hkbItem (keyboardGConfKey); if (hkbItem.value ().isNull ()) { /* * Lets cache this value in GConf, as it is faster than querying it * XXX: This doesn't help on the first opening time */ QSystemDeviceInfo devInfo; QSystemDeviceInfo::KeyboardTypeFlags keybFlags = devInfo.keyboardTypes (); hkbItem.set (false); if ((keybFlags & QSystemDeviceInfo::FlipKeyboard) || (keybFlags & QSystemDeviceInfo::FullQwertyKeyboard) || (keybFlags & QSystemDeviceInfo::HalfQwertyKeyboard) || (keybFlags & QSystemDeviceInfo::ITUKeypad)) { /* has hardware keyboard */ hkbItem.set (true); } } /* * Show the keyboard tones only if the device have hardware keyboard */ if (hkbItem.value ().toBool ()) { picombo = new ProfileIntCombo ( "keypad.sound.level", true, container); picombo->setObjectName("ProfileIntCombo_keypad.sound.level"); picombo->setStyleName ("CommonComboBoxInverted"); layout->addItem (picombo); } picombo = new ProfileIntCombo ("system.sound.level", true, container); picombo->setObjectName("ProfileIntCombo_system.sound.level"); picombo->setStyleName ("CommonComboBoxInverted"); layout->addItem (picombo); GConfStringCombo *combo = new GConfStringCombo( "/meegotouch/input_feedback/volume/priority2/pulse", QStringList() << "off" << "low" << "medium" << "high", container); combo->setObjectName("GConfStringCombo_pulse"); combo->setStyleName ("CommonComboBoxInverted"); layout->addItem (combo); combo = new GConfStringCombo( "/meegotouch/input_feedback/volume/priority2/vibra", QStringList() << "off" << "low" << "medium" << "high", container); combo->setObjectName("GConfStringCombo_vibra"); combo->setStyleName ("CommonComboBoxInverted"); layout->addItem (combo); container->setObjectName("MConcreateAlertTonePreviewtainer_feedback"); container->setStyleName ("CommonLargePanelInverted"); return container; } MWidgetController * AlertToneAppletWidget::createAlertTonesList (QGraphicsWidget *parent) { MWidgetController *container; QGraphicsLinearLayout *layout; AlertToneWidget *alertToneWidget; container = createEmptyContainer (parent, &layout); /* * And then the list... */ for (int i = 0; i < m_alertTones.size (); i++) { alertToneWidget = new AlertToneWidget ( m_alertTones[i], i, container); alertToneWidget->setObjectName ( "AlertToneWidget_" + m_alertTones[i]->key()); // connect the widgets showWidget signal // If we send the changeWidget() signal, DCP will show the widget in an // MApplicationPage, if we send the showWidget, SoundSettingsApplet will // show the widget in a sheet. connect (alertToneWidget, SIGNAL (showWidget (int)), this, SIGNAL (showWidget (int))); layout->addItem (alertToneWidget); } container->setObjectName ("MWidgetController_tones"); container->setStyleName ("CommonLargePanelInverted"); return container; } /* * This virtual method is called when the MApplicationPage for the widget is * already there, so we can initialize it. */ void AlertToneAppletWidget::polishEvent () { DEBUG_CLOCK_START; QGraphicsWidget *parent; MApplicationPage *page = 0; // testing //m_volumeExtension->init (); /* * We need to find the MApplicationPage among our parents. */ parent = parentWidget(); while (parent) { page = qobject_cast <MApplicationPage *>(parent); if (page) break; parent = parent->parentWidget(); } if (page) page->setComponentsDisplayMode ( MApplicationPage::HomeButton, MApplicationPageModel::Hide); QTimer::singleShot (1000, this, SLOT (delayedInit ())); DEBUG_CLOCK_END("polish event"); } <commit_msg>Changes: trying...<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of meegotouch-controlpanelsoundsettingsapplet. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "alerttoneappletwidget.h" #include "profilewidgetcontainer.h" #include <QSet> #include <QVariant> #include <MGConfItem> #include <MLabel> #include <QGraphicsLinearLayout> #include <MSeparator> #include <MApplicationPage> #include <QSystemDeviceInfo> #include <QTimer> using namespace QtMobility; #include "soundsettingsutils.h" #include "alerttonewidget.h" #include "gconfstringcombo.h" #include "profileintcombo.h" #include "profiledatainterface.h" #include "profilecontainer.h" static const QString keyboardGConfKey ("/meegotouch/settings/has_keyboard"); #include <MWidgetCreator> M_REGISTER_WIDGET_NO_CREATE(AlertToneAppletWidget) #include "../styles.h" #define DEBUG #define WARNING #include "../debug.h" #include <time.h> /****************************************************************************** * Helper functions. */ static MWidgetController * createEmptyContainer( QGraphicsWidget *parent, QGraphicsLinearLayout **layout) { MWidgetController *container = new MWidgetController (parent); container->setContentsMargins (0., 0., 0., 0.); (*layout) = new QGraphicsLinearLayout (Qt::Vertical); (*layout)->setContentsMargins (0., 0., 0., 0.); container->setLayout (*layout); return container; } static void addSubTitle ( QGraphicsWidget *parent, QGraphicsLinearLayout *targetLayout, const QString &subTitle) { MWidgetController *container; QGraphicsLinearLayout *layout; MLabel *label; MSeparator *separator; container = new MWidgetController (parent); container->setContentsMargins (0., 0., 0., 0.); container->setStyleName (SUBTITLE_PANEL_STYLE_NAME); layout = new QGraphicsLinearLayout (Qt::Horizontal); layout->setContentsMargins (0., 0., 0., 0.); layout->setSpacing (0.); /* * */ separator = new MSeparator; separator->setStyleName (SUBTITLE_DIVIDER_STYLE_NAME); /* * */ label = new MLabel (subTitle); label->setStyleName (SUBTITLE_LABEL_STYLE_NAME); layout->addItem (separator); layout->setStretchFactor (separator, 2); layout->addItem (label); layout->setAlignment (label, Qt::AlignLeft); layout->setStretchFactor (label, 0); container->setLayout (layout); targetLayout->addItem (container); } static MLabel * addTitleLabel ( QGraphicsWidget *parent, QGraphicsLinearLayout *targetLayout, const char *labelStyleName) { Q_UNUSED (parent); MLabel *label; label = new MLabel; label->setStyleName (labelStyleName); targetLayout->addItem (label); return label; } /****************************************************************************** * AlertToneAppletWidget implementation */ AlertToneAppletWidget::AlertToneAppletWidget ( QList<AlertTone *> alertTones, QGraphicsWidget *parent): DcpStylableWidget (parent), m_alertTones(alertTones), m_ProfileIf (new ProfileDataInterface), m_tones (0), m_feedback (0), m_profileWidget (0) { setContentsMargins (0., 0., 0., 0.); /* * This should be called later, not from the constructor. */ createContents (); } AlertToneAppletWidget::~AlertToneAppletWidget () { /* * Removing the unused files. This is not the best place, but we have no * business-logic, so we do it here. */ QSet<QString> files; for (int n = 0; n < m_alertTones.size(); ++n) { files += m_alertTones[n]->fileName(); } SoundSettings::removeUnusedFiles (files); delete m_ProfileIf; m_ProfileIf = 0; } void AlertToneAppletWidget::delayedInit () { DEBUG_CLOCK_START; m_profileWidget->init (); DEBUG_CLOCK_END("Initializing slider."); } void AlertToneAppletWidget::createContents () { DEBUG_CLOCK_START; QGraphicsLinearLayout *layout; MLabel *label; setContentsMargins (0., 0., 0., 0); layout = new QGraphicsLinearLayout (Qt::Vertical); layout->setContentsMargins (0., 0., 0., 0.); layout->setSpacing (0.); setLayout (layout); /* * The main title */ #ifndef MEEGO label = addTitleLabel ( this, layout, APP_TITLE_LABEL_STYLE_NAME); //% "Alert tones" label->setText(qtTrId("qtn_sond_sounds")); #endif DEBUG_CLOCK_END("First widgets."); SYS_DEBUG ("%s: constructing volumeExtension", SYS_TIME_STR); m_profileWidget = new ProfileWidgetContainer (this); layout->addItem (m_profileWidget); SYS_DEBUG ("%s DONE: constructing volumeExtension", SYS_TIME_STR); DEBUG_CLOCK_END("volume extension"); /* * A subtitle that shows 'Profile vibration' */ addSubTitle ( this, layout, //% "Vibration profile" qtTrId("qtn_prof_vibration")); /* * Add the profie vibration switches... */ createProfileSwitches (layout, this); /* * A secondary title, it says 'Tones' */ addSubTitle ( this, layout, //% "Alert tones" qtTrId("qtn_sond_event_tones")); /* * A list with the sound file setting widgets. */ m_tones = createAlertTonesList (this); layout->addItem (m_tones); /* * An other secondary title, that says 'Feedback'. */ addSubTitle ( this, layout, //% "Feedback" qtTrId("qtn_sond_feedback")); /* * The list with the feedback setting widgets. */ m_feedback = createFeedbackList (this); layout->addItem (m_feedback); retranslateUi (); DEBUG_CLOCK_END("Whole content"); } void AlertToneAppletWidget::createProfileSwitches ( QGraphicsLinearLayout *layout, QGraphicsWidget *parent) { Q_UNUSED (parent); QList<ProfileDataInterface::ProfileData> profileDataList = m_ProfileIf->getProfilesData(); for (int i = 0; i < profileDataList.size(); ++i) { ProfileDataInterface::ProfileData d = profileDataList[i]; ProfileContainer *widget; widget = new ProfileContainer ( d.profileId, d.profileName, d.vibrationEnabled); // For testability driver: set some object name... widget->setObjectName (ProfileDataInterface::mapId (d.profileId)); connect (widget, SIGNAL (toggled(bool)), this, SLOT (vibrationChanged(bool))); layout->addItem (widget); } } void AlertToneAppletWidget::vibrationChanged ( bool enabled) { //NOTE: MButton->isChecked() method returns the state before the // press at this point ProfileContainer *profile = static_cast<ProfileContainer*> (this->sender ()); m_ProfileIf->setVibration (profile->id (), enabled); } MWidgetController * AlertToneAppletWidget::createFeedbackList( QGraphicsWidget *parent) { MWidgetController *container; QGraphicsLinearLayout *layout; container = createEmptyContainer (parent, &layout); ProfileIntCombo *picombo = 0; MGConfItem hkbItem (keyboardGConfKey); if (hkbItem.value ().isNull ()) { /* * Lets cache this value in GConf, as it is faster than querying it * XXX: This doesn't help on the first opening time */ QSystemDeviceInfo devInfo; QSystemDeviceInfo::KeyboardTypeFlags keybFlags = devInfo.keyboardTypes (); hkbItem.set (false); if ((keybFlags & QSystemDeviceInfo::FlipKeyboard) || (keybFlags & QSystemDeviceInfo::FullQwertyKeyboard) || (keybFlags & QSystemDeviceInfo::HalfQwertyKeyboard) || (keybFlags & QSystemDeviceInfo::ITUKeypad)) { /* has hardware keyboard */ hkbItem.set (true); } } /* * Show the keyboard tones only if the device have hardware keyboard */ if (hkbItem.value ().toBool ()) { picombo = new ProfileIntCombo ( "keypad.sound.level", true, container); picombo->setObjectName("ProfileIntCombo_keypad.sound.level"); picombo->setStyleName ("CommonComboBoxInverted"); layout->addItem (picombo); } picombo = new ProfileIntCombo ("system.sound.level", true, container); picombo->setObjectName("ProfileIntCombo_system.sound.level"); picombo->setStyleName ("CommonComboBoxInverted"); layout->addItem (picombo); GConfStringCombo *combo = new GConfStringCombo( "/meegotouch/input_feedback/volume/priority2/pulse", QStringList() << "off" << "low" << "medium" << "high", container); combo->setObjectName("GConfStringCombo_pulse"); combo->setStyleName ("CommonComboBoxInverted"); layout->addItem (combo); combo = new GConfStringCombo( "/meegotouch/input_feedback/volume/priority2/vibra", QStringList() << "off" << "low" << "medium" << "high", container); combo->setObjectName("GConfStringCombo_vibra"); combo->setStyleName ("CommonComboBoxInverted"); layout->addItem (combo); container->setObjectName("MConcreateAlertTonePreviewtainer_feedback"); container->setStyleName ("CommonLargePanelInverted"); return container; } MWidgetController * AlertToneAppletWidget::createAlertTonesList (QGraphicsWidget *parent) { MWidgetController *container; QGraphicsLinearLayout *layout; AlertToneWidget *alertToneWidget; container = createEmptyContainer (parent, &layout); /* * And then the list... */ for (int i = 0; i < m_alertTones.size (); i++) { alertToneWidget = new AlertToneWidget ( m_alertTones[i], i, container); alertToneWidget->setObjectName ( "AlertToneWidget_" + m_alertTones[i]->key()); // connect the widgets showWidget signal // If we send the changeWidget() signal, DCP will show the widget in an // MApplicationPage, if we send the showWidget, SoundSettingsApplet will // show the widget in a sheet. connect (alertToneWidget, SIGNAL (showWidget (int)), this, SIGNAL (showWidget (int))); layout->addItem (alertToneWidget); } container->setObjectName ("MWidgetController_tones"); container->setStyleName ("CommonLargePanelInverted"); return container; } /* * This virtual method is called when the MApplicationPage for the widget is * already there, so we can initialize it. */ void AlertToneAppletWidget::polishEvent () { DEBUG_CLOCK_START; QGraphicsWidget *parent; MApplicationPage *page = 0; // testing //m_volumeExtension->init (); /* * We need to find the MApplicationPage among our parents. */ parent = parentWidget(); while (parent) { page = qobject_cast <MApplicationPage *>(parent); if (page) break; parent = parent->parentWidget(); } if (page) page->setComponentsDisplayMode ( MApplicationPage::HomeButton, MApplicationPageModel::Hide); /* * XXX: FIXME: TODO: adjust this delay to make it best */ QTimer::singleShot (500, this, SLOT (delayedInit ())); DEBUG_CLOCK_END("polish event"); } <|endoftext|>
<commit_before>#include "recent_file_cache.h" #include <cerrno> #include <chrono> #include <cstdio> #include <iomanip> #include <iostream> #include <memory> #include <queue> #include <sstream> #include <string> #include <sys/stat.h> #include <unordered_map> #include <utility> #include <vector> #include "../../helper/common.h" #include "../../log.h" using std::chrono::minutes; using std::chrono::steady_clock; using std::chrono::time_point; using std::endl; using std::move; using std::ostream; using std::ostringstream; using std::pair; using std::queue; using std::shared_ptr; using std::static_pointer_cast; using std::string; using std::vector; // If the cache contains more than this many entries, any entries older than CACHE_AGEOFF will be purged. static const size_t CACHE_WATERMARK = 4096; // Entries older than this duration will be purged once the cache grows beyond CACHE_WATERMARK entries. static const minutes CACHE_AGEOFF = minutes(5); shared_ptr<StatResult> StatResult::at(string &&path, bool file_hint, bool directory_hint) { struct stat path_stat {}; if (lstat(path.c_str(), &path_stat) != 0) { errno_t stat_errno = errno; // Ignore lstat() errors on entries that: // (a) we aren't allowed to see // (b) are at paths with too many symlinks or looping symlinks // (c) have names that are too long // (d) have a path component that is (no longer) a directory // Log any other errno that we see. if (stat_errno != ENOENT && stat_errno != EACCES && stat_errno != ELOOP && stat_errno != ENAMETOOLONG && stat_errno != ENOTDIR) { LOGGER << "lstat(" << path << ") failed: " << strerror(stat_errno) << "." << endl; } EntryKind guessed_kind = KIND_UNKNOWN; if (file_hint && !directory_hint) guessed_kind = KIND_FILE; if (!file_hint && directory_hint) guessed_kind = KIND_DIRECTORY; return shared_ptr<StatResult>(new AbsentEntry(move(path), guessed_kind)); } // Derive the entry kind from the lstat() results. EntryKind entry_kind = KIND_UNKNOWN; if ((path_stat.st_mode & S_IFREG) != 0) { entry_kind = KIND_FILE; } if ((path_stat.st_mode & S_IFDIR) != 0) { entry_kind = KIND_DIRECTORY; } return shared_ptr<StatResult>(new PresentEntry(move(path), entry_kind, path_stat.st_ino, path_stat.st_size)); } bool StatResult::has_changed_from(const StatResult &other) const { return entry_kind != other.entry_kind || path != other.path; } bool StatResult::could_be_rename_of(const StatResult &other) const { return !kinds_are_different(entry_kind, other.entry_kind); } bool StatResult::update_for_rename(const std::string &from_dir_path, const std::string &to_dir_path) { if (path.rfind(from_dir_path, 0) == 0) { path = to_dir_path + path.substr(from_dir_path.size()); return true; } return false; } const string &StatResult::get_path() const { return path; } EntryKind StatResult::get_entry_kind() const { return entry_kind; } ostream &operator<<(ostream &out, const StatResult &result) { out << result.to_string(true); return out; } PresentEntry::PresentEntry(std::string &&path, EntryKind entry_kind, ino_t inode, off_t size) : StatResult(move(path), entry_kind), inode{inode}, size{size}, last_seen{steady_clock::now()} { // } bool PresentEntry::is_present() const { return true; } bool PresentEntry::has_changed_from(const StatResult &other) const { if (StatResult::has_changed_from(other)) return true; if (other.is_absent()) return true; const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT return inode != casted.get_inode() || get_path() != casted.get_path(); } bool PresentEntry::could_be_rename_of(const StatResult &other) const { if (!StatResult::could_be_rename_of(other)) return false; if (other.is_absent()) return false; const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT return inode == casted.get_inode() && !kinds_are_different(get_entry_kind(), casted.get_entry_kind()); } ino_t PresentEntry::get_inode() const { return inode; } off_t PresentEntry::get_size() const { return size; } const time_point<steady_clock> &PresentEntry::get_last_seen() const { return last_seen; } string PresentEntry::to_string(bool verbose) const { ostringstream result; result << "[present " << get_entry_kind(); if (verbose) result << " (" << get_path() << ")"; result << " inode=" << inode << " size=" << size << "]"; return result.str(); } bool AbsentEntry::is_present() const { return false; } bool AbsentEntry::has_changed_from(const StatResult &other) const { if (StatResult::has_changed_from(other)) return true; if (other.is_present()) return true; return false; } bool AbsentEntry::could_be_rename_of(const StatResult & /*other*/) const { return false; } string AbsentEntry::to_string(bool verbose) const { ostringstream result; result << "[absent " << get_entry_kind(); if (verbose) result << " (" << get_path() << ")"; result << "]"; return result.str(); } shared_ptr<StatResult> RecentFileCache::current_at_path(const string &path, bool file_hint, bool directory_hint) { auto maybe_pending = pending.find(path); if (maybe_pending != pending.end()) { return maybe_pending->second; } shared_ptr<StatResult> stat_result = StatResult::at(string(path), file_hint, directory_hint); if (stat_result->is_present()) { pending.emplace(path, static_pointer_cast<PresentEntry>(stat_result)); } return stat_result; } shared_ptr<StatResult> RecentFileCache::former_at_path(const string &path, bool file_hint, bool directory_hint) { auto maybe = by_path.find(path); if (maybe == by_path.end()) { EntryKind kind = KIND_UNKNOWN; if (file_hint && !directory_hint) kind = KIND_FILE; if (!file_hint && directory_hint) kind = KIND_DIRECTORY; return shared_ptr<StatResult>(new AbsentEntry(string(path), kind)); } return maybe->second; } void RecentFileCache::evict(const string &path) { auto maybe = by_path.find(path); if (maybe != by_path.end()) { shared_ptr<PresentEntry> existing = maybe->second; auto range = by_timestamp.equal_range(existing->get_last_seen()); auto to_erase = by_timestamp.end(); for (auto it = range.first; it != range.second; ++it) { if (it->second == existing) { to_erase = it; } } if (to_erase != by_timestamp.end()) { by_timestamp.erase(to_erase); } by_path.erase(maybe); } } void RecentFileCache::evict(const shared_ptr<PresentEntry> &entry) { auto maybe = by_path.find(entry->get_path()); if (maybe != by_path.end() && maybe->second == entry) { evict(entry->get_path()); } } void RecentFileCache::update_for_rename(const string &from_dir_path, const string &to_dir_path) { vector<pair<string, string>> renames; for (auto &each : by_path) { if (each.second->update_for_rename(from_dir_path, to_dir_path)) { renames.emplace_back(each.first, each.second->get_path()); } } for (auto &rename : renames) { shared_ptr<PresentEntry> p = by_path[rename.first]; by_path.erase(rename.first); by_path.emplace(rename.second, p); } } void RecentFileCache::apply() { for (auto &pair : pending) { shared_ptr<PresentEntry> &present = pair.second; // Clear an existing entry at the same path if one exists evict(present->get_path()); // Add the new PresentEntry by_path.emplace(present->get_path(), present); by_timestamp.emplace(present->get_last_seen(), present); } pending.clear(); } void RecentFileCache::prune() { if (by_path.size() <= CACHE_WATERMARK) { return; } LOGGER << "Cache currently contains " << plural(by_path.size(), "entry", "entries") << ". Pruning triggered." << endl; time_point<steady_clock> oldest = steady_clock::now() - CACHE_AGEOFF; auto to_keep = by_timestamp.upper_bound(oldest); size_t prune_count = 0; for (auto it = by_timestamp.begin(); it != to_keep && it != by_timestamp.end(); ++it) { shared_ptr<PresentEntry> entry = it->second; by_path.erase(entry->get_path()); prune_count++; } if (to_keep != by_timestamp.begin()) { by_timestamp.erase(by_timestamp.begin(), to_keep); } LOGGER << "Pruned " << plural(prune_count, "entry", "entries") << ". " << plural(by_path.size(), "entry", "entries") << " remain." << endl; } void RecentFileCache::prepopulate(const string &root, size_t max) { size_t count = 0; size_t entries = 0; queue<string> next_roots; next_roots.push(root); while (count < max && !next_roots.empty()) { string current_root(next_roots.front()); next_roots.pop(); DIR *dir = opendir(current_root.c_str()); if (dir == nullptr) { errno_t opendir_errno = errno; LOGGER << "Unable to open directory " << root << ": " << strerror(opendir_errno) << "." << endl; LOGGER << "Incompletely pre-populated cache with " << entries << " entries." << endl; return; } errno = 0; dirent *entry = readdir(dir); while (entry != nullptr) { string entry_name(entry->d_name, entry->d_namlen); if (entry_name != "." && entry_name != "..") { string entry_path(path_join(current_root, entry_name)); bool file_hint = (entry->d_type & DT_REG) == DT_REG; bool dir_hint = (entry->d_type & DT_DIR) == DT_DIR; shared_ptr<StatResult> r = current_at_path(entry_path, file_hint, dir_hint); if (r->is_present()) { entries++; if (r->get_entry_kind() == KIND_DIRECTORY) next_roots.push(entry_path); } count++; if (count >= max) { LOGGER << "Incompletely pre-populated cache with " << entries << " entries." << endl; return; } } errno = 0; entry = readdir(dir); } errno_t readdir_errno = errno; if (readdir_errno != 0) { LOGGER << "Unable to read directory entry within " << root << ": " << strerror(readdir_errno) << "." << endl; } if (closedir(dir) != 0) { errno_t closedir_errno = errno; LOGGER << "Unable to close directory " << root << ": " << strerror(closedir_errno) << "." << endl; } } apply(); LOGGER << "Pre-populated cache with " << entries << " entries." << endl; } <commit_msg>Don't update exact-match entries<commit_after>#include "recent_file_cache.h" #include <cerrno> #include <chrono> #include <cstdio> #include <iomanip> #include <iostream> #include <memory> #include <queue> #include <sstream> #include <string> #include <sys/stat.h> #include <unordered_map> #include <utility> #include <vector> #include "../../helper/common.h" #include "../../log.h" using std::chrono::minutes; using std::chrono::steady_clock; using std::chrono::time_point; using std::endl; using std::move; using std::ostream; using std::ostringstream; using std::pair; using std::queue; using std::shared_ptr; using std::static_pointer_cast; using std::string; using std::vector; // If the cache contains more than this many entries, any entries older than CACHE_AGEOFF will be purged. static const size_t CACHE_WATERMARK = 4096; // Entries older than this duration will be purged once the cache grows beyond CACHE_WATERMARK entries. static const minutes CACHE_AGEOFF = minutes(5); shared_ptr<StatResult> StatResult::at(string &&path, bool file_hint, bool directory_hint) { struct stat path_stat {}; if (lstat(path.c_str(), &path_stat) != 0) { errno_t stat_errno = errno; // Ignore lstat() errors on entries that: // (a) we aren't allowed to see // (b) are at paths with too many symlinks or looping symlinks // (c) have names that are too long // (d) have a path component that is (no longer) a directory // Log any other errno that we see. if (stat_errno != ENOENT && stat_errno != EACCES && stat_errno != ELOOP && stat_errno != ENAMETOOLONG && stat_errno != ENOTDIR) { LOGGER << "lstat(" << path << ") failed: " << strerror(stat_errno) << "." << endl; } EntryKind guessed_kind = KIND_UNKNOWN; if (file_hint && !directory_hint) guessed_kind = KIND_FILE; if (!file_hint && directory_hint) guessed_kind = KIND_DIRECTORY; return shared_ptr<StatResult>(new AbsentEntry(move(path), guessed_kind)); } // Derive the entry kind from the lstat() results. EntryKind entry_kind = KIND_UNKNOWN; if ((path_stat.st_mode & S_IFREG) != 0) { entry_kind = KIND_FILE; } if ((path_stat.st_mode & S_IFDIR) != 0) { entry_kind = KIND_DIRECTORY; } return shared_ptr<StatResult>(new PresentEntry(move(path), entry_kind, path_stat.st_ino, path_stat.st_size)); } bool StatResult::has_changed_from(const StatResult &other) const { return entry_kind != other.entry_kind || path != other.path; } bool StatResult::could_be_rename_of(const StatResult &other) const { return !kinds_are_different(entry_kind, other.entry_kind); } bool StatResult::update_for_rename(const std::string &from_dir_path, const std::string &to_dir_path) { if (path.size() > from_dir_path.size() && path.rfind(from_dir_path, 0) == 0) { path = to_dir_path + path.substr(from_dir_path.size()); return true; } return false; } const string &StatResult::get_path() const { return path; } EntryKind StatResult::get_entry_kind() const { return entry_kind; } ostream &operator<<(ostream &out, const StatResult &result) { out << result.to_string(true); return out; } PresentEntry::PresentEntry(std::string &&path, EntryKind entry_kind, ino_t inode, off_t size) : StatResult(move(path), entry_kind), inode{inode}, size{size}, last_seen{steady_clock::now()} { // } bool PresentEntry::is_present() const { return true; } bool PresentEntry::has_changed_from(const StatResult &other) const { if (StatResult::has_changed_from(other)) return true; if (other.is_absent()) return true; const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT return inode != casted.get_inode() || get_path() != casted.get_path(); } bool PresentEntry::could_be_rename_of(const StatResult &other) const { if (!StatResult::could_be_rename_of(other)) return false; if (other.is_absent()) return false; const auto &casted = static_cast<const PresentEntry &>(other); // NOLINT return inode == casted.get_inode() && !kinds_are_different(get_entry_kind(), casted.get_entry_kind()); } ino_t PresentEntry::get_inode() const { return inode; } off_t PresentEntry::get_size() const { return size; } const time_point<steady_clock> &PresentEntry::get_last_seen() const { return last_seen; } string PresentEntry::to_string(bool verbose) const { ostringstream result; result << "[present " << get_entry_kind(); if (verbose) result << " (" << get_path() << ")"; result << " inode=" << inode << " size=" << size << "]"; return result.str(); } bool AbsentEntry::is_present() const { return false; } bool AbsentEntry::has_changed_from(const StatResult &other) const { if (StatResult::has_changed_from(other)) return true; if (other.is_present()) return true; return false; } bool AbsentEntry::could_be_rename_of(const StatResult & /*other*/) const { return false; } string AbsentEntry::to_string(bool verbose) const { ostringstream result; result << "[absent " << get_entry_kind(); if (verbose) result << " (" << get_path() << ")"; result << "]"; return result.str(); } shared_ptr<StatResult> RecentFileCache::current_at_path(const string &path, bool file_hint, bool directory_hint) { auto maybe_pending = pending.find(path); if (maybe_pending != pending.end()) { return maybe_pending->second; } shared_ptr<StatResult> stat_result = StatResult::at(string(path), file_hint, directory_hint); if (stat_result->is_present()) { pending.emplace(path, static_pointer_cast<PresentEntry>(stat_result)); } return stat_result; } shared_ptr<StatResult> RecentFileCache::former_at_path(const string &path, bool file_hint, bool directory_hint) { auto maybe = by_path.find(path); if (maybe == by_path.end()) { EntryKind kind = KIND_UNKNOWN; if (file_hint && !directory_hint) kind = KIND_FILE; if (!file_hint && directory_hint) kind = KIND_DIRECTORY; return shared_ptr<StatResult>(new AbsentEntry(string(path), kind)); } return maybe->second; } void RecentFileCache::evict(const string &path) { auto maybe = by_path.find(path); if (maybe != by_path.end()) { shared_ptr<PresentEntry> existing = maybe->second; auto range = by_timestamp.equal_range(existing->get_last_seen()); auto to_erase = by_timestamp.end(); for (auto it = range.first; it != range.second; ++it) { if (it->second == existing) { to_erase = it; } } if (to_erase != by_timestamp.end()) { by_timestamp.erase(to_erase); } by_path.erase(maybe); } } void RecentFileCache::evict(const shared_ptr<PresentEntry> &entry) { auto maybe = by_path.find(entry->get_path()); if (maybe != by_path.end() && maybe->second == entry) { evict(entry->get_path()); } } void RecentFileCache::update_for_rename(const string &from_dir_path, const string &to_dir_path) { vector<pair<string, string>> renames; for (auto &each : by_path) { if (each.second->update_for_rename(from_dir_path, to_dir_path)) { renames.emplace_back(each.first, each.second->get_path()); } } for (auto &rename : renames) { shared_ptr<PresentEntry> p = by_path[rename.first]; by_path.erase(rename.first); by_path.emplace(rename.second, p); } } void RecentFileCache::apply() { for (auto &pair : pending) { shared_ptr<PresentEntry> &present = pair.second; // Clear an existing entry at the same path if one exists evict(present->get_path()); // Add the new PresentEntry by_path.emplace(present->get_path(), present); by_timestamp.emplace(present->get_last_seen(), present); } pending.clear(); } void RecentFileCache::prune() { if (by_path.size() <= CACHE_WATERMARK) { return; } LOGGER << "Cache currently contains " << plural(by_path.size(), "entry", "entries") << ". Pruning triggered." << endl; time_point<steady_clock> oldest = steady_clock::now() - CACHE_AGEOFF; auto to_keep = by_timestamp.upper_bound(oldest); size_t prune_count = 0; for (auto it = by_timestamp.begin(); it != to_keep && it != by_timestamp.end(); ++it) { shared_ptr<PresentEntry> entry = it->second; by_path.erase(entry->get_path()); prune_count++; } if (to_keep != by_timestamp.begin()) { by_timestamp.erase(by_timestamp.begin(), to_keep); } LOGGER << "Pruned " << plural(prune_count, "entry", "entries") << ". " << plural(by_path.size(), "entry", "entries") << " remain." << endl; } void RecentFileCache::prepopulate(const string &root, size_t max) { size_t count = 0; size_t entries = 0; queue<string> next_roots; next_roots.push(root); while (count < max && !next_roots.empty()) { string current_root(next_roots.front()); next_roots.pop(); DIR *dir = opendir(current_root.c_str()); if (dir == nullptr) { errno_t opendir_errno = errno; LOGGER << "Unable to open directory " << root << ": " << strerror(opendir_errno) << "." << endl; LOGGER << "Incompletely pre-populated cache with " << entries << " entries." << endl; return; } errno = 0; dirent *entry = readdir(dir); while (entry != nullptr) { string entry_name(entry->d_name, entry->d_namlen); if (entry_name != "." && entry_name != "..") { string entry_path(path_join(current_root, entry_name)); bool file_hint = (entry->d_type & DT_REG) == DT_REG; bool dir_hint = (entry->d_type & DT_DIR) == DT_DIR; shared_ptr<StatResult> r = current_at_path(entry_path, file_hint, dir_hint); if (r->is_present()) { entries++; if (r->get_entry_kind() == KIND_DIRECTORY) next_roots.push(entry_path); } count++; if (count >= max) { LOGGER << "Incompletely pre-populated cache with " << entries << " entries." << endl; return; } } errno = 0; entry = readdir(dir); } errno_t readdir_errno = errno; if (readdir_errno != 0) { LOGGER << "Unable to read directory entry within " << root << ": " << strerror(readdir_errno) << "." << endl; } if (closedir(dir) != 0) { errno_t closedir_errno = errno; LOGGER << "Unable to close directory " << root << ": " << strerror(closedir_errno) << "." << endl; } } apply(); LOGGER << "Pre-populated cache with " << entries << " entries." << endl; } <|endoftext|>
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <processor/Processor.h> #include <processor/IoPortManager.h> #include <processor/PageFaultHandler.h> #include <process/initialiseMultitasking.h> #include "gdt.h" #include "SyscallManager.h" #include "InterruptManager.h" #include "VirtualAddressSpace.h" #include "../x86_common/PhysicalMemoryManager.h" // Multiprocessor headers #if defined(MULTIPROCESSOR) #include "../x86_common/Multiprocessor.h" #endif void Processor::switchAddressSpace(VirtualAddressSpace &AddressSpace) { const X64VirtualAddressSpace &x64AddressSpace = static_cast<const X64VirtualAddressSpace&>(AddressSpace); // Get the current page directory uint64_t cr3; asm volatile ("mov %%cr3, %0" : "=r" (cr3)); // Do we need to set a new page directory? if (cr3 != x64AddressSpace.m_PhysicalPML4) { // Set the new page directory asm volatile ("mov %0, %%cr3" :: "r" (x64AddressSpace.m_PhysicalPML4)); // Update the information in the ProcessorInformation structure ProcessorInformation &processorInformation = Processor::information(); processorInformation.setVirtualAddressSpace(AddressSpace); } } void Processor::initialise1(const BootstrapStruct_t &Info) { // Initialise this processor's interrupt handling X64InterruptManager::initialiseProcessor(); // Initialise this processor's syscall handling X64SyscallManager::initialiseProcessor(); PageFaultHandler::instance().initialise(); // Initialise the physical memory-management X86CommonPhysicalMemoryManager &physicalMemoryManager = X86CommonPhysicalMemoryManager::instance(); physicalMemoryManager.initialise(Info); // Initialise the I/O Manager IoPortManager &ioPortManager = IoPortManager::instance(); ioPortManager.initialise(0, 0x10000); m_Initialised = 1; } void Processor::initialise2(const BootstrapStruct_t &Info) { size_t nProcessors = 1; #if defined(MULTIPROCESSOR) nProcessors = Multiprocessor::initialise1(); #endif // Initialise the GDT X64GdtManager::instance().initialise(nProcessors); X64GdtManager::initialiseProcessor(); initialiseMultitasking(); #if defined(MULTIPROCESSOR) if (nProcessors != 1) Multiprocessor::initialise2(); #endif // Initialise the 64-bit physical memory management X86CommonPhysicalMemoryManager &physicalMemoryManager = X86CommonPhysicalMemoryManager::instance(); physicalMemoryManager.initialise64(Info); m_Initialised = 2; } void Processor::identify(HugeStaticString &str) { uint32_t eax, ebx, ecx, edx; char ident[13]; cpuid(0, 0, eax, ebx, ecx, edx); memcpy(ident, &ebx, 4); memcpy(&ident[4], &edx, 4); memcpy(&ident[8], &ecx, 4); ident[12] = 0; str = ident; } void Processor::setTlsBase(uintptr_t newBase) { X64GdtManager::instance().setTlsBase(newBase); // Reload FS/GS uint16_t newseg = newBase ? Processor::information().getTlsSelector() | 3 : 0x23; asm volatile("mov %0, %%bx; mov %%bx, %%fs; mov %%bx, %%gs" :: "r" (newseg) : "ebx"); } <commit_msg>x64: removed setting of FS/GS in Processor::setTlsBase temporarily.<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <processor/Processor.h> #include <processor/IoPortManager.h> #include <processor/PageFaultHandler.h> #include <process/initialiseMultitasking.h> #include "gdt.h" #include "SyscallManager.h" #include "InterruptManager.h" #include "VirtualAddressSpace.h" #include "../x86_common/PhysicalMemoryManager.h" // Multiprocessor headers #if defined(MULTIPROCESSOR) #include "../x86_common/Multiprocessor.h" #endif void Processor::switchAddressSpace(VirtualAddressSpace &AddressSpace) { const X64VirtualAddressSpace &x64AddressSpace = static_cast<const X64VirtualAddressSpace&>(AddressSpace); // Get the current page directory uint64_t cr3; asm volatile ("mov %%cr3, %0" : "=r" (cr3)); // Do we need to set a new page directory? if (cr3 != x64AddressSpace.m_PhysicalPML4) { // Set the new page directory asm volatile ("mov %0, %%cr3" :: "r" (x64AddressSpace.m_PhysicalPML4)); // Update the information in the ProcessorInformation structure ProcessorInformation &processorInformation = Processor::information(); processorInformation.setVirtualAddressSpace(AddressSpace); } } void Processor::initialise1(const BootstrapStruct_t &Info) { // Initialise this processor's interrupt handling X64InterruptManager::initialiseProcessor(); // Initialise this processor's syscall handling X64SyscallManager::initialiseProcessor(); PageFaultHandler::instance().initialise(); // Initialise the physical memory-management X86CommonPhysicalMemoryManager &physicalMemoryManager = X86CommonPhysicalMemoryManager::instance(); physicalMemoryManager.initialise(Info); // Initialise the I/O Manager IoPortManager &ioPortManager = IoPortManager::instance(); ioPortManager.initialise(0, 0x10000); m_Initialised = 1; } void Processor::initialise2(const BootstrapStruct_t &Info) { size_t nProcessors = 1; #if defined(MULTIPROCESSOR) nProcessors = Multiprocessor::initialise1(); #endif // Initialise the GDT X64GdtManager::instance().initialise(nProcessors); X64GdtManager::initialiseProcessor(); initialiseMultitasking(); #if defined(MULTIPROCESSOR) if (nProcessors != 1) Multiprocessor::initialise2(); #endif // Initialise the 64-bit physical memory management X86CommonPhysicalMemoryManager &physicalMemoryManager = X86CommonPhysicalMemoryManager::instance(); physicalMemoryManager.initialise64(Info); m_Initialised = 2; } void Processor::identify(HugeStaticString &str) { uint32_t eax, ebx, ecx, edx; char ident[13]; cpuid(0, 0, eax, ebx, ecx, edx); memcpy(ident, &ebx, 4); memcpy(&ident[4], &edx, 4); memcpy(&ident[8], &ecx, 4); ident[12] = 0; str = ident; } void Processor::setTlsBase(uintptr_t newBase) { X64GdtManager::instance().setTlsBase(newBase); // Reload FS/GS uint16_t newseg = newBase ? Processor::information().getTlsSelector() | 3 : 0x23; // asm volatile("mov %0, %%bx; mov %%bx, %%fs; mov %%bx, %%gs" :: "r" (newseg) : "ebx"); } <|endoftext|>
<commit_before>/* * Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 "workload/stresstest/Application.h" #include <cassert> #include <vector> #include "workload/stresstest/BlastTerminal.h" #include "event/Simulator.h" #include "network/Network.h" namespace StressTest { Application::Application( const std::string& _name, const Component* _parent, u32 _id, Workload* _workload, MetadataHandler* _metadataHandler, Json::Value _settings) : ::Application(_name, _parent, _id, _workload, _metadataHandler, _settings), killOnSaturation_(_settings["kill_on_saturation"].asBool()), logDuringSaturation_(_settings["log_during_saturation"].asBool()), maxSaturationCycles_(_settings["max_saturation_cycles"].asUInt()), warmupThreshold_(_settings["warmup_threshold"].asDouble()) { // check settings assert(!_settings["kill_on_saturation"].isNull()); assert(!_settings["log_during_saturation"].isNull()); if (logDuringSaturation_) { assert(!_settings["max_saturation_cycles"].isNull()); } assert(!_settings["warmup_threshold"].isNull()); assert(warmupThreshold_ > 0); assert(warmupThreshold_ <= 1.0); // all terminals are the same activeTerminals_ = numTerminals(); for (u32 t = 0; t < numTerminals(); t++) { std::string tname = "BlastTerminal_" + std::to_string(t); std::vector<u32> address; gSim->getNetwork()->translateInterfaceIdToAddress(t, &address); BlastTerminal* terminal = new BlastTerminal(tname, this, t, address, this, _settings["blast_terminal"]); setTerminal(t, terminal); // remove terminals with no injection if (maxInjectionRate(t) == 0.0) { activeTerminals_--; } } // initialize state machine fsm_ = Application::Fsm::WARMING; // initialize counters warmedTerminals_ = 0; saturatedTerminals_ = 0; completedTerminals_ = 0; doneTerminals_ = 0; } Application::~Application() {} f64 Application::percentComplete() const { f64 percentSum = 0.0; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); percentSum += t->percentComplete(); } return percentSum / activeTerminals_; } void Application::start() { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); if (doLogging_) { t->startLogging(); } else { t->stopSending(); } } if (!doLogging_) { workload_->applicationComplete(id_); } } void Application::stop() { if (doLogging_) { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopLogging(); } } else { workload_->applicationDone(id_); } } void Application::kill() { if (doLogging_) { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopSending(); } } } void Application::terminalWarmed(u32 _id) { assert(fsm_ == Application::Fsm::WARMING); warmedTerminals_++; // dbgprintf("Terminal %u is warmed (%u total)", _id, warmedTerminals_); assert(warmedTerminals_ <= activeTerminals_); f64 percentWarmed = warmedTerminals_ / static_cast<f64>(activeTerminals_); if (percentWarmed >= warmupThreshold_) { fsm_ = Application::Fsm::LOGGING; dbgprintf("Warmup threshold %f reached", warmupThreshold_); doLogging_ = true; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); } } void Application::terminalSaturated(u32 _id) { assert(fsm_ == Application::Fsm::WARMING); saturatedTerminals_++; // dbgprintf("Terminal %u is saturated (%u total)", _id, saturatedTerminals_); assert(saturatedTerminals_ <= activeTerminals_); f64 percentSaturated = saturatedTerminals_ / static_cast<f64>(activeTerminals_); if (percentSaturated > (1.0 - warmupThreshold_)) { // the network is saturated if (killOnSaturation_) { // just kill the simulator right here dbgprintf("Saturation threshold %f reached, initiating kill fast", 1.0 - warmupThreshold_); exit(0); } else if (logDuringSaturation_) { // start the logging phase dbgprintf("Saturation threshold %f reached, continuing anyway", 1.0 - warmupThreshold_); fsm_ = Application::Fsm::LOGGING; doLogging_ = true; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); // set the maximum number of cycles to stay within the logging phase u64 timeout = gSim->futureCycle(Simulator::Clock::CHANNEL, maxSaturationCycles_); dbgprintf("setting timeout from %lu to %lu", gSim->time(), timeout); addEvent(timeout, 0, nullptr, 0); } else { // drain all the packets from the network dbgprintf("Saturation threshold %f reached", 1.0 - warmupThreshold_); fsm_ = Application::Fsm::DRAINING; doLogging_ = false; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); } } } void Application::terminalComplete(u32 _id) { completedTerminals_++; // dbgprintf("Terminal %u is done logging (%u total)", // _id, completedTerminals_); assert(completedTerminals_ <= activeTerminals_); if (completedTerminals_ == activeTerminals_) { dbgprintf("All terminals are done logging"); fsm_ = Application::Fsm::BLABBING; workload_->applicationComplete(id_); } } void Application::terminalDone(u32 _id) { doneTerminals_++; // dbgprintf("Terminal %u is done sending (%u total)", _id, doneTerminals_); assert(doneTerminals_ <= activeTerminals_); if (doneTerminals_ == activeTerminals_) { dbgprintf("All terminals are done sending"); fsm_ = Application::Fsm::DRAINING; workload_->applicationDone(id_); } } void Application::processEvent(void* _event, s32 _type) { if (fsm_ == Application::Fsm::LOGGING) { dbgprintf("Max saturation time reached"); fsm_ = Application::Fsm::BLABBING; workload_->applicationComplete(id_); } } } // namespace StressTest <commit_msg>now allowing stresstest to skip warmup with warmup_threshold=0<commit_after>/* * Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 "workload/stresstest/Application.h" #include <cassert> #include <vector> #include "workload/stresstest/BlastTerminal.h" #include "event/Simulator.h" #include "network/Network.h" #define FORCE_WARMED (0x123) #define MAX_SATURATION (0x456) namespace StressTest { Application::Application( const std::string& _name, const Component* _parent, u32 _id, Workload* _workload, MetadataHandler* _metadataHandler, Json::Value _settings) : ::Application(_name, _parent, _id, _workload, _metadataHandler, _settings), killOnSaturation_(_settings["kill_on_saturation"].asBool()), logDuringSaturation_(_settings["log_during_saturation"].asBool()), maxSaturationCycles_(_settings["max_saturation_cycles"].asUInt()), warmupThreshold_(_settings["warmup_threshold"].asDouble()) { // check settings assert(!_settings["kill_on_saturation"].isNull()); assert(!_settings["log_during_saturation"].isNull()); if (logDuringSaturation_) { assert(!_settings["max_saturation_cycles"].isNull()); } assert(!_settings["warmup_threshold"].isNull()); assert(warmupThreshold_ >= 0.0); assert(warmupThreshold_ <= 1.0); // all terminals are the same activeTerminals_ = numTerminals(); for (u32 t = 0; t < numTerminals(); t++) { std::string tname = "BlastTerminal_" + std::to_string(t); std::vector<u32> address; gSim->getNetwork()->translateInterfaceIdToAddress(t, &address); BlastTerminal* terminal = new BlastTerminal(tname, this, t, address, this, _settings["blast_terminal"]); setTerminal(t, terminal); // remove terminals with no injection if (maxInjectionRate(t) == 0.0) { activeTerminals_--; } } // initialize state machine fsm_ = Application::Fsm::WARMING; // initialize counters warmedTerminals_ = 0; saturatedTerminals_ = 0; completedTerminals_ = 0; doneTerminals_ = 0; // force warmed if threshold is 0.0 if (warmupThreshold_ == 0.0) { addEvent(0, 0, nullptr, FORCE_WARMED); } } Application::~Application() {} f64 Application::percentComplete() const { f64 percentSum = 0.0; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); percentSum += t->percentComplete(); } return percentSum / activeTerminals_; } void Application::start() { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); if (doLogging_) { t->startLogging(); } else { t->stopSending(); } } if (!doLogging_) { workload_->applicationComplete(id_); } } void Application::stop() { if (doLogging_) { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopLogging(); } } else { workload_->applicationDone(id_); } } void Application::kill() { if (doLogging_) { for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopSending(); } } } void Application::terminalWarmed(u32 _id) { assert(fsm_ == Application::Fsm::WARMING); if (_id != U32_MAX) { warmedTerminals_++; } // dbgprintf("Terminal %u is warmed (%u total)", _id, warmedTerminals_); assert(warmedTerminals_ <= activeTerminals_); f64 percentWarmed = warmedTerminals_ / static_cast<f64>(activeTerminals_); if (percentWarmed >= warmupThreshold_) { fsm_ = Application::Fsm::LOGGING; dbgprintf("Warmup threshold %f reached", warmupThreshold_); doLogging_ = true; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); } } void Application::terminalSaturated(u32 _id) { assert(fsm_ == Application::Fsm::WARMING); saturatedTerminals_++; // dbgprintf("Terminal %u is saturated (%u total)", _id, saturatedTerminals_); assert(saturatedTerminals_ <= activeTerminals_); f64 percentSaturated = saturatedTerminals_ / static_cast<f64>(activeTerminals_); if (percentSaturated > (1.0 - warmupThreshold_)) { // the network is saturated if (killOnSaturation_) { // just kill the simulator right here dbgprintf("Saturation threshold %f reached, initiating kill fast", 1.0 - warmupThreshold_); exit(0); } else if (logDuringSaturation_) { // start the logging phase dbgprintf("Saturation threshold %f reached, continuing anyway", 1.0 - warmupThreshold_); fsm_ = Application::Fsm::LOGGING; doLogging_ = true; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); // set the maximum number of cycles to stay within the logging phase u64 timeout = gSim->futureCycle(Simulator::Clock::CHANNEL, maxSaturationCycles_); dbgprintf("setting timeout from %lu to %lu", gSim->time(), timeout); addEvent(timeout, 0, nullptr, MAX_SATURATION); } else { // drain all the packets from the network dbgprintf("Saturation threshold %f reached", 1.0 - warmupThreshold_); fsm_ = Application::Fsm::DRAINING; doLogging_ = false; for (u32 idx = 0; idx < numTerminals(); idx++) { BlastTerminal* t = reinterpret_cast<BlastTerminal*>(getTerminal(idx)); t->stopWarming(); } workload_->applicationReady(id_); } } } void Application::terminalComplete(u32 _id) { completedTerminals_++; // dbgprintf("Terminal %u is done logging (%u total)", // _id, completedTerminals_); assert(completedTerminals_ <= activeTerminals_); if (completedTerminals_ == activeTerminals_) { dbgprintf("All terminals are done logging"); fsm_ = Application::Fsm::BLABBING; workload_->applicationComplete(id_); } } void Application::terminalDone(u32 _id) { doneTerminals_++; // dbgprintf("Terminal %u is done sending (%u total)", _id, doneTerminals_); assert(doneTerminals_ <= activeTerminals_); if (doneTerminals_ == activeTerminals_) { dbgprintf("All terminals are done sending"); fsm_ = Application::Fsm::DRAINING; workload_->applicationDone(id_); } } void Application::processEvent(void* _event, s32 _type) { switch (_type) { case FORCE_WARMED: { terminalWarmed(U32_MAX); break; } case MAX_SATURATION: { if (fsm_ == Application::Fsm::LOGGING) { dbgprintf("Max saturation time reached"); fsm_ = Application::Fsm::BLABBING; workload_->applicationComplete(id_); } break; } default: assert(false); } } } // namespace StressTest <|endoftext|>
<commit_before>/* Adapted from ciUI's Moving Graph by @brucelane with permission from @rezaali https://github.com/rezaali/ciUI */ #include "Graph.h" using namespace ci; using namespace ci::app; using namespace std; using namespace MinimalUI; int MovingGraph::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT; int MovingGraph::DEFAULT_WIDTH = 96; // common initialization void MovingGraph::init() { // initialize unique variables mMin = hasParam("min") ? getParam<float>("min") : 0.0f; mMax = hasParam("max") ? getParam<float>("max") : 1.0f; // set size int x = hasParam("width") ? getParam<int>("width") : MovingGraph::DEFAULT_WIDTH; int y = hasParam("height") ? getParam<int>("height") : MovingGraph::DEFAULT_HEIGHT; setSize(Vec2i(x, y)); // set position and bounds setPositionAndBounds(); mScreenMin = mBounds.getX1(); mScreenMax = mBounds.getX2(); mBufferSize = 128; mScale = mBounds.getHeight() * 0.5f; mInc = mBounds.getWidth() / ((float)mBufferSize - 1.0f); renderNameTexture(); // set screen value update(); } // without event handler MovingGraph::MovingGraph(UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString) : UIElement(aUIController, aName, aParamString), mLinkedValue(aValueToLink) { init(); } // with event handler MovingGraph::MovingGraph(UIController *aUIController, const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString) : UIElement(aUIController, aName, aParamString), mLinkedValue(aValueToLink) { // initialize unique variables addEventHandler(aEventHandler); mPressed = hasParam("pressed") ? getParam<bool>("pressed") : false; mStateless = hasParam("stateless") ? getParam<bool>("stateless") : true; mExclusive = hasParam("exclusive") ? getParam<bool>("exclusive") : false; mCallbackOnRelease = hasParam("callbackOnRelease") ? getParam<bool>("callbackOnRelease") : true; mContinuous = hasParam("continuous") ? getParam<bool>("continuous") : false; init(); } // without event handler UIElementRef MovingGraph::create(UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString) { return shared_ptr<MovingGraph>(new MovingGraph(aUIController, aName, aValueToLink, aParamString)); } // with event handler UIElementRef MovingGraph::create(UIController *aUIController, const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString) { return shared_ptr<MovingGraph>(new MovingGraph(aUIController, aName, aValueToLink, aEventHandler, aParamString)); } void MovingGraph::draw() { // set the color if (isActive()) { gl::color(UIController::ACTIVE_STROKE_COLOR); } else if (mPressed) { gl::color(UIController::DEFAULT_STROKE_COLOR); } else { gl::color(getBackgroundColor()); } // draw the outer rect gl::drawStrokedRect(getBounds()); // draw the background drawBackground(); // draw the graph gl::color( UIController::ACTIVE_STROKE_COLOR ); gl::pushMatrices(); gl::translate( mBounds.getX1(), mBounds.getY1() + mScale ); mShape.clear(); mShape.moveTo( 0.0f, lmap<float>( mBuffer[0], mMin, mMax, mScale, -mScale ) ); for (int i = 1; i < mBuffer.size(); i++) { mShape.lineTo( mInc * (float)i, lmap<float>( mBuffer[i], mMin, mMax, mScale, -mScale ) ); } gl::draw( mShape ); gl::popMatrices(); // draw the label drawLabel(); } void MovingGraph::release() { if (mPressed) { mPressed = false; if (mCallbackOnRelease) { callEventHandlers(); } } } void MovingGraph::handleMouseUp(const Vec2i &aMousePos) { if (mStateless) { // mPressed should always be false if it's a stateless button; just call the handler callEventHandlers(); } else { if (mPressed) { // if the button is in an exclusive group and it's already pressed, don't do anything if (!mExclusive) { // release the button mPressed = false; callEventHandlers(); } } else { // if the button is an exclusive group and isn't pressed, release all the buttons in the group first if (mExclusive) { getParent()->releaseGroup(getGroup()); } // press the button mPressed = true; callEventHandlers(); } } } void MovingGraph::addEventHandler(const std::function<void(bool)>& aEventHandler) { mEventHandlers.push_back(aEventHandler); } void MovingGraph::callEventHandlers() { for (int i = 0; i < mEventHandlers.size(); i++) { mEventHandlers[i](mPressed); } } void MovingGraph::update() { if (mContinuous && mStateless && isActive()) { callEventHandlers(); } mBuffer.push_back( *mLinkedValue ); if( mBuffer.size() >= mBufferSize ) { mBuffer.erase( mBuffer.begin(), mBuffer.begin() + 1 ); } } <commit_msg>feedback done but I don't know how to remove the highlight on click, tryed deactivate() without success<commit_after>/* Adapted from ciUI's Moving Graph by @brucelane with permission from @rezaali https://github.com/rezaali/ciUI */ #include "Graph.h" using namespace ci; using namespace ci::app; using namespace std; using namespace MinimalUI; int MovingGraph::DEFAULT_HEIGHT = UIElement::DEFAULT_HEIGHT; int MovingGraph::DEFAULT_WIDTH = 96; // common initialization void MovingGraph::init() { // initialize unique variables mMin = hasParam("min") ? getParam<float>("min") : 0.0f; mMax = hasParam("max") ? getParam<float>("max") : 1.0f; mPressed = hasParam("pressed") ? getParam<bool>("pressed") : false; mStateless = hasParam("stateless") ? getParam<bool>("stateless") : true; mExclusive = hasParam("exclusive") ? getParam<bool>("exclusive") : false; mCallbackOnRelease = hasParam("callbackOnRelease") ? getParam<bool>("callbackOnRelease") : true; mContinuous = hasParam("continuous") ? getParam<bool>("continuous") : false; // set size int x = hasParam("width") ? getParam<int>("width") : MovingGraph::DEFAULT_WIDTH; int y = hasParam("height") ? getParam<int>("height") : MovingGraph::DEFAULT_HEIGHT; setSize(Vec2i(x, y)); // set position and bounds setPositionAndBounds(); mScreenMin = mBounds.getX1(); mScreenMax = mBounds.getX2(); mBufferSize = 128; mScale = mBounds.getHeight() * 0.5f; mInc = mBounds.getWidth() / ((float)mBufferSize - 1.0f); renderNameTexture(); // set screen value update(); } // without event handler MovingGraph::MovingGraph(UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString) : UIElement(aUIController, aName, aParamString), mLinkedValue(aValueToLink) { init(); } // with event handler MovingGraph::MovingGraph(UIController *aUIController, const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString) : UIElement(aUIController, aName, aParamString), mLinkedValue(aValueToLink) { // initialize unique variables addEventHandler(aEventHandler); init(); } // without event handler UIElementRef MovingGraph::create(UIController *aUIController, const string &aName, float *aValueToLink, const string &aParamString) { return shared_ptr<MovingGraph>(new MovingGraph(aUIController, aName, aValueToLink, aParamString)); } // with event handler UIElementRef MovingGraph::create(UIController *aUIController, const string &aName, float *aValueToLink, const std::function<void(bool)>& aEventHandler, const string &aParamString) { return shared_ptr<MovingGraph>(new MovingGraph(aUIController, aName, aValueToLink, aEventHandler, aParamString)); } void MovingGraph::draw() { // set the color if (isActive()) { gl::color(UIController::ACTIVE_STROKE_COLOR); } else if (mPressed) { gl::color(UIController::DEFAULT_STROKE_COLOR); } else { gl::color(getBackgroundColor()); } // draw the button background gl::drawSolidRect(getBounds()); // draw the background drawBackground(); // draw the graph if (isActive()) { gl::color(UIController::ACTIVE_STROKE_COLOR); } else { gl::color(UIController::DEFAULT_STROKE_COLOR); } // draw the outer rect gl::drawStrokedRect(getBounds()); gl::pushMatrices(); gl::translate( mBounds.getX1(), mBounds.getY1() + mScale ); // active color for moving graph gl::color(UIController::ACTIVE_STROKE_COLOR); mShape.clear(); mShape.moveTo( 0.0f, lmap<float>( mBuffer[0], mMin, mMax, mScale, -mScale ) ); for (int i = 1; i < mBuffer.size(); i++) { mShape.lineTo( mInc * (float)i, lmap<float>( mBuffer[i], mMin, mMax, mScale, -mScale ) ); } gl::draw( mShape ); gl::popMatrices(); // draw the label drawLabel(); } void MovingGraph::release() { if (mPressed) { mPressed = false; if (mCallbackOnRelease) { callEventHandlers(); } } } void MovingGraph::handleMouseUp(const Vec2i &aMousePos) { if (mStateless) { // mPressed should always be false if it's a stateless button; just call the handler callEventHandlers(); } else { if (mPressed) { // if the button is in an exclusive group and it's already pressed, don't do anything if (!mExclusive) { // release the button mPressed = false; callEventHandlers(); } } else { // if the button is an exclusive group and isn't pressed, release all the buttons in the group first if (mExclusive) { getParent()->releaseGroup(getGroup()); } // press the button mPressed = true; callEventHandlers(); } } } void MovingGraph::addEventHandler(const std::function<void(bool)>& aEventHandler) { mEventHandlers.push_back(aEventHandler); } void MovingGraph::callEventHandlers() { for (int i = 0; i < mEventHandlers.size(); i++) { mEventHandlers[i](mPressed); } } void MovingGraph::update() { if (mContinuous && mStateless && isActive()) { callEventHandlers(); } mBuffer.push_back( *mLinkedValue ); if( mBuffer.size() >= mBufferSize ) { mBuffer.erase( mBuffer.begin(), mBuffer.begin() + 1 ); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTextPropertySetContext.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 08:38:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX #define _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX #ifndef _XMLOFF_XMLPROPERTYSETCONTEXT_HXX #include "xmlprcon.hxx" #endif class XMLTextPropertySetContext : public SvXMLPropertySetContext { // SvXMLImportContextRef xTabStop; // SvXMLImportContextRef xBackground; // SvXMLImportContextRef xDropCap; ::rtl::OUString& rDropCapTextStyleName; public: XMLTextPropertySetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList, sal_uInt32 nFamily, ::std::vector< XMLPropertyState > &rProps, const UniReference < SvXMLImportPropertyMapper > &rMap, ::rtl::OUString& rDopCapTextStyleName ); virtual ~XMLTextPropertySetContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList, ::std::vector< XMLPropertyState > &rProperties, const XMLPropertyState& rProp); }; #endif // _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.298); FILE MERGED 2005/09/05 14:40:05 rt 1.2.298.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextPropertySetContext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:25:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX #define _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX #ifndef _XMLOFF_XMLPROPERTYSETCONTEXT_HXX #include "xmlprcon.hxx" #endif class XMLTextPropertySetContext : public SvXMLPropertySetContext { // SvXMLImportContextRef xTabStop; // SvXMLImportContextRef xBackground; // SvXMLImportContextRef xDropCap; ::rtl::OUString& rDropCapTextStyleName; public: XMLTextPropertySetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList, sal_uInt32 nFamily, ::std::vector< XMLPropertyState > &rProps, const UniReference < SvXMLImportPropertyMapper > &rMap, ::rtl::OUString& rDopCapTextStyleName ); virtual ~XMLTextPropertySetContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList, ::std::vector< XMLPropertyState > &rProperties, const XMLPropertyState& rProp); }; #endif // _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX <|endoftext|>
<commit_before>// ToolFactory.cc for Fluxbox // Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // // 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 "ToolFactory.hh" // Tools #include "ButtonTool.hh" #include "ClockTool.hh" #include "SystemTray.hh" #include "IconbarTool.hh" #include "WorkspaceNameTool.hh" #include "ArrowButton.hh" // Themes #include "WorkspaceNameTheme.hh" #include "ButtonTheme.hh" #include "FbTk/CommandParser.hh" #include "Screen.hh" #include "Toolbar.hh" #include "fluxbox.hh" #include <utility> namespace { class ShowMenuAboveToolbar: public FbTk::Command<void> { public: explicit ShowMenuAboveToolbar(Toolbar &tbar):m_tbar(tbar) { } void execute() { // get last button pos const XEvent &event = Fluxbox::instance()->lastEvent(); int head = m_tbar.screen().getHead(event.xbutton.x_root, event.xbutton.y_root); std::pair<int, int> m = m_tbar.screen().clampToHead( head, event.xbutton.x_root - (m_tbar.menu().width() / 2), event.xbutton.y_root - (m_tbar.menu().height() / 2), m_tbar.menu().width(), m_tbar.menu().height()); m_tbar.menu().setScreen(m_tbar.screen().getHeadX(head), m_tbar.screen().getHeadY(head), m_tbar.screen().getHeadWidth(head), m_tbar.screen().getHeadHeight(head)); m_tbar.menu().move(m.first, m.second); m_tbar.menu().show(); m_tbar.menu().grabInputFocus(); } private: Toolbar &m_tbar; }; }; ToolFactory::ToolFactory(BScreen &screen):m_screen(screen), m_clock_theme(screen.screenNumber(), "toolbar.clock", "Toolbar.Clock"), m_button_theme(new ButtonTheme(screen.screenNumber(), "toolbar.button", "Toolbar.Button", "toolbar.clock", "Toolbar.Clock")), m_workspace_theme(new WorkspaceNameTheme(screen.screenNumber(), "toolbar.workspace", "Toolbar.Workspace")), m_systray_theme(new ButtonTheme(screen.screenNumber(), "toolbar.systray", "Toolbar.Systray", "toolbar.clock", "Toolbar.Systray")), m_focused_iconbar_theme(screen.screenNumber(), "toolbar.iconbar.focused", "Toolbar.Iconbar.Focused"), m_unfocused_iconbar_theme(screen.screenNumber(), "toolbar.iconbar.unfocused", "Toolbar.Iconbar.Unfocused") { } ToolbarItem *ToolFactory::create(const std::string &name, const FbTk::FbWindow &parent, Toolbar &tbar) { ToolbarItem * item = 0; unsigned int button_size = 24; if (tbar.theme()->buttonSize() > 0) button_size = tbar.theme()->buttonSize(); if (name == "workspacename") { WorkspaceNameTool *witem = new WorkspaceNameTool(parent, *m_workspace_theme, screen()); using namespace FbTk; RefCount<Command<void> > showmenu(new ShowMenuAboveToolbar(tbar)); witem->button().setOnClick(showmenu); item = witem; } else if (name == "iconbar") { item = new IconbarTool(parent, m_focused_iconbar_theme, m_unfocused_iconbar_theme, screen(), tbar.menu()); } else if (name == "systemtray") { item = new SystemTray(parent, dynamic_cast<ButtonTheme &>(*m_systray_theme), screen()); } else if (name == "clock") { item = new ClockTool(parent, m_clock_theme, screen(), tbar.menu()); } else if (name == "nextworkspace" || name == "prevworkspace") { FbTk::RefCount<FbTk::Command<void> > cmd(FbTk::CommandParser<void>::instance().parse(name)); if (*cmd == 0) // we need a command return 0; // TODO maybe direction of arrows should depend on toolbar layout ? FbTk::FbDrawable::TriangleType arrow_type = FbTk::FbDrawable::LEFT; if (name == "nextworkspace") arrow_type = FbTk::FbDrawable::RIGHT; ArrowButton *win = new ArrowButton(arrow_type, parent, 0, 0, button_size, button_size); win->setOnClick(cmd); item = new ButtonTool(win, ToolbarItem::SQUARE, dynamic_cast<ButtonTheme &>(*m_button_theme), screen().imageControl()); } else if (name == "nextwindow" || name == "prevwindow") { FbTk::RefCount<FbTk::Command<void> > cmd(FbTk::CommandParser<void>::instance().parse(name)); if (*cmd == 0) // we need a command return 0; FbTk::FbDrawable::TriangleType arrow_type = FbTk::FbDrawable::LEFT; if (name == "nextwindow") arrow_type = FbTk::FbDrawable::RIGHT; ArrowButton *win = new ArrowButton(arrow_type, parent, 0, 0, button_size, button_size); win->setOnClick(cmd); item = new ButtonTool(win, ToolbarItem::SQUARE, dynamic_cast<ButtonTheme &>(*m_button_theme), screen().imageControl()); } if (item) item->renderTheme(tbar.alpha()); return item; } void ToolFactory::updateThemes() { m_clock_theme.reconfigTheme(); m_focused_iconbar_theme.reconfigTheme(); m_unfocused_iconbar_theme.reconfigTheme(); m_button_theme->reconfigTheme(); m_workspace_theme->reconfigTheme(); } int ToolFactory::maxFontHeight() { unsigned int max_height = 0; if (max_height < m_clock_theme.font().height()) max_height = m_clock_theme.font().height(); if (max_height < m_focused_iconbar_theme.text().font().height()) max_height = m_focused_iconbar_theme.text().font().height(); if (max_height < m_unfocused_iconbar_theme.text().font().height()) max_height = m_unfocused_iconbar_theme.text().font().height(); if (max_height < m_workspace_theme->font().height()) max_height = m_workspace_theme->font().height(); return max_height; } <commit_msg>little hack to allow arbitrary commands in the toolbar<commit_after>// ToolFactory.cc for Fluxbox // Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // // 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 "ToolFactory.hh" // Tools #include "ButtonTool.hh" #include "ClockTool.hh" #include "SystemTray.hh" #include "IconbarTool.hh" #include "WorkspaceNameTool.hh" #include "ArrowButton.hh" // Themes #include "WorkspaceNameTheme.hh" #include "ButtonTheme.hh" #include "FbTk/CommandParser.hh" #include "Screen.hh" #include "Toolbar.hh" #include "fluxbox.hh" #include <utility> namespace { class ShowMenuAboveToolbar: public FbTk::Command<void> { public: explicit ShowMenuAboveToolbar(Toolbar &tbar):m_tbar(tbar) { } void execute() { // get last button pos const XEvent &event = Fluxbox::instance()->lastEvent(); int head = m_tbar.screen().getHead(event.xbutton.x_root, event.xbutton.y_root); std::pair<int, int> m = m_tbar.screen().clampToHead( head, event.xbutton.x_root - (m_tbar.menu().width() / 2), event.xbutton.y_root - (m_tbar.menu().height() / 2), m_tbar.menu().width(), m_tbar.menu().height()); m_tbar.menu().setScreen(m_tbar.screen().getHeadX(head), m_tbar.screen().getHeadY(head), m_tbar.screen().getHeadWidth(head), m_tbar.screen().getHeadHeight(head)); m_tbar.menu().move(m.first, m.second); m_tbar.menu().show(); m_tbar.menu().grabInputFocus(); } private: Toolbar &m_tbar; }; }; ToolFactory::ToolFactory(BScreen &screen):m_screen(screen), m_clock_theme(screen.screenNumber(), "toolbar.clock", "Toolbar.Clock"), m_button_theme(new ButtonTheme(screen.screenNumber(), "toolbar.button", "Toolbar.Button", "toolbar.clock", "Toolbar.Clock")), m_workspace_theme(new WorkspaceNameTheme(screen.screenNumber(), "toolbar.workspace", "Toolbar.Workspace")), m_systray_theme(new ButtonTheme(screen.screenNumber(), "toolbar.systray", "Toolbar.Systray", "toolbar.clock", "Toolbar.Systray")), m_focused_iconbar_theme(screen.screenNumber(), "toolbar.iconbar.focused", "Toolbar.Iconbar.Focused"), m_unfocused_iconbar_theme(screen.screenNumber(), "toolbar.iconbar.unfocused", "Toolbar.Iconbar.Unfocused") { } ToolbarItem *ToolFactory::create(const std::string &name, const FbTk::FbWindow &parent, Toolbar &tbar) { ToolbarItem * item = 0; unsigned int button_size = 24; if (tbar.theme()->buttonSize() > 0) button_size = tbar.theme()->buttonSize(); if (name == "workspacename") { WorkspaceNameTool *witem = new WorkspaceNameTool(parent, *m_workspace_theme, screen()); using namespace FbTk; RefCount<Command<void> > showmenu(new ShowMenuAboveToolbar(tbar)); witem->button().setOnClick(showmenu); item = witem; } else if (name == "iconbar") { item = new IconbarTool(parent, m_focused_iconbar_theme, m_unfocused_iconbar_theme, screen(), tbar.menu()); } else if (name == "systemtray") { item = new SystemTray(parent, dynamic_cast<ButtonTheme &>(*m_systray_theme), screen()); } else if (name == "clock") { item = new ClockTool(parent, m_clock_theme, screen(), tbar.menu()); } else if (name == "nextworkspace" || name == "prevworkspace") { FbTk::RefCount<FbTk::Command<void> > cmd(FbTk::CommandParser<void>::instance().parse(name)); if (*cmd == 0) // we need a command return 0; // TODO maybe direction of arrows should depend on toolbar layout ? FbTk::FbDrawable::TriangleType arrow_type = FbTk::FbDrawable::LEFT; if (name == "nextworkspace") arrow_type = FbTk::FbDrawable::RIGHT; ArrowButton *win = new ArrowButton(arrow_type, parent, 0, 0, button_size, button_size); win->setOnClick(cmd); item = new ButtonTool(win, ToolbarItem::SQUARE, dynamic_cast<ButtonTheme &>(*m_button_theme), screen().imageControl()); } else { FbTk::RefCount<FbTk::Command<void> > cmd(FbTk::CommandParser<void>::instance().parse(name)); if (*cmd == 0) // we need a command return 0; FbTk::FbDrawable::TriangleType arrow_type = FbTk::FbDrawable::LEFT; if (name == "nextwindow") arrow_type = FbTk::FbDrawable::RIGHT; ArrowButton *win = new ArrowButton(arrow_type, parent, 0, 0, button_size, button_size); win->setOnClick(cmd); item = new ButtonTool(win, ToolbarItem::SQUARE, dynamic_cast<ButtonTheme &>(*m_button_theme), screen().imageControl()); } if (item) item->renderTheme(tbar.alpha()); return item; } void ToolFactory::updateThemes() { m_clock_theme.reconfigTheme(); m_focused_iconbar_theme.reconfigTheme(); m_unfocused_iconbar_theme.reconfigTheme(); m_button_theme->reconfigTheme(); m_workspace_theme->reconfigTheme(); } int ToolFactory::maxFontHeight() { unsigned int max_height = 0; if (max_height < m_clock_theme.font().height()) max_height = m_clock_theme.font().height(); if (max_height < m_focused_iconbar_theme.text().font().height()) max_height = m_focused_iconbar_theme.text().font().height(); if (max_height < m_unfocused_iconbar_theme.text().font().height()) max_height = m_unfocused_iconbar_theme.text().font().height(); if (max_height < m_workspace_theme->font().height()) max_height = m_workspace_theme->font().height(); return max_height; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/log.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/consteval.h" #include "kernel/celltypes.h" #include "fsmdata.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN static RTLIL::Module *module; static SigMap assign_map; typedef std::pair<RTLIL::Cell*, RTLIL::IdString> sig2driver_entry_t; static SigSet<sig2driver_entry_t> sig2driver, sig2user; static std::set<RTLIL::Cell*> muxtree_cells; static SigPool sig_at_port; static bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, pool<Cell*> &recursion_monitor) { if (sig.is_fully_const() || old_sig == sig) { return true; } if (sig_at_port.check_any(assign_map(sig))) { return false; } std::set<sig2driver_entry_t> cellport_list; sig2driver.find(sig, cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$mux" && cellport.first->type != "$pmux") || cellport.second != "\\Y") { return false; } if (recursion_monitor.count(cellport.first)) { log_warning("logic loop in mux tree at signal %s in module %s.\n", log_signal(sig), RTLIL::id2cstr(module->name)); return false; } recursion_monitor.insert(cellport.first); RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort("\\A")); RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort("\\B")); if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor)) { recursion_monitor.erase(cellport.first); return false; } for (int i = 0; i < sig_b.size(); i += sig_a.size()) if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor)) { recursion_monitor.erase(cellport.first); return false; } recursion_monitor.erase(cellport.first); muxtree_cells.insert(cellport.first); } return true; } static bool check_state_users(RTLIL::SigSpec sig) { if (sig_at_port.check_any(assign_map(sig))) return false; std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig, cellport_list); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; if (muxtree_cells.count(cell) > 0) continue; if (cell->type == "$logic_not" && assign_map(cell->getPort("\\A")) == sig) continue; if (cellport.second != "\\A" && cellport.second != "\\B") return false; if (!cell->hasPort("\\A") || !cell->hasPort("\\B") || !cell->hasPort("\\Y")) return false; for (auto &port_it : cell->connections()) if (port_it.first != "\\A" && port_it.first != "\\B" && port_it.first != "\\Y") return false; if (assign_map(cell->getPort("\\A")) == sig && cell->getPort("\\B").is_fully_const()) continue; if (assign_map(cell->getPort("\\B")) == sig && cell->getPort("\\A").is_fully_const()) continue; return false; } return true; } static void detect_fsm(RTLIL::Wire *wire) { bool has_fsm_encoding_attr = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() != "none"; bool has_fsm_encoding_none = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() == "none"; bool has_init_attr = wire->attributes.count("\\init") > 0; bool is_module_port = sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire))); bool looks_like_state_reg = false, looks_like_good_state_reg = false; bool is_self_resetting = false; if (has_fsm_encoding_none) return; if (wire->width <= 1) { if (has_fsm_encoding_attr) { log_warning("Removing fsm_encoding attribute from 1-bit net: %s.%s\n", log_id(wire->module), log_id(wire)); wire->attributes.erase("\\fsm_encoding"); } return; } std::set<sig2driver_entry_t> cellport_list; sig2driver.find(RTLIL::SigSpec(wire), cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$dff" && cellport.first->type != "$adff") || cellport.second != "\\Q") continue; muxtree_cells.clear(); pool<Cell*> recursion_monitor; RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort("\\Q")); RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort("\\D")); if (sig_q != assign_map(wire)) continue; looks_like_state_reg = check_state_mux_tree(sig_q, sig_d, recursion_monitor); looks_like_good_state_reg = check_state_users(sig_q); if (!looks_like_state_reg) break; ConstEval ce(wire->module); std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig_q, cellport_list); auto sig_q_bits = sig_q.to_sigbit_pool(); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; bool set_output = false, clr_output = false; if (cell->type.in("$ne", "$reduce_or", "$reduce_bool")) set_output = true; if (cell->type.in("$eq", "$logic_not", "$reduce_and")) clr_output = true; if (set_output || clr_output) { for (auto &port_it : cell->connections()) if (cell->input(port_it.first)) for (auto bit : assign_map(port_it.second)) if (bit.wire != nullptr && !sig_q_bits.count(bit)) goto next_cellport; } if (set_output || clr_output) { for (auto &port_it : cell->connections()) if (cell->output(port_it.first)) { SigSpec sig = assign_map(port_it.second); Const val(set_output ? State::S1 : State::S0, GetSize(sig)); ce.set(sig, val); } } next_cellport:; } SigSpec sig_y = sig_d, sig_undef; if (ce.eval(sig_y, sig_undef)) is_self_resetting = true; } if (has_fsm_encoding_attr) { vector<string> warnings; if (is_module_port) warnings.push_back("Forcing FSM recoding on module port might result in larger circuit.\n"); if (!looks_like_good_state_reg) warnings.push_back("Users of state reg look like FSM recoding might result in larger circuit.\n"); if (has_init_attr) warnings.push_back("Initialization value on FSM state register is ignored. Possible simulation-synthesis mismatch!\n"); if (!looks_like_state_reg) warnings.push_back("Doesn't look like a proper FSM. Possible simulation-synthesis mismatch!\n"); if (is_self_resetting) warnings.push_back("FSM seems to be self-resetting. Possible simulation-synthesis mismatch!\n"); if (!warnings.empty()) { string warnmsg = stringf("Regarding the user-specified fsm_encoding attribute on %s.%s:\n", log_id(wire->module), log_id(wire)); for (auto w : warnings) warnmsg += " " + w; log_warning("%s", warnmsg.c_str()); } else { log("FSM state register %s.%s already has fsm_encoding attribute.\n", log_id(wire->module), log_id(wire)); } } else if (looks_like_state_reg && looks_like_good_state_reg && !has_init_attr && !is_module_port && !is_self_resetting) { log("Found FSM state register %s.%s.\n", log_id(wire->module), log_id(wire)); wire->attributes["\\fsm_encoding"] = RTLIL::Const("auto"); } else if (looks_like_state_reg) { log("Not marking %s.%s as FSM state register:\n", log_id(wire->module), log_id(wire)); if (is_module_port) log(" Register is connected to module port.\n"); if (!looks_like_good_state_reg) log(" Users of register don't seem to benefit from recoding.\n"); if (has_init_attr) log(" Register has an initialization value.\n"); if (is_self_resetting) log(" Circuit seems to be self-resetting.\n"); } } struct FsmDetectPass : public Pass { FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fsm_detect [selection]\n"); log("\n"); log("This pass detects finite state machines by identifying the state signal.\n"); log("The state signal is then marked by setting the attribute 'fsm_encoding'\n"); log("on the state signal to \"auto\".\n"); log("\n"); log("Existing 'fsm_encoding' attributes are not changed by this pass.\n"); log("\n"); log("Signals can be protected from being detected by this pass by setting the\n"); log("'fsm_encoding' attribute to \"none\".\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing FSM_DETECT pass (finding FSMs in design).\n"); extra_args(args, 1, design); CellTypes ct; ct.setup_internals(); ct.setup_internals_mem(); ct.setup_stdcells(); ct.setup_stdcells_mem(); for (auto &mod_it : design->modules_) { if (!design->selected(mod_it.second)) continue; module = mod_it.second; assign_map.set(module); sig2driver.clear(); sig2user.clear(); sig_at_port.clear(); for (auto &cell_it : module->cells_) for (auto &conn_it : cell_it.second->connections()) { if (ct.cell_output(cell_it.second->type, conn_it.first) || !ct.cell_known(cell_it.second->type)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2driver.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } if (!ct.cell_known(cell_it.second->type) || ct.cell_input(cell_it.second->type, conn_it.first)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2user.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } } for (auto &wire_it : module->wires_) if (wire_it.second->port_id != 0) sig_at_port.add(assign_map(RTLIL::SigSpec(wire_it.second))); for (auto &wire_it : module->wires_) if (design->selected(module, wire_it.second)) detect_fsm(wire_it.second); } assign_map.clear(); sig2driver.clear(); sig2user.clear(); muxtree_cells.clear(); } } FsmDetectPass; PRIVATE_NAMESPACE_END <commit_msg>fsm_detect: Add a cache to avoid excessive CPU usage for big mux networks.<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/log.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/consteval.h" #include "kernel/celltypes.h" #include "fsmdata.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN static RTLIL::Module *module; static SigMap assign_map; typedef std::pair<RTLIL::Cell*, RTLIL::IdString> sig2driver_entry_t; static SigSet<sig2driver_entry_t> sig2driver, sig2user; static std::set<RTLIL::Cell*> muxtree_cells; static SigPool sig_at_port; static bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, pool<Cell*> &recursion_monitor, dict<RTLIL::SigSpec, bool> &mux_tree_cache) { if (mux_tree_cache.find(sig) != mux_tree_cache.end()) return mux_tree_cache.at(sig); if (sig.is_fully_const() || old_sig == sig) { ret_true: mux_tree_cache[sig] = true; return true; } if (sig_at_port.check_any(assign_map(sig))) { ret_false: mux_tree_cache[sig] = false; return false; } std::set<sig2driver_entry_t> cellport_list; sig2driver.find(sig, cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$mux" && cellport.first->type != "$pmux") || cellport.second != "\\Y") { goto ret_false; } if (recursion_monitor.count(cellport.first)) { log_warning("logic loop in mux tree at signal %s in module %s.\n", log_signal(sig), RTLIL::id2cstr(module->name)); goto ret_false; } recursion_monitor.insert(cellport.first); RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort("\\A")); RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort("\\B")); if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor, mux_tree_cache)) { recursion_monitor.erase(cellport.first); goto ret_false; } for (int i = 0; i < sig_b.size(); i += sig_a.size()) if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor, mux_tree_cache)) { recursion_monitor.erase(cellport.first); goto ret_false; } recursion_monitor.erase(cellport.first); muxtree_cells.insert(cellport.first); } goto ret_true; } static bool check_state_users(RTLIL::SigSpec sig) { if (sig_at_port.check_any(assign_map(sig))) return false; std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig, cellport_list); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; if (muxtree_cells.count(cell) > 0) continue; if (cell->type == "$logic_not" && assign_map(cell->getPort("\\A")) == sig) continue; if (cellport.second != "\\A" && cellport.second != "\\B") return false; if (!cell->hasPort("\\A") || !cell->hasPort("\\B") || !cell->hasPort("\\Y")) return false; for (auto &port_it : cell->connections()) if (port_it.first != "\\A" && port_it.first != "\\B" && port_it.first != "\\Y") return false; if (assign_map(cell->getPort("\\A")) == sig && cell->getPort("\\B").is_fully_const()) continue; if (assign_map(cell->getPort("\\B")) == sig && cell->getPort("\\A").is_fully_const()) continue; return false; } return true; } static void detect_fsm(RTLIL::Wire *wire) { bool has_fsm_encoding_attr = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() != "none"; bool has_fsm_encoding_none = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() == "none"; bool has_init_attr = wire->attributes.count("\\init") > 0; bool is_module_port = sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire))); bool looks_like_state_reg = false, looks_like_good_state_reg = false; bool is_self_resetting = false; if (has_fsm_encoding_none) return; if (wire->width <= 1) { if (has_fsm_encoding_attr) { log_warning("Removing fsm_encoding attribute from 1-bit net: %s.%s\n", log_id(wire->module), log_id(wire)); wire->attributes.erase("\\fsm_encoding"); } return; } std::set<sig2driver_entry_t> cellport_list; sig2driver.find(RTLIL::SigSpec(wire), cellport_list); for (auto &cellport : cellport_list) { if ((cellport.first->type != "$dff" && cellport.first->type != "$adff") || cellport.second != "\\Q") continue; muxtree_cells.clear(); pool<Cell*> recursion_monitor; RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort("\\Q")); RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort("\\D")); dict<RTLIL::SigSpec, bool> mux_tree_cache; if (sig_q != assign_map(wire)) continue; looks_like_state_reg = check_state_mux_tree(sig_q, sig_d, recursion_monitor, mux_tree_cache); looks_like_good_state_reg = check_state_users(sig_q); if (!looks_like_state_reg) break; ConstEval ce(wire->module); std::set<sig2driver_entry_t> cellport_list; sig2user.find(sig_q, cellport_list); auto sig_q_bits = sig_q.to_sigbit_pool(); for (auto &cellport : cellport_list) { RTLIL::Cell *cell = cellport.first; bool set_output = false, clr_output = false; if (cell->type.in("$ne", "$reduce_or", "$reduce_bool")) set_output = true; if (cell->type.in("$eq", "$logic_not", "$reduce_and")) clr_output = true; if (set_output || clr_output) { for (auto &port_it : cell->connections()) if (cell->input(port_it.first)) for (auto bit : assign_map(port_it.second)) if (bit.wire != nullptr && !sig_q_bits.count(bit)) goto next_cellport; } if (set_output || clr_output) { for (auto &port_it : cell->connections()) if (cell->output(port_it.first)) { SigSpec sig = assign_map(port_it.second); Const val(set_output ? State::S1 : State::S0, GetSize(sig)); ce.set(sig, val); } } next_cellport:; } SigSpec sig_y = sig_d, sig_undef; if (ce.eval(sig_y, sig_undef)) is_self_resetting = true; } if (has_fsm_encoding_attr) { vector<string> warnings; if (is_module_port) warnings.push_back("Forcing FSM recoding on module port might result in larger circuit.\n"); if (!looks_like_good_state_reg) warnings.push_back("Users of state reg look like FSM recoding might result in larger circuit.\n"); if (has_init_attr) warnings.push_back("Initialization value on FSM state register is ignored. Possible simulation-synthesis mismatch!\n"); if (!looks_like_state_reg) warnings.push_back("Doesn't look like a proper FSM. Possible simulation-synthesis mismatch!\n"); if (is_self_resetting) warnings.push_back("FSM seems to be self-resetting. Possible simulation-synthesis mismatch!\n"); if (!warnings.empty()) { string warnmsg = stringf("Regarding the user-specified fsm_encoding attribute on %s.%s:\n", log_id(wire->module), log_id(wire)); for (auto w : warnings) warnmsg += " " + w; log_warning("%s", warnmsg.c_str()); } else { log("FSM state register %s.%s already has fsm_encoding attribute.\n", log_id(wire->module), log_id(wire)); } } else if (looks_like_state_reg && looks_like_good_state_reg && !has_init_attr && !is_module_port && !is_self_resetting) { log("Found FSM state register %s.%s.\n", log_id(wire->module), log_id(wire)); wire->attributes["\\fsm_encoding"] = RTLIL::Const("auto"); } else if (looks_like_state_reg) { log("Not marking %s.%s as FSM state register:\n", log_id(wire->module), log_id(wire)); if (is_module_port) log(" Register is connected to module port.\n"); if (!looks_like_good_state_reg) log(" Users of register don't seem to benefit from recoding.\n"); if (has_init_attr) log(" Register has an initialization value.\n"); if (is_self_resetting) log(" Circuit seems to be self-resetting.\n"); } } struct FsmDetectPass : public Pass { FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fsm_detect [selection]\n"); log("\n"); log("This pass detects finite state machines by identifying the state signal.\n"); log("The state signal is then marked by setting the attribute 'fsm_encoding'\n"); log("on the state signal to \"auto\".\n"); log("\n"); log("Existing 'fsm_encoding' attributes are not changed by this pass.\n"); log("\n"); log("Signals can be protected from being detected by this pass by setting the\n"); log("'fsm_encoding' attribute to \"none\".\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing FSM_DETECT pass (finding FSMs in design).\n"); extra_args(args, 1, design); CellTypes ct; ct.setup_internals(); ct.setup_internals_mem(); ct.setup_stdcells(); ct.setup_stdcells_mem(); for (auto &mod_it : design->modules_) { if (!design->selected(mod_it.second)) continue; module = mod_it.second; assign_map.set(module); sig2driver.clear(); sig2user.clear(); sig_at_port.clear(); for (auto &cell_it : module->cells_) for (auto &conn_it : cell_it.second->connections()) { if (ct.cell_output(cell_it.second->type, conn_it.first) || !ct.cell_known(cell_it.second->type)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2driver.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } if (!ct.cell_known(cell_it.second->type) || ct.cell_input(cell_it.second->type, conn_it.first)) { RTLIL::SigSpec sig = conn_it.second; assign_map.apply(sig); sig2user.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first)); } } for (auto &wire_it : module->wires_) if (wire_it.second->port_id != 0) sig_at_port.add(assign_map(RTLIL::SigSpec(wire_it.second))); for (auto &wire_it : module->wires_) if (design->selected(module, wire_it.second)) detect_fsm(wire_it.second); } assign_map.clear(); sig2driver.clear(); sig2user.clear(); muxtree_cells.clear(); } } FsmDetectPass; PRIVATE_NAMESPACE_END <|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. Some parts of this code are derived from ITK. See ITKCopyright.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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {QB_Toulouse_Ortho_PAN.tif}, {QB_Toulouse_Ortho_XS.tif} // OUTPUTS: {QB_Toulouse_Ortho_PXS.tif} // OUTPUTS: {pretty_QB_Toulouse_Ortho_PXS.png} // OUTPUTS: {pretty_QB_Toulouse_Ortho_PAN.png} // OUTPUTS: {pretty_QB_Toulouse_Ortho_XS.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // Here we are illustrating the use of the // \doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} for PAN-sharpening. // This example takes a PAN and the corresponding XS images as input. These // images are supposed to be registered. // // The fusion operation is defined as // // \begin{equation} // \frac{XS}{\mathrm{Filtered}(PAN)} PAN // \end{equation} // // Software Guide : EndLatex // Software Guide : BeginLatex // // Figure~\ref{fig:PANSHARP_FILTER} shows the result of applying // this PAN sharpening filter to a Quickbird image. // \begin{figure} // \center // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_PAN.eps} // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_XS.eps} // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_PXS.eps} // \itkcaption[Pan sharpening]{Result of applying // the \doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} to // orthorectified Quickbird // image. From left to right : original PAN image, original XS image and the // result of the PAN sharpening} // \label{fig:PANSHARP_FILTER} // \end{figure} // // Software Guide : EndLatex // Software Guide : BeginLatex // // We start by including the required header and declaring the main function: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbSimpleRcsPanSharpeningFusionImageFilter.h" // Software Guide : EndCodeSnippet #include "otbPrintableImageFilter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginCodeSnippet int main(int argc, char* argv[]) { // Software Guide : EndCodeSnippet if (argc < 7) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputPanchromatiqueImage inputMultiSpectralImage outputImage outputImagePrinted panchroPrinted msPrinted" << std::endl; return 1; } // Software Guide : BeginLatex // // We declare the different image type used here as well as the image reader. // Note that, the reader for the PAN image is templated by an // \doxygen{otb}{Image} while the XS reader uses an // \doxygen{otb}{VectorImage}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image<double, 2> ImageType; typedef otb::VectorImage<double, 2> VectorImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> ReaderVectorType; typedef otb::VectorImage<unsigned short int, 2> VectorIntImageType; ReaderVectorType::Pointer readerXS = ReaderVectorType::New(); ReaderType::Pointer readerPAN = ReaderType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We pass the filenames to the readers // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet readerPAN->SetFileName(argv[1]); readerXS->SetFileName(argv[2]); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We declare the fusion filter an set its inputs using the readers: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::SimpleRcsPanSharpeningFusionImageFilter <ImageType, VectorImageType, VectorIntImageType> FusionFilterType; FusionFilterType::Pointer fusion = FusionFilterType::New(); fusion->SetPanInput(readerPAN->GetOutput()); fusion->SetXsInput(readerXS->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::StreamingImageFileWriter<VectorIntImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[3]); writer->SetInput(fusion->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet typedef otb::PrintableImageFilter<VectorIntImageType> PrintableImageType; PrintableImageType::Pointer printable = PrintableImageType::New(); typedef otb::VectorImage<unsigned char, 2> VectorCharImageType; typedef otb::StreamingImageFileWriter<VectorCharImageType> PNGWriterType; PNGWriterType::Pointer pngwriter = PNGWriterType::New(); printable->SetInput(fusion->GetOutput()); printable->SetChannel(3); printable->SetChannel(2); printable->SetChannel(1); pngwriter->SetFileName(argv[4]); pngwriter->SetInput(printable->GetOutput()); pngwriter->Update(); typedef otb::PrintableImageFilter<VectorImageType> PrintableImageType2; PrintableImageType2::Pointer printable2 = PrintableImageType2::New(); printable2->SetInput(readerXS->GetOutput()); printable2->SetChannel(3); printable2->SetChannel(2); printable2->SetChannel(1); pngwriter->SetFileName(argv[6]); pngwriter->SetInput(printable2->GetOutput()); pngwriter->Update(); typedef otb::Image<unsigned char, 2> CharImageType; typedef itk::RescaleIntensityImageFilter <ImageType, CharImageType> RescalerType; RescalerType::Pointer rescaler = RescalerType::New(); typedef otb::StreamingImageFileWriter<CharImageType> PNGWriterType2; PNGWriterType2::Pointer pngwriter2 = PNGWriterType2::New(); rescaler->SetInput(readerPAN->GetOutput()); pngwriter2->SetFileName(argv[5]); pngwriter2->SetInput(rescaler->GetOutput()); pngwriter2->Update(); return EXIT_SUCCESS; } <commit_msg>DOC:add rescaleintensityfilter to create a printable image<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. Some parts of this code are derived from ITK. See ITKCopyright.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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {QB_Toulouse_Ortho_PAN.tif}, {QB_Toulouse_Ortho_XS.tif} // OUTPUTS: {QB_Toulouse_Ortho_PXS.tif} // OUTPUTS: {pretty_QB_Toulouse_Ortho_PXS.png} // OUTPUTS: {pretty_QB_Toulouse_Ortho_PAN.png} // OUTPUTS: {pretty_QB_Toulouse_Ortho_XS.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // Here we are illustrating the use of the // \doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} for PAN-sharpening. // This example takes a PAN and the corresponding XS images as input. These // images are supposed to be registered. // // The fusion operation is defined as // // \begin{equation} // \frac{XS}{\mathrm{Filtered}(PAN)} PAN // \end{equation} // // Software Guide : EndLatex // Software Guide : BeginLatex // // Figure~\ref{fig:PANSHARP_FILTER} shows the result of applying // this PAN sharpening filter to a Quickbird image. // \begin{figure} // \center // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_PAN.eps} // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_XS.eps} // \includegraphics[width=0.44\textwidth]{pretty_QB_Toulouse_Ortho_PXS.eps} // \itkcaption[Pan sharpening]{Result of applying // the \doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} to // orthorectified Quickbird // image. From left to right : original PAN image, original XS image and the // result of the PAN sharpening} // \label{fig:PANSHARP_FILTER} // \end{figure} // // Software Guide : EndLatex // Software Guide : BeginLatex // // We start by including the required header and declaring the main function: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbSimpleRcsPanSharpeningFusionImageFilter.h" // Software Guide : EndCodeSnippet #include "otbPrintableImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "otbImageToVectorImageCastFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" // Software Guide : BeginCodeSnippet int main(int argc, char* argv[]) { // Software Guide : EndCodeSnippet if (argc < 7) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputPanchromatiqueImage inputMultiSpectralImage outputImage outputImagePrinted panchroPrinted msPrinted" << std::endl; return 1; } // Software Guide : BeginLatex // // We declare the different image type used here as well as the image reader. // Note that, the reader for the PAN image is templated by an // \doxygen{otb}{Image} while the XS reader uses an // \doxygen{otb}{VectorImage}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image<double, 2> ImageType; typedef otb::VectorImage<double, 2> VectorImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> ReaderVectorType; typedef otb::VectorImage<unsigned short int, 2> VectorIntImageType; ReaderVectorType::Pointer readerXS = ReaderVectorType::New(); ReaderType::Pointer readerPAN = ReaderType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We pass the filenames to the readers // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet readerPAN->SetFileName(argv[1]); readerXS->SetFileName(argv[2]); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We declare the fusion filter an set its inputs using the readers: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::SimpleRcsPanSharpeningFusionImageFilter <ImageType, VectorImageType, VectorIntImageType> FusionFilterType; FusionFilterType::Pointer fusion = FusionFilterType::New(); fusion->SetPanInput(readerPAN->GetOutput()); fusion->SetXsInput(readerXS->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::StreamingImageFileWriter<VectorIntImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[3]); writer->SetInput(fusion->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet typedef otb::PrintableImageFilter<VectorIntImageType> PrintableImageType; PrintableImageType::Pointer printable = PrintableImageType::New(); typedef otb::VectorImage<unsigned char, 2> VectorCharImageType; typedef otb::StreamingImageFileWriter<VectorCharImageType> PNGWriterType; PNGWriterType::Pointer pngwriter = PNGWriterType::New(); printable->SetInput(fusion->GetOutput()); printable->SetChannel(3); printable->SetChannel(2); printable->SetChannel(1); pngwriter->SetFileName(argv[4]); pngwriter->SetInput(printable->GetOutput()); pngwriter->Update(); typedef otb::PrintableImageFilter<VectorImageType> PrintableImageType2; PrintableImageType2::Pointer printable2 = PrintableImageType2::New(); printable2->SetInput(readerXS->GetOutput()); printable2->SetChannel(3); printable2->SetChannel(2); printable2->SetChannel(1); pngwriter->SetFileName(argv[6]); pngwriter->SetInput(printable2->GetOutput()); pngwriter->Update(); typedef otb::ImageToVectorImageCastFilter<ImageType,VectorImageType> VectorCastFilterType; VectorCastFilterType::Pointer vectorCastFilter = VectorCastFilterType::New(); PNGWriterType::Pointer pngwriterPan = PNGWriterType::New(); vectorCastFilter->SetInput(readerPAN->GetOutput()); PrintableImageType2::Pointer printable3 = PrintableImageType2::New(); printable3->SetInput(vectorCastFilter->GetOutput()); printable3->SetChannel(1); printable3->SetChannel(1); printable3->SetChannel(1); pngwriterPan->SetFileName(argv[5]); pngwriterPan->SetInput(printable3->GetOutput()); pngwriterPan->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// HLine.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "HLine.h" #include "HILine.h" #include "HCircle.h" #include "HArc.h" #include "../interface/Tool.h" #include "../interface/PropertyDouble.h" #include "../interface/PropertyLength.h" #include "../interface/PropertyVertex.h" #include "Gripper.h" #include "Sketch.h" #include "SolveSketch.h" HLine::HLine(const HLine &line):EndedObject(&line.color){ operator=(line); } HLine::HLine(const gp_Pnt &a, const gp_Pnt &b, const HeeksColor* col):EndedObject(col){ A->m_p = a; B->m_p = b; color = *col; } HLine::~HLine(){ } const HLine& HLine::operator=(const HLine &b){ EndedObject::operator=(b); color = b.color; return *this; } HLine* line_for_tool = NULL; class SetLineHorizontal:public Tool{ public: void Run(){ line_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleHorizontal); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Horizontal");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this line to be horizontal");} }; static SetLineHorizontal horizontal_line_toggle; class SetLineVertical:public Tool{ public: void Run(){ line_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleVertical); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Vertical");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this line to be vertical");} }; static SetLineVertical vertical_line_toggle; class SetLineLength:public Tool{ public: void Run(){ line_for_tool->SetLineLengthConstraint(line_for_tool->A->m_p.Distance(line_for_tool->B->m_p)); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Line Length");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this lines length as constrained");} }; static SetLineLength line_length_toggle; void HLine::GetTools(std::list<Tool*>* t_list, const wxPoint* p) { line_for_tool = this; t_list->push_back(&horizontal_line_toggle); t_list->push_back(&vertical_line_toggle); t_list->push_back(&line_length_toggle); } void HLine::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(color); } GLfloat save_depth_range[2]; if(marked){ glGetFloatv(GL_DEPTH_RANGE, save_depth_range); glDepthRange(0, 0); glLineWidth(2); } glBegin(GL_LINES); glVertex3d(A->m_p.X(), A->m_p.Y(), A->m_p.Z()); glVertex3d(B->m_p.X(), B->m_p.Y(), B->m_p.Z()); glEnd(); if(marked){ glLineWidth(1); glDepthRange(save_depth_range[0], save_depth_range[1]); } if(!A->m_p.IsEqual(B->m_p, wxGetApp().m_geom_tol)) { gp_Pnt mid_point = A->m_p.XYZ() + (B->m_p.XYZ() - A->m_p.XYZ())/2; gp_Dir dir = B->m_p.XYZ() - mid_point.XYZ(); gp_Ax1 ax(mid_point,dir); //gp_Dir up(0,0,1); //ax.Rotate(gp_Ax1(mid_point,up),Pi/2); ConstrainedObject::glCommands(color,ax); } EndedObject::glCommands(select,marked,no_color); } void HLine::Draw(wxDC& dc) { wxGetApp().PlotSetColor(color); double s[3], e[3]; extract(A->m_p, s); extract(B->m_p, e); wxGetApp().PlotLine(s, e); } HeeksObj *HLine::MakeACopy(void)const{ HLine *new_object = new HLine(*this); return new_object; } void HLine::GetBox(CBox &box){ box.Insert(A->m_p.X(), A->m_p.Y(), A->m_p.Z()); box.Insert(B->m_p.X(), B->m_p.Y(), B->m_p.Z()); } void HLine::GetGripperPositions(std::list<GripData> *list, bool just_for_endof){ EndedObject::GetGripperPositions(list,just_for_endof); } static void on_set_start(const double *vt, HeeksObj* object){ ((HLine*)object)->A->m_p = make_point(vt); wxGetApp().Repaint(); } static void on_set_end(const double *vt, HeeksObj* object){ ((HLine*)object)->B->m_p = make_point(vt); wxGetApp().Repaint(); } static void on_set_length(double v, HeeksObj* object){ ((HLine*)object)->SetLineLength(v); if(wxGetApp().autosolve_constraints) SolveSketch((CSketch*)object->Owner()); wxGetApp().Repaint(); } void HLine::GetProperties(std::list<Property *> *list){ double a[3], b[3]; extract(A->m_p, a); extract(B->m_p, b); list->push_back(new PropertyVertex(_("start"), a, this, on_set_start)); list->push_back(new PropertyVertex(_("end"), b, this, on_set_end)); double length = A->m_p.Distance(B->m_p); list->push_back(new PropertyLength(_("Length"), length, this, on_set_length)); HeeksObj::GetProperties(list); } bool HLine::FindNearPoint(const double* ray_start, const double* ray_direction, double *point){ gp_Lin ray(make_point(ray_start), make_vector(ray_direction)); gp_Pnt p1, p2; ClosestPointsOnLines(GetLine(), ray, p1, p2); if(!Intersects(p1)) return false; extract(p1, point); return true; } bool HLine::FindPossTangentPoint(const double* ray_start, const double* ray_direction, double *point){ // any point on this line is a possible tangent point return FindNearPoint(ray_start, ray_direction, point); } gp_Lin HLine::GetLine()const{ gp_Vec v(A->m_p, B->m_p); return gp_Lin(A->m_p, v); } int HLine::Intersects(const HeeksObj *object, std::list< double > *rl)const{ int numi = 0; switch(object->GetType()) { case LineType: { // The OpenCascade libraries throw an exception when one tries to // create a gp_Lin() object using a vector that doesn't point // anywhere. If this is a zero-length line then we're in // trouble. Don't bother with it. if ((A->m_p.X() == B->m_p.X()) && (A->m_p.Y() == B->m_p.Y()) && (A->m_p.Z() == B->m_p.Z())) break; gp_Pnt pnt; if(intersect(GetLine(), ((HLine*)object)->GetLine(), pnt)) { if(Intersects(pnt) && ((HLine*)object)->Intersects(pnt)){ if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case ILineType: { gp_Pnt pnt; if(intersect(GetLine(), ((HILine*)object)->GetLine(), pnt)) { if(Intersects(pnt)){ if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case ArcType: { std::list<gp_Pnt> plist; intersect(GetLine(), ((HArc*)object)->GetCircle(), plist); for(std::list<gp_Pnt>::iterator It = plist.begin(); It != plist.end(); It++) { gp_Pnt& pnt = *It; if(Intersects(pnt) && ((HArc*)object)->Intersects(pnt)) { if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case CircleType: { std::list<gp_Pnt> plist; intersect(GetLine(), ((HCircle*)object)->GetCircle(), plist); for(std::list<gp_Pnt>::iterator It = plist.begin(); It != plist.end(); It++) { gp_Pnt& pnt = *It; if(Intersects(pnt)) { if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; } return numi; } bool HLine::Intersects(const gp_Pnt &pnt)const { gp_Lin this_line = GetLine(); if(!intersect(pnt, this_line))return false; // check it lies between A and B gp_Vec v = this_line.Direction(); double dpA = gp_Vec(A->m_p.XYZ()) * v; double dpB = gp_Vec(B->m_p.XYZ()) * v; double dp = gp_Vec(pnt.XYZ()) * v; return dp >= dpA - wxGetApp().m_geom_tol && dp <= dpB + wxGetApp().m_geom_tol; } void HLine::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm, bool want_start_point)const{ if(want_start_point) { double p[3]; extract(A->m_p, p); (*callbackfunc)(p); } double p[3]; extract(B->m_p, p); (*callbackfunc)(p); } gp_Vec HLine::GetSegmentVector(double fraction) { gp_Vec line_vector(A->m_p, B->m_p); if(line_vector.Magnitude() < 0.000000001)return gp_Vec(0, 0, 0); return gp_Vec(A->m_p, B->m_p).Normalized(); } void HLine::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = new TiXmlElement( "Line" ); root->LinkEndChild( element ); element->SetAttribute("col", color.COLORREF_color()); #ifdef OLDLINES element->SetDoubleAttribute("sx", A->m_p.X()); element->SetDoubleAttribute("sy", A->m_p.Y()); element->SetDoubleAttribute("sz", A->m_p.Z()); element->SetDoubleAttribute("ex", B->m_p.X()); element->SetDoubleAttribute("ey", B->m_p.Y()); element->SetDoubleAttribute("ez", B->m_p.Z()); #endif WriteBaseXML(element); } // static member function HeeksObj* HLine::ReadFromXMLElement(TiXmlElement* pElem) { gp_Pnt p0, p1; HeeksColor c; // get the attributes for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next()) { std::string name(a->Name()); if(name == "col"){c = HeeksColor(a->IntValue());} else if(name == "sx"){p0.SetX(a->DoubleValue());} else if(name == "sy"){p0.SetY(a->DoubleValue());} else if(name == "sz"){p0.SetZ(a->DoubleValue());} else if(name == "ex"){p1.SetX(a->DoubleValue());} else if(name == "ey"){p1.SetY(a->DoubleValue());} else if(name == "ez"){p1.SetZ(a->DoubleValue());} } HLine* new_object = new HLine(p0, p1, &c); new_object->ReadBaseXML(pElem); if(new_object->GetNumChildren()>2) { //This is a new style line, with children points new_object->Remove(new_object->A); new_object->Remove(new_object->B); delete new_object->A; delete new_object->B; new_object->A = (HPoint*)new_object->GetFirstChild(); new_object->B = (HPoint*)new_object->GetNextChild(); new_object->A->m_draw_unselected = false; new_object->B->m_draw_unselected = false; } return new_object; } void HLine::Reverse() { HPoint* temp = A; A = B; B = temp; m_objects.pop_front(); m_objects.pop_front(); m_objects.push_front(B); m_objects.push_front(A); } <commit_msg>Fixed problem where, if the imported line was of zero length, OpenCascade would throw a construction error when creating a gp_Vec frmo it. If a line is of zero length, we discard the object when reading in the line object.<commit_after>// HLine.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "HLine.h" #include "HILine.h" #include "HCircle.h" #include "HArc.h" #include "../interface/Tool.h" #include "../interface/PropertyDouble.h" #include "../interface/PropertyLength.h" #include "../interface/PropertyVertex.h" #include "Gripper.h" #include "Sketch.h" #include "SolveSketch.h" HLine::HLine(const HLine &line):EndedObject(&line.color){ operator=(line); } HLine::HLine(const gp_Pnt &a, const gp_Pnt &b, const HeeksColor* col):EndedObject(col){ A->m_p = a; B->m_p = b; color = *col; } HLine::~HLine(){ } const HLine& HLine::operator=(const HLine &b){ EndedObject::operator=(b); color = b.color; return *this; } HLine* line_for_tool = NULL; class SetLineHorizontal:public Tool{ public: void Run(){ line_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleHorizontal); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Horizontal");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this line to be horizontal");} }; static SetLineHorizontal horizontal_line_toggle; class SetLineVertical:public Tool{ public: void Run(){ line_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleVertical); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Vertical");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this line to be vertical");} }; static SetLineVertical vertical_line_toggle; class SetLineLength:public Tool{ public: void Run(){ line_for_tool->SetLineLengthConstraint(line_for_tool->A->m_p.Distance(line_for_tool->B->m_p)); SolveSketch((CSketch*)line_for_tool->Owner()); wxGetApp().Repaint(); } const wxChar* GetTitle(){return _T("Toggle Line Length");} wxString BitmapPath(){return _T("new");} const wxChar* GetToolTip(){return _("Set this lines length as constrained");} }; static SetLineLength line_length_toggle; void HLine::GetTools(std::list<Tool*>* t_list, const wxPoint* p) { line_for_tool = this; t_list->push_back(&horizontal_line_toggle); t_list->push_back(&vertical_line_toggle); t_list->push_back(&line_length_toggle); } void HLine::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(color); } GLfloat save_depth_range[2]; if(marked){ glGetFloatv(GL_DEPTH_RANGE, save_depth_range); glDepthRange(0, 0); glLineWidth(2); } glBegin(GL_LINES); glVertex3d(A->m_p.X(), A->m_p.Y(), A->m_p.Z()); glVertex3d(B->m_p.X(), B->m_p.Y(), B->m_p.Z()); glEnd(); if(marked){ glLineWidth(1); glDepthRange(save_depth_range[0], save_depth_range[1]); } if(!A->m_p.IsEqual(B->m_p, wxGetApp().m_geom_tol)) { gp_Pnt mid_point = A->m_p.XYZ() + (B->m_p.XYZ() - A->m_p.XYZ())/2; gp_Dir dir = B->m_p.XYZ() - mid_point.XYZ(); gp_Ax1 ax(mid_point,dir); //gp_Dir up(0,0,1); //ax.Rotate(gp_Ax1(mid_point,up),Pi/2); ConstrainedObject::glCommands(color,ax); } EndedObject::glCommands(select,marked,no_color); } void HLine::Draw(wxDC& dc) { wxGetApp().PlotSetColor(color); double s[3], e[3]; extract(A->m_p, s); extract(B->m_p, e); wxGetApp().PlotLine(s, e); } HeeksObj *HLine::MakeACopy(void)const{ HLine *new_object = new HLine(*this); return new_object; } void HLine::GetBox(CBox &box){ box.Insert(A->m_p.X(), A->m_p.Y(), A->m_p.Z()); box.Insert(B->m_p.X(), B->m_p.Y(), B->m_p.Z()); } void HLine::GetGripperPositions(std::list<GripData> *list, bool just_for_endof){ EndedObject::GetGripperPositions(list,just_for_endof); } static void on_set_start(const double *vt, HeeksObj* object){ ((HLine*)object)->A->m_p = make_point(vt); wxGetApp().Repaint(); } static void on_set_end(const double *vt, HeeksObj* object){ ((HLine*)object)->B->m_p = make_point(vt); wxGetApp().Repaint(); } static void on_set_length(double v, HeeksObj* object){ ((HLine*)object)->SetLineLength(v); if(wxGetApp().autosolve_constraints) SolveSketch((CSketch*)object->Owner()); wxGetApp().Repaint(); } void HLine::GetProperties(std::list<Property *> *list){ double a[3], b[3]; extract(A->m_p, a); extract(B->m_p, b); list->push_back(new PropertyVertex(_("start"), a, this, on_set_start)); list->push_back(new PropertyVertex(_("end"), b, this, on_set_end)); double length = A->m_p.Distance(B->m_p); list->push_back(new PropertyLength(_("Length"), length, this, on_set_length)); HeeksObj::GetProperties(list); } bool HLine::FindNearPoint(const double* ray_start, const double* ray_direction, double *point){ // The OpenCascade libraries throw an exception when one tries to // create a gp_Lin() object using a vector that doesn't point // anywhere. If this is a zero-length line then we're in // trouble. Don't bother with it. if ((A->m_p.X() == B->m_p.X()) && (A->m_p.Y() == B->m_p.Y()) && (A->m_p.Z() == B->m_p.Z())) return(false); gp_Lin ray(make_point(ray_start), make_vector(ray_direction)); gp_Pnt p1, p2; ClosestPointsOnLines(GetLine(), ray, p1, p2); if(!Intersects(p1)) return false; extract(p1, point); return true; } bool HLine::FindPossTangentPoint(const double* ray_start, const double* ray_direction, double *point){ // any point on this line is a possible tangent point return FindNearPoint(ray_start, ray_direction, point); } gp_Lin HLine::GetLine()const{ gp_Vec v(A->m_p, B->m_p); return gp_Lin(A->m_p, v); } int HLine::Intersects(const HeeksObj *object, std::list< double > *rl)const{ int numi = 0; switch(object->GetType()) { case LineType: { // The OpenCascade libraries throw an exception when one tries to // create a gp_Lin() object using a vector that doesn't point // anywhere. If this is a zero-length line then we're in // trouble. Don't bother with it. if ((A->m_p.X() == B->m_p.X()) && (A->m_p.Y() == B->m_p.Y()) && (A->m_p.Z() == B->m_p.Z())) break; gp_Pnt pnt; if(intersect(GetLine(), ((HLine*)object)->GetLine(), pnt)) { if(Intersects(pnt) && ((HLine*)object)->Intersects(pnt)){ if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case ILineType: { gp_Pnt pnt; if(intersect(GetLine(), ((HILine*)object)->GetLine(), pnt)) { if(Intersects(pnt)){ if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case ArcType: { std::list<gp_Pnt> plist; intersect(GetLine(), ((HArc*)object)->GetCircle(), plist); for(std::list<gp_Pnt>::iterator It = plist.begin(); It != plist.end(); It++) { gp_Pnt& pnt = *It; if(Intersects(pnt) && ((HArc*)object)->Intersects(pnt)) { if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; case CircleType: { std::list<gp_Pnt> plist; intersect(GetLine(), ((HCircle*)object)->GetCircle(), plist); for(std::list<gp_Pnt>::iterator It = plist.begin(); It != plist.end(); It++) { gp_Pnt& pnt = *It; if(Intersects(pnt)) { if(rl)add_pnt_to_doubles(pnt, *rl); numi++; } } } break; } return numi; } bool HLine::Intersects(const gp_Pnt &pnt)const { gp_Lin this_line = GetLine(); if(!intersect(pnt, this_line))return false; // check it lies between A and B gp_Vec v = this_line.Direction(); double dpA = gp_Vec(A->m_p.XYZ()) * v; double dpB = gp_Vec(B->m_p.XYZ()) * v; double dp = gp_Vec(pnt.XYZ()) * v; return dp >= dpA - wxGetApp().m_geom_tol && dp <= dpB + wxGetApp().m_geom_tol; } void HLine::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm, bool want_start_point)const{ if(want_start_point) { double p[3]; extract(A->m_p, p); (*callbackfunc)(p); } double p[3]; extract(B->m_p, p); (*callbackfunc)(p); } gp_Vec HLine::GetSegmentVector(double fraction) { gp_Vec line_vector(A->m_p, B->m_p); if(line_vector.Magnitude() < 0.000000001)return gp_Vec(0, 0, 0); return gp_Vec(A->m_p, B->m_p).Normalized(); } void HLine::WriteXML(TiXmlNode *root) { TiXmlElement * element; element = new TiXmlElement( "Line" ); root->LinkEndChild( element ); element->SetAttribute("col", color.COLORREF_color()); #ifdef OLDLINES element->SetDoubleAttribute("sx", A->m_p.X()); element->SetDoubleAttribute("sy", A->m_p.Y()); element->SetDoubleAttribute("sz", A->m_p.Z()); element->SetDoubleAttribute("ex", B->m_p.X()); element->SetDoubleAttribute("ey", B->m_p.Y()); element->SetDoubleAttribute("ez", B->m_p.Z()); #endif WriteBaseXML(element); } // static member function HeeksObj* HLine::ReadFromXMLElement(TiXmlElement* pElem) { gp_Pnt p0, p1; HeeksColor c; // get the attributes for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next()) { std::string name(a->Name()); if(name == "col"){c = HeeksColor(a->IntValue());} else if(name == "sx"){p0.SetX(a->DoubleValue());} else if(name == "sy"){p0.SetY(a->DoubleValue());} else if(name == "sz"){p0.SetZ(a->DoubleValue());} else if(name == "ex"){p1.SetX(a->DoubleValue());} else if(name == "ey"){p1.SetY(a->DoubleValue());} else if(name == "ez"){p1.SetZ(a->DoubleValue());} } // The OpenCascade libraries throw an exception when one tries to // create a gp_Lin() object using a vector that doesn't point // anywhere. If this is a zero-length line then we're in // trouble. Don't bother with it. if ((p0.X() == p1.X()) && (p0.Y() == p1.Y()) && (p0.Z() == p1.Z())) return(NULL); HLine* new_object = new HLine(p0, p1, &c); new_object->ReadBaseXML(pElem); if(new_object->GetNumChildren()>2) { //This is a new style line, with children points new_object->Remove(new_object->A); new_object->Remove(new_object->B); delete new_object->A; delete new_object->B; new_object->A = (HPoint*)new_object->GetFirstChild(); new_object->B = (HPoint*)new_object->GetNextChild(); new_object->A->m_draw_unselected = false; new_object->B->m_draw_unselected = false; } return new_object; } void HLine::Reverse() { HPoint* temp = A; A = B; B = temp; m_objects.pop_front(); m_objects.pop_front(); m_objects.push_front(B); m_objects.push_front(A); } <|endoftext|>
<commit_before>/* medDatabaseRemover.cpp --- * * Author: John Stark * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Jun 29 15:27:20 2010 (+0200) * Version: $Id$ * Last-Updated: Tue Jun 29 15:46:20 2010 (+0200) * By: Julien Wintz * Update #: 19 */ /* Commentary: * */ #include "medDatabaseRemover.h" #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractDataReader.h> #include <dtkCore/dtkAbstractDataWriter.h> #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkGlobal.h> #include <dtkLog/dtkLog.h> #include <medDatabaseController.h> #include <medStorage.h> #include <medDataIndex.h> #include <medAbstractDataImage.h> #define EXEC_QUERY(q) execQuery(q, __FILE__ , __LINE__ ) namespace { inline bool execQuery ( QSqlQuery & query, const char *file, int line ) { if ( ! query.exec() ) { qDebug() << file << "(" << line << ") :" << DTK_COLOR_FG_RED << query.lastError() << DTK_NO_COLOR; return false; } return true; } } class medDatabaseRemoverPrivate { public: medDataIndex index; QSqlDatabase * db; static const QString T_PATIENT; static const QString T_STUDY; static const QString T_SERIES; static const QString T_IMAGE; bool isCancelled; }; const QString medDatabaseRemoverPrivate::T_PATIENT = "patient"; const QString medDatabaseRemoverPrivate::T_STUDY = "study"; const QString medDatabaseRemoverPrivate::T_SERIES = "series"; const QString medDatabaseRemoverPrivate::T_IMAGE = "image"; medDatabaseRemover::medDatabaseRemover ( const medDataIndex &index_ ) : medJobItem(), d ( new medDatabaseRemoverPrivate ) { d->index = index_; d->db = medDatabaseController::instance()->database(); d->isCancelled = false; } medDatabaseRemover::~medDatabaseRemover ( void ) { delete d; d = NULL; } void medDatabaseRemover::run ( void ) { QSqlDatabase & db ( *d->db ); QSqlQuery ptQuery ( db ); const medDataIndex index = d->index; if ( index.isValidForPatient() ) { ptQuery.prepare ( "SELECT id FROM " + d->T_PATIENT + " WHERE id = :id" ); ptQuery.bindValue ( ":id", index.patientId() ); } else { ptQuery.prepare ( "SELECT id FROM " + d->T_PATIENT ); } EXEC_QUERY ( ptQuery ); while ( ptQuery.next() ) { if ( d->isCancelled ) break; int patientDbId = ptQuery.value ( 0 ).toInt(); QSqlQuery stQuery ( db ); if ( index.isValidForStudy() ) { stQuery.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE id = :id AND patient = :patient" ); stQuery.bindValue ( ":id", index.studyId() ); } else { stQuery.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE patient = :patient" ); } stQuery.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( stQuery ); while ( stQuery.next() ) { if ( d->isCancelled ) break; int studyDbId = stQuery.value ( 0 ).toInt(); QSqlQuery seQuery ( db ); if ( index.isValidForSeries() ) { seQuery.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE id = :id AND study = :study" ); seQuery.bindValue ( ":id", index.seriesId() ); } else { seQuery.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE study = :study" ); } seQuery.bindValue ( ":study", studyDbId ); EXEC_QUERY ( seQuery ); while ( seQuery.next() ) { if ( d->isCancelled ) break; int seriesDbId = seQuery.value ( 0 ).toInt(); QSqlQuery imQuery ( db ); if ( index.isValidForImage() ) { imQuery.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE id = :id AND series = :seriesId" ); imQuery.bindValue ( ":id", index.imageId() ); } else { imQuery.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE series = :series" ); } imQuery.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( imQuery ); imQuery.last(); double nbImage = imQuery.at(); EXEC_QUERY ( imQuery ); while ( imQuery.next() ) { int imageId = imQuery.value ( 0 ).toInt(); this->removeImage ( patientDbId, studyDbId, seriesDbId, imageId ); emit progressed ( imQuery.at() / nbImage * 100 ); } if ( this->isSeriesEmpty ( seriesDbId ) ) this->removeSeries ( patientDbId, studyDbId, seriesDbId ); } // seQuery.next if ( this->isStudyEmpty ( studyDbId ) ) this->removeStudy ( patientDbId, studyDbId ); } // stQuery.next if ( this->isPatientEmpty ( patientDbId ) ) this->removePatient ( patientDbId ); } // ptQuery.next emit removed ( index ); emit progress ( this, 100 ); emit progressed ( 100 ); if ( d->isCancelled ) emit failure ( this ); else emit success ( this ); return; } void medDatabaseRemover::removeImage ( int patientDbId, int studyDbId, int seriesDbId, int imageId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail FROM " + d->T_IMAGE + " WHERE id = :imageId " ); query.bindValue ( ":id", imageId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); } removeTableRow ( d->T_IMAGE, imageId ); } bool medDatabaseRemover::isSeriesEmpty ( int seriesDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE series = :series " ); query.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removeSeries ( int patientDbId, int studyDbId, int seriesDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail, path, name FROM " + d->T_SERIES + " WHERE id = :series " ); query.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( query ); QString thumbnail; if ( query.next() ) { thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); QString path = query.value ( 1 ).toString(); // if path is empty then it was an indexed series if ( !path.isNull() && !path.isEmpty() ) this->removeDataFile ( medDataIndex::makeSeriesIndex ( d->index.dataSourceId(), patientDbId, studyDbId, seriesDbId ) , path ); } removeTableRow ( d->T_SERIES, seriesDbId ); // we want to remove the directory if empty QFileInfo seriesFi ( medStorage::dataLocation() + thumbnail ); if ( seriesFi.dir().exists() ) seriesFi.dir().rmdir ( seriesFi.absolutePath() ); // only removes if empty } bool medDatabaseRemover::isStudyEmpty ( int studyDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE study = :study " ); query.bindValue ( ":study", studyDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removeStudy ( int patientDbId, int studyDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail, name, uid FROM " + d->T_STUDY + " WHERE id = :id " ); query.bindValue ( ":id", studyDbId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); } removeTableRow ( d->T_STUDY, studyDbId ); } bool medDatabaseRemover::isPatientEmpty ( int patientDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE patient = :patient " ); query.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removePatient ( int patientDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); QString patientName; QString patientBirthdate; QString patientId; query.prepare ( "SELECT thumbnail, patientId FROM " + d->T_PATIENT + " WHERE id = :patient " ); query.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); patientId = query.value ( 1 ).toString(); } removeTableRow ( d->T_PATIENT, patientDbId ); medDatabaseControllerImpl * dbi = medDatabaseController::instance(); QDir patientDir ( medStorage::dataLocation() + "/" + dbi->stringForPath ( patientId ) ); if ( patientDir.exists() ) patientDir.rmdir ( patientDir.path() ); // only removes if empty } void medDatabaseRemover::removeTableRow ( const QString &table, int id ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "DELETE FROM " + table + " WHERE id = :id" ); query.bindValue ( ":id", id ); EXEC_QUERY ( query ); } void medDatabaseRemover::removeFile ( const QString & filename ) { QFile file ( medStorage::dataLocation() + filename ); file.remove(); } void medDatabaseRemover::onCancel ( QObject* ) { d->isCancelled = true; } void medDatabaseRemover::removeDataFile ( const medDataIndex &index, const QString & filename ) { QFileInfo fi ( filename ); const QString suffix = fi.suffix(); const QString mhd ( "mhd" ); const QString mha ( "mha" ); if ( suffix == mhd ) { QString mhaFile ( filename ); mhaFile.chop ( mhd.length() ); mhaFile += mha; this->removeFile ( mhaFile ); } else if ( suffix == mha ) { QString mhdFile ( filename ); mhdFile.chop ( mha.length() ); mhdFile += mhd; this->removeFile ( mhdFile ); } this->removeFile ( filename ); } <commit_msg>Avoid to use EXEC_QUERY ( imQuery ); two times<commit_after>/* medDatabaseRemover.cpp --- * * Author: John Stark * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Jun 29 15:27:20 2010 (+0200) * Version: $Id$ * Last-Updated: Tue Jun 29 15:46:20 2010 (+0200) * By: Julien Wintz * Update #: 19 */ /* Commentary: * */ #include "medDatabaseRemover.h" #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractDataReader.h> #include <dtkCore/dtkAbstractDataWriter.h> #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkGlobal.h> #include <dtkLog/dtkLog.h> #include <medDatabaseController.h> #include <medStorage.h> #include <medDataIndex.h> #include <medAbstractDataImage.h> #define EXEC_QUERY(q) execQuery(q, __FILE__ , __LINE__ ) namespace { inline bool execQuery ( QSqlQuery & query, const char *file, int line ) { if ( ! query.exec() ) { qDebug() << file << "(" << line << ") :" << DTK_COLOR_FG_RED << query.lastError() << DTK_NO_COLOR; return false; } return true; } } class medDatabaseRemoverPrivate { public: medDataIndex index; QSqlDatabase * db; static const QString T_PATIENT; static const QString T_STUDY; static const QString T_SERIES; static const QString T_IMAGE; bool isCancelled; }; const QString medDatabaseRemoverPrivate::T_PATIENT = "patient"; const QString medDatabaseRemoverPrivate::T_STUDY = "study"; const QString medDatabaseRemoverPrivate::T_SERIES = "series"; const QString medDatabaseRemoverPrivate::T_IMAGE = "image"; medDatabaseRemover::medDatabaseRemover ( const medDataIndex &index_ ) : medJobItem(), d ( new medDatabaseRemoverPrivate ) { d->index = index_; d->db = medDatabaseController::instance()->database(); d->isCancelled = false; } medDatabaseRemover::~medDatabaseRemover ( void ) { delete d; d = NULL; } void medDatabaseRemover::run ( void ) { QSqlDatabase & db ( *d->db ); QSqlQuery ptQuery ( db ); const medDataIndex index = d->index; if ( index.isValidForPatient() ) { ptQuery.prepare ( "SELECT id FROM " + d->T_PATIENT + " WHERE id = :id" ); ptQuery.bindValue ( ":id", index.patientId() ); } else { ptQuery.prepare ( "SELECT id FROM " + d->T_PATIENT ); } EXEC_QUERY ( ptQuery ); while ( ptQuery.next() ) { if ( d->isCancelled ) break; int patientDbId = ptQuery.value ( 0 ).toInt(); QSqlQuery stQuery ( db ); if ( index.isValidForStudy() ) { stQuery.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE id = :id AND patient = :patient" ); stQuery.bindValue ( ":id", index.studyId() ); } else { stQuery.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE patient = :patient" ); } stQuery.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( stQuery ); while ( stQuery.next() ) { if ( d->isCancelled ) break; int studyDbId = stQuery.value ( 0 ).toInt(); QSqlQuery seQuery ( db ); if ( index.isValidForSeries() ) { seQuery.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE id = :id AND study = :study" ); seQuery.bindValue ( ":id", index.seriesId() ); } else { seQuery.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE study = :study" ); } seQuery.bindValue ( ":study", studyDbId ); EXEC_QUERY ( seQuery ); while ( seQuery.next() ) { if ( d->isCancelled ) break; int seriesDbId = seQuery.value ( 0 ).toInt(); QSqlQuery imQuery ( db ); if ( index.isValidForImage() ) { imQuery.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE id = :id AND series = :seriesId" ); imQuery.bindValue ( ":id", index.imageId() ); } else { imQuery.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE series = :series" ); } imQuery.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( imQuery ); imQuery.last(); double nbImage = imQuery.at(); imQuery.first(); do { int imageId = imQuery.value ( 0 ).toInt(); this->removeImage ( patientDbId, studyDbId, seriesDbId, imageId ); emit progressed ( imQuery.at() / nbImage * 100 ); } while ( imQuery.next() ); if ( this->isSeriesEmpty ( seriesDbId ) ) this->removeSeries ( patientDbId, studyDbId, seriesDbId ); } // seQuery.next if ( this->isStudyEmpty ( studyDbId ) ) this->removeStudy ( patientDbId, studyDbId ); } // stQuery.next if ( this->isPatientEmpty ( patientDbId ) ) this->removePatient ( patientDbId ); } // ptQuery.next emit removed ( index ); emit progress ( this, 100 ); emit progressed ( 100 ); if ( d->isCancelled ) emit failure ( this ); else emit success ( this ); return; } void medDatabaseRemover::removeImage ( int patientDbId, int studyDbId, int seriesDbId, int imageId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail FROM " + d->T_IMAGE + " WHERE id = :imageId " ); query.bindValue ( ":id", imageId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); } removeTableRow ( d->T_IMAGE, imageId ); } bool medDatabaseRemover::isSeriesEmpty ( int seriesDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_IMAGE + " WHERE series = :series " ); query.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removeSeries ( int patientDbId, int studyDbId, int seriesDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail, path, name FROM " + d->T_SERIES + " WHERE id = :series " ); query.bindValue ( ":series", seriesDbId ); EXEC_QUERY ( query ); QString thumbnail; if ( query.next() ) { thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); QString path = query.value ( 1 ).toString(); // if path is empty then it was an indexed series if ( !path.isNull() && !path.isEmpty() ) this->removeDataFile ( medDataIndex::makeSeriesIndex ( d->index.dataSourceId(), patientDbId, studyDbId, seriesDbId ) , path ); } removeTableRow ( d->T_SERIES, seriesDbId ); // we want to remove the directory if empty QFileInfo seriesFi ( medStorage::dataLocation() + thumbnail ); if ( seriesFi.dir().exists() ) seriesFi.dir().rmdir ( seriesFi.absolutePath() ); // only removes if empty } bool medDatabaseRemover::isStudyEmpty ( int studyDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_SERIES + " WHERE study = :study " ); query.bindValue ( ":study", studyDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removeStudy ( int patientDbId, int studyDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT thumbnail, name, uid FROM " + d->T_STUDY + " WHERE id = :id " ); query.bindValue ( ":id", studyDbId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); } removeTableRow ( d->T_STUDY, studyDbId ); } bool medDatabaseRemover::isPatientEmpty ( int patientDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "SELECT id FROM " + d->T_STUDY + " WHERE patient = :patient " ); query.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( query ); return !query.next(); } void medDatabaseRemover::removePatient ( int patientDbId ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); QString patientName; QString patientBirthdate; QString patientId; query.prepare ( "SELECT thumbnail, patientId FROM " + d->T_PATIENT + " WHERE id = :patient " ); query.bindValue ( ":patient", patientDbId ); EXEC_QUERY ( query ); if ( query.next() ) { QString thumbnail = query.value ( 0 ).toString(); this->removeFile ( thumbnail ); patientId = query.value ( 1 ).toString(); } removeTableRow ( d->T_PATIENT, patientDbId ); medDatabaseControllerImpl * dbi = medDatabaseController::instance(); QDir patientDir ( medStorage::dataLocation() + "/" + dbi->stringForPath ( patientId ) ); if ( patientDir.exists() ) patientDir.rmdir ( patientDir.path() ); // only removes if empty } void medDatabaseRemover::removeTableRow ( const QString &table, int id ) { QSqlDatabase & db ( *d->db ); QSqlQuery query ( db ); query.prepare ( "DELETE FROM " + table + " WHERE id = :id" ); query.bindValue ( ":id", id ); EXEC_QUERY ( query ); } void medDatabaseRemover::removeFile ( const QString & filename ) { QFile file ( medStorage::dataLocation() + filename ); file.remove(); } void medDatabaseRemover::onCancel ( QObject* ) { d->isCancelled = true; } void medDatabaseRemover::removeDataFile ( const medDataIndex &index, const QString & filename ) { QFileInfo fi ( filename ); const QString suffix = fi.suffix(); const QString mhd ( "mhd" ); const QString mha ( "mha" ); if ( suffix == mhd ) { QString mhaFile ( filename ); mhaFile.chop ( mhd.length() ); mhaFile += mha; this->removeFile ( mhaFile ); } else if ( suffix == mha ) { QString mhdFile ( filename ); mhdFile.chop ( mha.length() ); mhdFile += mhd; this->removeFile ( mhdFile ); } this->removeFile ( filename ); } <|endoftext|>
<commit_before>/* User Server code for CMPT 276 Group Assignment, Spring 2016. This server manages a user’s social networking session. This server supports sign on/off, add friend, unfriend, update status, get user's friend list. This server handles disallowed method malformed request. As defined in ServerUrls.h, the URI for this server is http://localhost:34572. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <string> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "../include/ClientUtils.h" #include "../include/ServerUrls.h" #include "../include/ServerUtils.h" #include "../include/TableCache.h" #include "../include/azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using std::get; using web::http::client::http_client; using web::http::http_headers; using web::http::http_request; using web::http::http_response; using web::http::method; using web::http::methods; using web::http::status_code; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; const string get_update_data_op {"GetUpdateData"}; const string read_entity_auth_op {"ReadEntityAuth"}; const string update_entity_auth_op {"UpdateEntityAuth"}; const string auth_table_partition {"Userid"}; const string data_table {"DataTable"}; const string sign_on {"SignOn"}; //POST const string sign_off {"SignOff"}; //POST const string add_friend {"AddFriend"}; // PUT const string unfriend {"UnFriend"}; //PUT const string update_status {"UpdateStatus"}; //PUT const string get_friend_list {"ReadFriendList"}; //GET // Cache of active sessions std::unordered_map< string, std::tuple<string/*token*/, string/*partition*/, string/*row*/> > sessions; /* Return true if an HTTP request has a JSON body This routine can be called multiple times on the same message. */ bool has_json_body (http_request message) { return message.headers()["Content-type"] == "application/json"; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. get_json_body and get_json_bourne are valid and identical function calls. If the message has no JSON body, return an empty map. THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE (see http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7 for source of this limit). Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } unordered_map<string,string> get_json_bourne(http_request message) { return get_json_body(message); } void handle_post (http_request message){ string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Operation name and user ID if(paths.size() < 2) { message.reply(status_codes::BadRequest); return; } else if(paths[0] != sign_on && paths[0] != sign_off) { message.reply(status_codes::BadRequest); } const string operation = paths[0]; const string userid = paths[1]; if(operation == sign_on) { if(!has_json_body(message)) { message.reply(status_codes::BadRequest); return; } unordered_map<string, string> json_body {get_json_bourne(message)}; if(json_body.size() != 1) { message.reply(status_codes::BadRequest); return; } unordered_map<string, string>::const_iterator json_body_password_iterator {json_body.find("Password")}; // No 'Password' property if(json_body_password_iterator == json_body.end()) { message.reply(status_codes::BadRequest); return; } vector<pair<string, value>> json_pw; json_pw.push_back(make_pair( json_body_password_iterator->first, value::string(json_body_password_iterator->second) )); pair<status_code, value> result; result = do_request( methods::GET, string(server_urls::auth_server) + "/" + get_update_data_op + "/" + userid, value::object(json_pw) ); if(result.first != status_codes::OK) { message.reply(result.first); return; } else if(result.second.size() != 3) { message.reply(status_codes::InternalError); return; } const string token = get_json_object_prop( result.second, "token" ); const string data_partition = get_json_object_prop( result.second, "DataPartition" ); const string data_row = get_json_object_prop( result.second, "DataRow" ); if(token.empty() || data_partition.empty() || data_row.empty() ) { message.reply(status_codes::InternalError); return; } std::tuple<string, string, string> tuple_insert( token, data_partition, data_row); std::pair<string, std::tuple<string, string, string>> pair_insert( userid, tuple_insert ); sessions.insert(pair_insert); message.reply(status_codes::OK); return; } else if(operation == sign_off) { auto session = sessions.find(userid); if(session == sessions.end()) { message.reply(status_codes::NotFound); return; } sessions.erase(session); message.reply(status_codes::OK); return; } else { message.reply(status_codes::InternalError); return; } } void handle_put (http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); pair<status_code, value> result; string user_id {paths[1]}; string user_token {get<0>(sessions[user_id])}; string user_partition {get<1>(sessions[user_id])}; string user_row {get<2>(sessions[user_id])}; if(true/*basic criteria*/){} else if (paths[0] == add_friend) { // Get current friends list result = do_request( methods::GET, string(server_urls::basic_server) + "/" + read_entity_auth_op + "/" + data_table + "/" + user_token + "/" + user_partition + "/" + user_row ); //Check status code //Parse JSON body unordered_map<string,string> json_body = unpack_json_object(result.second); friends_list_t user_friends = parse_friends_list(json_body["Friends"]); // Add new friend to list user_friends.push_back(make_pair(paths[2],paths[3])); string user_friends_string = friends_list_to_string(user_friends); result.second = build_json_value("Friends", user_friends_string); // Put new friends list do_request( methods::PUT, string(server_urls::basic_server) + "/" + update_entity_auth_op + "/" + string(paths[2]) + "/" + string(paths[3]), result.second ); return; } else if (paths[0] == unfriend) {} else if (paths[0] == update_status) {} else { // malformed request vector<value> vec; message.reply(status_codes::BadRequest, value::array(vec)); return; } } void handle_get (http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); if(true/*basic criteria*/){} else if (paths[0] == get_friend_list) {} else { // malformed request vector<value> vec; message.reply(status_codes::BadRequest, value::array(vec)); return; } } int main (int argc, char const * argv[]) { cout << "Opening listener" << endl; http_listener listener {server_urls::user_server}; listener.support(methods::GET, &handle_get); // Get user's friend list listener.support(methods::POST, &handle_post); // SignOn, SignOff listener.support(methods::PUT, &handle_put); // Add friend, Unfriend, Update Status /*TO DO: Disallowed method*/ listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <commit_msg>add response code for correct function<commit_after>/* User Server code for CMPT 276 Group Assignment, Spring 2016. This server manages a user’s social networking session. This server supports sign on/off, add friend, unfriend, update status, get user's friend list. This server handles disallowed method malformed request. As defined in ServerUrls.h, the URI for this server is http://localhost:34572. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <string> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "../include/ClientUtils.h" #include "../include/ServerUrls.h" #include "../include/ServerUtils.h" #include "../include/TableCache.h" #include "../include/azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using std::get; using web::http::client::http_client; using web::http::http_headers; using web::http::http_request; using web::http::http_response; using web::http::method; using web::http::methods; using web::http::status_code; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; const string get_update_data_op {"GetUpdateData"}; const string read_entity_auth_op {"ReadEntityAuth"}; const string update_entity_auth_op {"UpdateEntityAuth"}; const string auth_table_partition {"Userid"}; const string data_table {"DataTable"}; const string sign_on {"SignOn"}; //POST const string sign_off {"SignOff"}; //POST const string add_friend {"AddFriend"}; // PUT const string unfriend {"UnFriend"}; //PUT const string update_status {"UpdateStatus"}; //PUT const string get_friend_list {"ReadFriendList"}; //GET // Cache of active sessions std::unordered_map< string, std::tuple<string/*token*/, string/*partition*/, string/*row*/> > sessions; /* Return true if an HTTP request has a JSON body This routine can be called multiple times on the same message. */ bool has_json_body (http_request message) { return message.headers()["Content-type"] == "application/json"; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. get_json_body and get_json_bourne are valid and identical function calls. If the message has no JSON body, return an empty map. THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE (see http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7 for source of this limit). Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } unordered_map<string,string> get_json_bourne(http_request message) { return get_json_body(message); } void handle_post (http_request message){ string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Operation name and user ID if(paths.size() < 2) { message.reply(status_codes::BadRequest); return; } else if(paths[0] != sign_on && paths[0] != sign_off) { message.reply(status_codes::BadRequest); } const string operation = paths[0]; const string userid = paths[1]; if(operation == sign_on) { if(!has_json_body(message)) { message.reply(status_codes::BadRequest); return; } unordered_map<string, string> json_body {get_json_bourne(message)}; if(json_body.size() != 1) { message.reply(status_codes::BadRequest); return; } unordered_map<string, string>::const_iterator json_body_password_iterator {json_body.find("Password")}; // No 'Password' property if(json_body_password_iterator == json_body.end()) { message.reply(status_codes::BadRequest); return; } vector<pair<string, value>> json_pw; json_pw.push_back(make_pair( json_body_password_iterator->first, value::string(json_body_password_iterator->second) )); pair<status_code, value> result; result = do_request( methods::GET, string(server_urls::auth_server) + "/" + get_update_data_op + "/" + userid, value::object(json_pw) ); if(result.first != status_codes::OK) { message.reply(result.first); return; } else if(result.second.size() != 3) { message.reply(status_codes::InternalError); return; } const string token = get_json_object_prop( result.second, "token" ); const string data_partition = get_json_object_prop( result.second, "DataPartition" ); const string data_row = get_json_object_prop( result.second, "DataRow" ); if(token.empty() || data_partition.empty() || data_row.empty() ) { message.reply(status_codes::InternalError); return; } std::tuple<string, string, string> tuple_insert( token, data_partition, data_row); std::pair<string, std::tuple<string, string, string>> pair_insert( userid, tuple_insert ); sessions.insert(pair_insert); message.reply(status_codes::OK); return; } else if(operation == sign_off) { auto session = sessions.find(userid); if(session == sessions.end()) { message.reply(status_codes::NotFound); return; } sessions.erase(session); message.reply(status_codes::OK); return; } else { message.reply(status_codes::InternalError); return; } } void handle_put (http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); pair<status_code, value> result; string user_id {paths[1]}; string user_token {get<0>(sessions[user_id])}; string user_partition {get<1>(sessions[user_id])}; string user_row {get<2>(sessions[user_id])}; if(true/*basic criteria*/){} else if (paths[0] == add_friend) { // Get current friends list result = do_request( methods::GET, string(server_urls::basic_server) + "/" + read_entity_auth_op + "/" + data_table + "/" + user_token + "/" + user_partition + "/" + user_row ); //Check status code //Parse JSON body unordered_map<string,string> json_body = unpack_json_object(result.second); friends_list_t user_friends = parse_friends_list(json_body["Friends"]); // Add new friend to list user_friends.push_back(make_pair(paths[2],paths[3])); string user_friends_string = friends_list_to_string(user_friends); result.second = build_json_value("Friends", user_friends_string); // Put new friends list do_request( methods::PUT, string(server_urls::basic_server) + "/" + update_entity_auth_op + "/" + string(paths[2]) + "/" + string(paths[3]), result.second ); message.reply(status::codes::OK); return; } else if (paths[0] == unfriend) {} else if (paths[0] == update_status) {} else { // malformed request vector<value> vec; message.reply(status_codes::BadRequest, value::array(vec)); return; } } void handle_get (http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); if(true/*basic criteria*/){} else if (paths[0] == get_friend_list) {} else { // malformed request vector<value> vec; message.reply(status_codes::BadRequest, value::array(vec)); return; } } int main (int argc, char const * argv[]) { cout << "Opening listener" << endl; http_listener listener {server_urls::user_server}; listener.support(methods::GET, &handle_get); // Get user's friend list listener.support(methods::POST, &handle_post); // SignOn, SignOff listener.support(methods::PUT, &handle_put); // Add friend, Unfriend, Update Status /*TO DO: Disallowed method*/ listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <|endoftext|>
<commit_before>// // Solver.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Solver.h" Solver::Solver(std::string a){ this->localExpression = a; expressions = *new vector<string>(); tokenStack = *new stack<string>(); output = ""; } Solver::~Solver(){ } std::string Solver::solve(){ string temp = ""; int count = 0; for(int i = 0; i < localExpression.size(); i ++){ //creates an array of expressions and operations if(localExpression.at(i) == ' '){ temp = ""; for (int j = count; j < i; j++) { temp.push_back(localExpression.at(j)); } expressions.push_back(temp); count = i+1; }else if(i == localExpression.size()-1){ temp = ""; for (int j = count; j <= i; j++) { temp.push_back(localExpression.at(j)); } expressions.push_back(temp); count = i+1; } } shuntingYard(); expressions.clear(); count = 0; for(int i = 0; i < output.size(); i ++){ //creates an array of expressions and operations if(output.at(i) == ' '){ temp = ""; for (int j = count; j < i; j++) { temp.push_back(output.at(j)); } expressions.push_back(temp); count = i+1; }else if(i == output.size()-1){ temp = ""; for (int j = count; j <= i; j++) { temp.push_back(output.at(j)); } expressions.push_back(temp); count = i+1; } } // cout << output << endl; return "Result:" + evaluateString(); //+ evaluateString(); } void Solver::shuntingYard(){ for(int i = 0; i < expressions.size(); i++){ string token = expressions.at(i); if(!isAnOperator(token) && (token != "(" && token != ")")){ if(i == 0) output += expressions.at(i); else output += " " + expressions.at(i); } if(isAnOperator(token)){ while(!tokenStack.empty() && isAnOperator(tokenStack.top()) ){ if((isLeftAssociative(token) && getOperatorPrecedence(token) <= getOperatorPrecedence(tokenStack.top())) || (!isLeftAssociative(token) && getOperatorPrecedence(token) < getOperatorPrecedence(tokenStack.top()))){ output += " " + tokenStack.top(); tokenStack.pop(); } break; } tokenStack.push(token); } if(token == "("){ tokenStack.push(token); } if(token == ")"){ while (!tokenStack.empty() && tokenStack.top() != "(") { output += " " + tokenStack.top(); tokenStack.pop(); } tokenStack.pop(); } } while (!tokenStack.empty()) { output += " " + tokenStack.top(); tokenStack.pop(); } if(output.at(0) == ' '){ output.erase(0,1); } } bool Solver::isAnOperator(string tkn){ if(tkn == "+" || tkn == "-" || tkn == "/" || tkn == "*" || tkn == "^") return true; else return false; } bool Solver::isLeftAssociative(string tkn){ if(tkn == "+" || tkn == "-" || tkn == "/" || tkn == "*") return true; else return false; } int Solver::getOperatorPrecedence(string tkn){ if(tkn == "^") return 4; else if(tkn == "*" || tkn == "/") return 3; else return 2; } string Solver::evaluateString(){ string out = *new string(""); string result = *new string(""); stack<string> stk = *new stack<string>(); if (expressions.size() == 1) { out = this->bindToExpressionType(expressions.at(0))->toString(); return out; } for(int i = 0; i < expressions.size(); i++){ string token = expressions.at(i); if(!isAnOperator(token)){ stk.push(token); } else{ Expression* e2; e2 = bindToExpressionType(stk.top()); e2->exp = stk.top(); stk.pop(); Expression *e1; e1 = bindToExpressionType(stk.top()); e1->exp = stk.top(); result = e1->exp; stk.pop(); //check function call and call appropriate method if(token == "+"){ if(e1->canAdd(e2)){ Expression *result = e1->add(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "+" + e2->exp); out += e1->exp + " + " + e2->exp; } }else if(token == "-"){ if(e1->canSubtract(e2)){ Expression *result = e1->subtract(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "-" + e2->exp); out += e1->exp + " - " + e2->exp; } }else if(token == "*"){ if(e1->canMultiply(e2)){ Expression *result = e1->multiply(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "*" + e2->exp); out += e1->exp + " * " + e2->exp; } }else if(token == "/"){ if (e1->type == "integer" && e2->type == "integer") { Integer *a = (Integer *)e1; Integer *b = (Integer *)e2; if(b->getValue() == 0) throw runtime_error("Error: Cannot Divide By Zero"); if (a->getValue() % b->getValue() != 0) { e1 = new Rational(e1,e2); stk.push(e1->toString()); out += e1->toString(); }else if(e1->canDivide(e2)){ Expression *result = e1->divide(e2); stk.push(result->toString()); out = result->toString(); } } else if(e1->canDivide(e2)){ Expression *result = e1->divide(e2); if (result->type == "rational") { Rational * a = (Rational *)result; if (a->getNumerator() == 1 && a->getDenominator() == 1) { stk.push("1"); out = "1"; }else{ stk.push(result->toString()); out = result->toString(); } }else{ stk.push(result->toString()); out = result->toString(); } } }else if(token == "^"){ if (e2->type == "integer") { Rational *b = new Rational(e2, new Integer(1)); e2 = b; } Exponential *a = new Exponential(e1,(Rational *)e2); output += a->toString(); Rational *t = (Rational *)e2; if (t->getNumerator() == 1 && t->getDenominator() == 1) { stk.push(e1->toString()); out += e1->toString(); }else{ stk.push(e1->toString() + "^" + e2->toString()); out += e1->toString() + "^" + e2->toString(); } }else{ cout << "Error: Invalid Operator" << endl; } } } return out; } Expression* Solver::bindToExpressionType(string e){ Expression *a = new Integer(0); //so the compiler doesnt complain. Will be set to appropriate type later for(int i = 0; i < e.length(); i++){ if (e[i] == '/') { string before; string after; for(int j = 0; j < i; j++){ before.push_back(e[j]); } for(int k = i+1; k < e.length(); k++){ after.push_back(e[k]); } a = new Rational(atoi(before.c_str()), atoi(after.c_str())); break; }else if(e[i] == 'p' && e[i+1] == 'i'){ a = new Pi(); break; }else if(e[i] == 'e'){ // a = new Euler(); break; }else if(e[i] == 'l' && e[i+1] == 'o' && e[i+2] == 'g'){ string base; string operand; int j = i + 4; while (e[j] != ':') { base.push_back(e[j]); j++; } for (int k = j+1; k < e.length(); k++) { operand.push_back(e[k]); } Expression *b = this->bindToExpressionType(base); Expression *o = this->bindToExpressionType(operand); if (b->type == "integer" && o->type == "integer") { Integer *ba = (Integer *)b; Integer *op = (Integer *)o; Logarithm *b = new Logarithm(ba->getValue(), op->getValue()); Logarithm *c = (Logarithm *)b->simplify(); if (c->getBase() == b->getBase() && c->getOperand() == b->getOperand()) { } }else{ a = new Logarithm(b,a); } break; } else if(!isdigit(e[i])){ break; } else if(i == e.length()-1){ a = new Integer(atoi(e.c_str())); } } return a; } <commit_msg>fixed issue with negatives<commit_after>// // Solver.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Solver.h" Solver::Solver(std::string a){ this->localExpression = a; expressions = *new vector<string>(); tokenStack = *new stack<string>(); output = ""; } Solver::~Solver(){ } std::string Solver::solve(){ string temp = ""; int count = 0; for(int i = 0; i < localExpression.size(); i ++){ //creates an array of expressions and operations if(localExpression.at(i) == ' '){ temp = ""; for (int j = count; j < i; j++) { temp.push_back(localExpression.at(j)); } expressions.push_back(temp); count = i+1; }else if(i == localExpression.size()-1){ temp = ""; for (int j = count; j <= i; j++) { temp.push_back(localExpression.at(j)); } expressions.push_back(temp); count = i+1; } } shuntingYard(); expressions.clear(); count = 0; for(int i = 0; i < output.size(); i ++){ //creates an array of expressions and operations if(output.at(i) == ' '){ temp = ""; for (int j = count; j < i; j++) { temp.push_back(output.at(j)); } expressions.push_back(temp); count = i+1; }else if(i == output.size()-1){ temp = ""; for (int j = count; j <= i; j++) { temp.push_back(output.at(j)); } expressions.push_back(temp); count = i+1; } } // cout << output << endl; return "Result:" + evaluateString(); //+ evaluateString(); } void Solver::shuntingYard(){ for(int i = 0; i < expressions.size(); i++){ string token = expressions.at(i); if(!isAnOperator(token) && (token != "(" && token != ")")){ if(i == 0) output += expressions.at(i); else output += " " + expressions.at(i); } if(isAnOperator(token)){ while(!tokenStack.empty() && isAnOperator(tokenStack.top()) ){ if((isLeftAssociative(token) && getOperatorPrecedence(token) <= getOperatorPrecedence(tokenStack.top())) || (!isLeftAssociative(token) && getOperatorPrecedence(token) < getOperatorPrecedence(tokenStack.top()))){ output += " " + tokenStack.top(); tokenStack.pop(); } break; } tokenStack.push(token); } if(token == "("){ tokenStack.push(token); } if(token == ")"){ while (!tokenStack.empty() && tokenStack.top() != "(") { output += " " + tokenStack.top(); tokenStack.pop(); } tokenStack.pop(); } } while (!tokenStack.empty()) { output += " " + tokenStack.top(); tokenStack.pop(); } if(output.at(0) == ' '){ output.erase(0,1); } } bool Solver::isAnOperator(string tkn){ if(tkn == "+" || tkn == "-" || tkn == "/" || tkn == "*" || tkn == "^") return true; else return false; } bool Solver::isLeftAssociative(string tkn){ if(tkn == "+" || tkn == "-" || tkn == "/" || tkn == "*") return true; else return false; } int Solver::getOperatorPrecedence(string tkn){ if(tkn == "^") return 4; else if(tkn == "*" || tkn == "/") return 3; else return 2; } string Solver::evaluateString(){ string out = *new string(""); string result = *new string(""); stack<string> stk = *new stack<string>(); if (expressions.size() == 1) { out = this->bindToExpressionType(expressions.at(0))->toString(); return out; } for(int i = 0; i < expressions.size(); i++){ string token = expressions.at(i); if(!isAnOperator(token)){ stk.push(token); } else{ Expression* e2; e2 = bindToExpressionType(stk.top()); e2->exp = stk.top(); stk.pop(); Expression *e1; e1 = bindToExpressionType(stk.top()); e1->exp = stk.top(); result = e1->exp; stk.pop(); //check function call and call appropriate method if(token == "+"){ if(e1->canAdd(e2)){ Expression *result = e1->add(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "+" + e2->exp); out += e1->exp + " + " + e2->exp; } }else if(token == "-"){ if(e1->canSubtract(e2)){ Expression *result = e1->subtract(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "-" + e2->exp); out += e1->exp + " - " + e2->exp; } }else if(token == "*"){ if(e1->canMultiply(e2)){ Expression *result = e1->multiply(e2); stk.push(result->toString()); out = result->toString(); }else{ stk.push(e1->exp + "*" + e2->exp); out += e1->exp + " * " + e2->exp; } }else if(token == "/"){ if (e1->type == "integer" && e2->type == "integer") { Integer *a = (Integer *)e1; Integer *b = (Integer *)e2; if(b->getValue() == 0) throw runtime_error("Error: Cannot Divide By Zero"); if (a->getValue() % b->getValue() != 0) { e1 = new Rational(e1,e2); stk.push(e1->toString()); out += e1->toString(); }else if(e1->canDivide(e2)){ Expression *result = e1->divide(e2); stk.push(result->toString()); out = result->toString(); } } else if(e1->canDivide(e2)){ Expression *result = e1->divide(e2); if (result->type == "rational") { Rational * a = (Rational *)result; if (a->getNumerator() == 1 && a->getDenominator() == 1) { stk.push("1"); out = "1"; }else{ stk.push(result->toString()); out = result->toString(); } }else{ stk.push(result->toString()); out = result->toString(); } } }else if(token == "^"){ if (e2->type == "integer") { Rational *b = new Rational(e2, new Integer(1)); e2 = b; } Exponential *a = new Exponential(e1,(Rational *)e2); output += a->toString(); Rational *t = (Rational *)e2; if (t->getNumerator() == 1 && t->getDenominator() == 1) { stk.push(e1->toString()); out += e1->toString(); }else{ stk.push(e1->toString() + "^" + e2->toString()); out += e1->toString() + "^" + e2->toString(); } }else{ cout << "Error: Invalid Operator" << endl; } } } return out; } Expression* Solver::bindToExpressionType(string e){ Expression *a = new Integer(0); //so the compiler doesnt complain. Will be set to appropriate type later for(int i = 0; i < e.length(); i++){ if (e[i] == '/') { string before; string after; for(int j = 0; j < i; j++){ before.push_back(e[j]); } for(int k = i+1; k < e.length(); k++){ after.push_back(e[k]); } a = new Rational(atoi(before.c_str()), atoi(after.c_str())); break; }else if(e[i] == 'p' && e[i+1] == 'i'){ a = new Pi(); break; }else if(e[i] == 'e'){ // a = new Euler(); break; }else if(e[i] == 'l' && e[i+1] == 'o' && e[i+2] == 'g'){ string base; string operand; int j = i + 4; while (e[j] != ':') { base.push_back(e[j]); j++; } for (int k = j+1; k < e.length(); k++) { operand.push_back(e[k]); } Expression *b = this->bindToExpressionType(base); Expression *o = this->bindToExpressionType(operand); if (b->type == "integer" && o->type == "integer") { Integer *ba = (Integer *)b; Integer *op = (Integer *)o; Logarithm *b = new Logarithm(ba->getValue(), op->getValue()); Logarithm *c = (Logarithm *)b->simplify(); if (c->getBase() == b->getBase() && c->getOperand() == b->getOperand()) { } }else{ a = new Logarithm(b,a); } break; } else if(!isdigit(e[i]) && e[i] != '-'){ cout << e[i] << endl; break; } else if(i == e.length()-1){ a = new Integer(atoi(e.c_str())); } } return a; } <|endoftext|>
<commit_before>#include "videosourcefactory.h" #include "iobserver.h" #include "iobservable.h" #include <thread> #include <chrono> #include <iostream> #include <cstring> #include <fstream> #include <vector> #include <ctime> gg::Device device; gg::ColourSpace colour; size_t test_duration; // seconds float frame_rate_to_check; std::string report_filename(""); using namespace std::chrono; typedef time_point<system_clock> timestamp; typedef std::vector< timestamp > timestamps; //! //! \brief This gg::IObserver implementor //! records a timestamp every time it is //! updated. //! //! It can then be used to check the frame //! rate of the gg::IObservable it was //! attached to. //! class FrameRateTimer : public gg::IObserver { protected: timestamps _timestamps; public: void update(gg::VideoFrame & frame) override { _timestamps.push_back(system_clock::now()); } //! //! \brief Get statistics based on currently //! available timestamp collection //! \param max_frame_rate fps //! \param min_frame_rate fps //! \param avg_frame_rate fps //! \param n_timestamps //! \return \c true if timestamps are available //! AND meaningful, such that the computations //! can be carried out, \c false otherwise //! bool statistics(float & max_frame_rate, float & min_frame_rate, float & avg_frame_rate, size_t & n_timestamps) { if (_timestamps.empty() or _timestamps.size() < 10) return false; n_timestamps = _timestamps.size(); // unit: sec float min_duration = std::numeric_limits<float>::max(), max_duration = std::numeric_limits<float>::min(), sum_durations = 0.0; for (size_t i = 0; i < _timestamps.size() - 1; i++) { float cur_duration = duration_ms(_timestamps[i], _timestamps[i + 1]); sum_durations += cur_duration; if (cur_duration < min_duration) min_duration = cur_duration; else if (cur_duration > max_duration) max_duration = cur_duration; } if (min_duration <= 0.0 or max_duration <= 0.0 or sum_durations <= 0.0) return false; max_frame_rate = 1000.0 / min_duration; min_frame_rate = 1000.0 / max_duration; avg_frame_rate = 1000.0 * (n_timestamps - 1) / sum_durations; return true; } //! //! \brief Output timestamp for each \c update() //! call as well as the time duration between //! each consecutive call pair, as well as the //! computed statistics to CSV file with \c //! filename //! \param filename nop if empty //! \sa statistics() //! \throw std::ios_base::failure in case the //! (non-empty) \c filename does not point to a //! valid file, writeable by user //! void report(std::string filename) { // Open file std::ofstream outfile; outfile.open(filename); if (not outfile.is_open()) throw std::ios_base::failure( filename.append(" could not be opened")); // CSV format std::string delimiter(", "); // Get statistics float max_fr, min_fr, avg_fr; size_t n_timestamps; if (statistics(max_fr, min_fr, avg_fr, n_timestamps)) { // Write header outfile << "Nr. of timestamps" << delimiter << "Max. frame rate (fps)" << delimiter << "Min. frame rate (fps)" << delimiter << "Avg. frame rate (fps)" << std::endl; // Write data outfile << n_timestamps << delimiter << max_fr << delimiter << min_fr << delimiter << avg_fr << std::endl; } else outfile << "Statistics could not be computed" << std::endl; // Write timestamps and inter-frame durations if (n_timestamps > 0) { char buffer [80]; typedef duration<int, std::ratio_multiply<hours::period, std::ratio<24> >::type> days; // Write header outfile << "Frame timestamp (date-time)" << delimiter << "Inter-frame duration (ms)" << std::endl; // Write data for (timestamp ts : _timestamps) { // Nicely format date-time for human-readability time_t tt = system_clock::to_time_t(ts); tm local_tm = *localtime(&tt); strftime (buffer, 80, "%Y/%m/%d %H:%M:%S", &local_tm); // Append millisecond resolution to human-readable timestamp system_clock::duration tp = ts.time_since_epoch(); days d = duration_cast<days>(tp); tp -= d; hours h = duration_cast<hours>(tp); tp -= h; minutes m = duration_cast<minutes>(tp); tp -= m; seconds s = duration_cast<seconds>(tp); tp -= s; milliseconds ms = duration_cast<milliseconds>(tp); tp -= ms; sprintf(buffer, "%s.%03lu", buffer, ms.count()); // Current inter-frame duration float cur_duration = duration_ms(_timestamps[0], ts); // Debugging output std::cout << d.count() << "d " << h.count() << ':' << m.count() << ':' << s.count() << '.' << ms.count(); std::cout << " " << tp.count() << "[" << system_clock::duration::period::num << '/' << system_clock::duration::period::den << "]"; std::cout << " " << cur_duration << "ms [inter-frame]"; std::cout << std::endl; // Actual output to CSV file outfile << buffer << delimiter << cur_duration << std::endl; } } else outfile << "No timestamps" << std::endl; // Close file outfile.close(); } protected: //! //! \brief Get duration between two timestamps in milliseconds //! \param t0 //! \param t1 //! \return //! float duration_ms(const timestamp & t0, const timestamp & t1) { duration<float> difference = duration_cast<seconds>(t1 - t0); return difference.count(); } }; bool parse_args(int argc, char * argv[]) { if (argc < 5) return false; if (std::strcmp(argv[1], "DVI") == 0) device = gg::DVI2PCIeDuo_DVI; else if (std::strcmp(argv[1], "SDI") == 0) device = gg::DVI2PCIeDuo_SDI; else return false; if (std::strcmp(argv[2], "BGRA") == 0) colour = gg::BGRA; else if (std::strcmp(argv[2], "I420") == 0) colour = gg::I420; else return false; int test_duration_ = std::atoi(argv[3]); if (test_duration_ <= 0) return false; else test_duration = test_duration_; double frame_rate_to_check_ = std::atof(argv[4]); if (frame_rate_to_check_ <= 0.0) return false; else frame_rate_to_check = frame_rate_to_check_; if (argc >= 6) report_filename = std::string(argv[5]); return true; } void synopsis(int argc, char * argv[]) { printf("%s DVI | SDI BGRA | I420 <test_duration>" " <frame_rate_to_check> [ <report_filename> ]" "\n", argv[0]); } int main(int argc, char * argv[]) { if (not parse_args(argc, argv)) { synopsis(argc, argv); return EXIT_FAILURE; } // gg::VideoSourceFactory & source_fac = gg::VideoSourceFactory::get_instance(); // IVideoSource * epiphan = source_fac.get_device(device, colour); FrameRateTimer timer; // epiphan->attach(timer); // std::this_thread::sleep_for(std::chrono::seconds(duration)); // epiphan->detach(timer); float max_fr, min_fr, avg_fr; size_t n_timestamps; if (not timer.statistics(max_fr, min_fr, avg_fr, n_timestamps)) return EXIT_FAILURE; timer.report(report_filename); return ( avg_fr >= frame_rate_to_check and min_fr >= frame_rate_to_check ) ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>Issue #117: commented Epiphan code back into test_frame_rate<commit_after>#include "videosourcefactory.h" #include "iobserver.h" #include "iobservable.h" #include <thread> #include <chrono> #include <iostream> #include <cstring> #include <fstream> #include <vector> #include <ctime> gg::Device device; gg::ColourSpace colour; size_t test_duration; // seconds float frame_rate_to_check; std::string report_filename(""); using namespace std::chrono; typedef time_point<system_clock> timestamp; typedef std::vector< timestamp > timestamps; //! //! \brief This gg::IObserver implementor //! records a timestamp every time it is //! updated. //! //! It can then be used to check the frame //! rate of the gg::IObservable it was //! attached to. //! class FrameRateTimer : public gg::IObserver { protected: timestamps _timestamps; public: void update(gg::VideoFrame & frame) override { _timestamps.push_back(system_clock::now()); } //! //! \brief Get statistics based on currently //! available timestamp collection //! \param max_frame_rate fps //! \param min_frame_rate fps //! \param avg_frame_rate fps //! \param n_timestamps //! \return \c true if timestamps are available //! AND meaningful, such that the computations //! can be carried out, \c false otherwise //! bool statistics(float & max_frame_rate, float & min_frame_rate, float & avg_frame_rate, size_t & n_timestamps) { if (_timestamps.empty() or _timestamps.size() < 10) return false; n_timestamps = _timestamps.size(); // unit: sec float min_duration = std::numeric_limits<float>::max(), max_duration = std::numeric_limits<float>::min(), sum_durations = 0.0; for (size_t i = 0; i < _timestamps.size() - 1; i++) { float cur_duration = duration_ms(_timestamps[i], _timestamps[i + 1]); sum_durations += cur_duration; if (cur_duration < min_duration) min_duration = cur_duration; else if (cur_duration > max_duration) max_duration = cur_duration; } if (min_duration <= 0.0 or max_duration <= 0.0 or sum_durations <= 0.0) return false; max_frame_rate = 1000.0 / min_duration; min_frame_rate = 1000.0 / max_duration; avg_frame_rate = 1000.0 * (n_timestamps - 1) / sum_durations; return true; } //! //! \brief Output timestamp for each \c update() //! call as well as the time duration between //! each consecutive call pair, as well as the //! computed statistics to CSV file with \c //! filename //! \param filename nop if empty //! \sa statistics() //! \throw std::ios_base::failure in case the //! (non-empty) \c filename does not point to a //! valid file, writeable by user //! void report(std::string filename) { // Open file std::ofstream outfile; outfile.open(filename); if (not outfile.is_open()) throw std::ios_base::failure( filename.append(" could not be opened")); // CSV format std::string delimiter(", "); // Get statistics float max_fr, min_fr, avg_fr; size_t n_timestamps; if (statistics(max_fr, min_fr, avg_fr, n_timestamps)) { // Write header outfile << "Nr. of timestamps" << delimiter << "Max. frame rate (fps)" << delimiter << "Min. frame rate (fps)" << delimiter << "Avg. frame rate (fps)" << std::endl; // Write data outfile << n_timestamps << delimiter << max_fr << delimiter << min_fr << delimiter << avg_fr << std::endl; } else outfile << "Statistics could not be computed" << std::endl; // Write timestamps and inter-frame durations if (n_timestamps > 0) { char buffer [80]; typedef duration<int, std::ratio_multiply<hours::period, std::ratio<24> >::type> days; // Write header outfile << "Frame timestamp (date-time)" << delimiter << "Inter-frame duration (ms)" << std::endl; // Write data for (timestamp ts : _timestamps) { // Nicely format date-time for human-readability time_t tt = system_clock::to_time_t(ts); tm local_tm = *localtime(&tt); strftime (buffer, 80, "%Y/%m/%d %H:%M:%S", &local_tm); // Append millisecond resolution to human-readable timestamp system_clock::duration tp = ts.time_since_epoch(); days d = duration_cast<days>(tp); tp -= d; hours h = duration_cast<hours>(tp); tp -= h; minutes m = duration_cast<minutes>(tp); tp -= m; seconds s = duration_cast<seconds>(tp); tp -= s; milliseconds ms = duration_cast<milliseconds>(tp); tp -= ms; sprintf(buffer, "%s.%03lu", buffer, ms.count()); // Current inter-frame duration float cur_duration = duration_ms(_timestamps[0], ts); // Debugging output std::cout << d.count() << "d " << h.count() << ':' << m.count() << ':' << s.count() << '.' << ms.count(); std::cout << " " << tp.count() << "[" << system_clock::duration::period::num << '/' << system_clock::duration::period::den << "]"; std::cout << " " << cur_duration << "ms [inter-frame]"; std::cout << std::endl; // Actual output to CSV file outfile << buffer << delimiter << cur_duration << std::endl; } } else outfile << "No timestamps" << std::endl; // Close file outfile.close(); } protected: //! //! \brief Get duration between two timestamps in milliseconds //! \param t0 //! \param t1 //! \return //! float duration_ms(const timestamp & t0, const timestamp & t1) { duration<float> difference = duration_cast<seconds>(t1 - t0); return difference.count(); } }; bool parse_args(int argc, char * argv[]) { if (argc < 5) return false; if (std::strcmp(argv[1], "DVI") == 0) device = gg::DVI2PCIeDuo_DVI; else if (std::strcmp(argv[1], "SDI") == 0) device = gg::DVI2PCIeDuo_SDI; else return false; if (std::strcmp(argv[2], "BGRA") == 0) colour = gg::BGRA; else if (std::strcmp(argv[2], "I420") == 0) colour = gg::I420; else return false; int test_duration_ = std::atoi(argv[3]); if (test_duration_ <= 0) return false; else test_duration = test_duration_; double frame_rate_to_check_ = std::atof(argv[4]); if (frame_rate_to_check_ <= 0.0) return false; else frame_rate_to_check = frame_rate_to_check_; if (argc >= 6) report_filename = std::string(argv[5]); return true; } void synopsis(int argc, char * argv[]) { printf("%s DVI | SDI BGRA | I420 <test_duration>" " <frame_rate_to_check> [ <report_filename> ]" "\n", argv[0]); } int main(int argc, char * argv[]) { if (not parse_args(argc, argv)) { synopsis(argc, argv); return EXIT_FAILURE; } gg::VideoSourceFactory & source_fac = gg::VideoSourceFactory::get_instance(); IVideoSource * epiphan = source_fac.get_device(device, colour); FrameRateTimer timer; epiphan->attach(timer); std::this_thread::sleep_for(std::chrono::seconds(test_duration)); epiphan->detach(timer); float max_fr, min_fr, avg_fr; size_t n_timestamps; if (not timer.statistics(max_fr, min_fr, avg_fr, n_timestamps)) return EXIT_FAILURE; timer.report(report_filename); return ( avg_fr >= frame_rate_to_check and min_fr >= frame_rate_to_check ) ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkUniformGridAMRAlgorithm.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkUniformGridAMRAlgorithm.h" #include "vtkObjectFactory.h" #include "vtkUniformGridAMR.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCompositeDataPipeline.h" #include "vtkDemandDrivenPipeline.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkExecutive.h" vtkStandardNewMacro(vtkUniformGridAMRAlgorithm); //------------------------------------------------------------------------------ vtkUniformGridAMRAlgorithm::vtkUniformGridAMRAlgorithm() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //------------------------------------------------------------------------------ vtkUniformGridAMRAlgorithm::~vtkUniformGridAMRAlgorithm() { } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf( os, indent ); } //------------------------------------------------------------------------------ vtkUniformGridAMR* vtkUniformGridAMRAlgorithm::GetOutput() { return this->GetOutput(0); } //------------------------------------------------------------------------------ vtkUniformGridAMR* vtkUniformGridAMRAlgorithm::GetOutput(int port) { vtkDataObject* output = vtkCompositeDataPipeline::SafeDownCast( this->GetExecutive())->GetCompositeOutputData(port); return( vtkUniformGridAMR::SafeDownCast(output) ); } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::SetInput( vtkDataObject* input ) { this->SetInput(0, input); } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::SetInput(int index, vtkDataObject* input) { if( input != NULL ) { this->SetInputConnection(index,input->GetProducerPort()); } else { // Setting a NULL input removes the connection this->SetInputConnection(index,0); } } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::ProcessRequest( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) { // create the output if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT())) { return this->RequestDataObject(request, inputVector, outputVector); } // generate the data if(request->Has(vtkCompositeDataPipeline::REQUEST_DATA())) { int retVal = this->RequestData(request,inputVector,outputVector); return( retVal ); } // execute information if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) { if(request->Has(vtkStreamingDemandDrivenPipeline::FROM_OUTPUT_PORT())) { int outputPort = request->Get(vtkStreamingDemandDrivenPipeline::FROM_OUTPUT_PORT()); vtkInformation* info = outputVector->GetInformationObject(outputPort); if( info != NULL ) { info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); } } else { for (int outIdx=0; outIdx < this->GetNumberOfOutputPorts(); outIdx++) { vtkInformation* info = outputVector->GetInformationObject(outIdx); if(info != NULL) { info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); } } } return this->RequestInformation(request, inputVector, outputVector); } // set update extent if( request->Has( vtkCompositeDataPipeline::REQUEST_UPDATE_EXTENT())) { return( this->RequestUpdateExtent(request,inputVector,outputVector) ); } return( this->Superclass::ProcessRequest(request,inputVector,outputVector) ); } //------------------------------------------------------------------------------ vtkExecutive* vtkUniformGridAMRAlgorithm::CreateDefaultExecutive() { return vtkCompositeDataPipeline::New(); } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::FillOutputPortInformation( int port, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUniformGridAMR"); return 1; } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::FillInputPortInformation( int port, vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkUniformGridAMR"); return 1; } //------------------------------------------------------------------------------ vtkDataObject* vtkUniformGridAMRAlgorithm::GetInput(int port) { if( this->GetNumberOfInputConnections(port) < 1 ) { return NULL; } return this->GetExecutive()->GetInputData(port,0); } <commit_msg>STYLE: Whitespace changes<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkUniformGridAMRAlgorithm.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkUniformGridAMRAlgorithm.h" #include "vtkObjectFactory.h" #include "vtkUniformGridAMR.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCompositeDataPipeline.h" #include "vtkDemandDrivenPipeline.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkExecutive.h" vtkStandardNewMacro(vtkUniformGridAMRAlgorithm); //------------------------------------------------------------------------------ vtkUniformGridAMRAlgorithm::vtkUniformGridAMRAlgorithm() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //------------------------------------------------------------------------------ vtkUniformGridAMRAlgorithm::~vtkUniformGridAMRAlgorithm() { } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf( os, indent ); } //------------------------------------------------------------------------------ vtkUniformGridAMR* vtkUniformGridAMRAlgorithm::GetOutput() { return this->GetOutput(0); } //------------------------------------------------------------------------------ vtkUniformGridAMR* vtkUniformGridAMRAlgorithm::GetOutput(int port) { vtkDataObject* output = vtkCompositeDataPipeline::SafeDownCast( this->GetExecutive())->GetCompositeOutputData(port); return( vtkUniformGridAMR::SafeDownCast(output) ); } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::SetInput( vtkDataObject* input ) { this->SetInput(0, input); } //------------------------------------------------------------------------------ void vtkUniformGridAMRAlgorithm::SetInput(int index, vtkDataObject* input) { if( input != NULL ) { this->SetInputConnection(index,input->GetProducerPort()); } else { // Setting a NULL input removes the connection this->SetInputConnection(index,0); } } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::ProcessRequest( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) { // create the output if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT())) { return this->RequestDataObject(request, inputVector, outputVector); } // generate the data if(request->Has(vtkCompositeDataPipeline::REQUEST_DATA())) { int retVal = this->RequestData(request,inputVector,outputVector); return( retVal ); } // execute information if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) { if(request->Has(vtkStreamingDemandDrivenPipeline::FROM_OUTPUT_PORT())) { int outputPort = request->Get(vtkStreamingDemandDrivenPipeline::FROM_OUTPUT_PORT()); vtkInformation* info = outputVector->GetInformationObject(outputPort); if( info != NULL ) { info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); } } else { for (int outIdx=0; outIdx < this->GetNumberOfOutputPorts(); outIdx++) { vtkInformation* info = outputVector->GetInformationObject(outIdx); if(info != NULL) { info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),-1); } } } return this->RequestInformation(request, inputVector, outputVector); } // set update extent if( request->Has( vtkCompositeDataPipeline::REQUEST_UPDATE_EXTENT())) { return( this->RequestUpdateExtent(request,inputVector,outputVector) ); } return( this->Superclass::ProcessRequest(request,inputVector,outputVector) ); } //------------------------------------------------------------------------------ vtkExecutive* vtkUniformGridAMRAlgorithm::CreateDefaultExecutive() { return vtkCompositeDataPipeline::New(); } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::FillOutputPortInformation( int port, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUniformGridAMR"); return 1; } //------------------------------------------------------------------------------ int vtkUniformGridAMRAlgorithm::FillInputPortInformation( int port, vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkUniformGridAMR"); return 1; } //------------------------------------------------------------------------------ vtkDataObject* vtkUniformGridAMRAlgorithm::GetInput(int port) { if( this->GetNumberOfInputConnections(port) < 1 ) { return NULL; } return this->GetExecutive()->GetInputData(port,0); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMNode.hpp> #include "DOMDocumentImpl.hpp" #include "DOMNodeListImpl.hpp" #include "DOMRangeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMCasts.hpp" DOMParentNode::DOMParentNode(DOMDocument *ownerDoc) : fOwnerDocument(ownerDoc), fChildNodeList(castToNode(this)) { fFirstChild = 0; }; // This only makes a shallow copy, cloneChildren must also be called for a // deep clone DOMParentNode::DOMParentNode(const DOMParentNode &other) : fChildNodeList(castToNode(this)) { this->fOwnerDocument = other.fOwnerDocument; // Need to break the association w/ original kids this->fFirstChild = 0; }; void DOMParentNode::changed() { DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument()); doc->changed(); } int DOMParentNode::changes() const { DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument()); return doc->changes(); }; DOMNode * DOMParentNode::appendChild(DOMNode *newChild) { return insertBefore(newChild, 0); }; void DOMParentNode::cloneChildren(const DOMNode *other) { // for (DOMNode *mykid = other.getFirstChild(); for (DOMNode *mykid = other->getFirstChild(); mykid != 0; mykid = mykid->getNextSibling()) { appendChild(mykid->cloneNode(true)); } } DOMDocument * DOMParentNode::getOwnerDocument() const { return fOwnerDocument; } // unlike getOwnerDocument this is not overriden by DocumentImpl to return 0 DOMDocument * DOMParentNode::getDocument() const { return fOwnerDocument; } void DOMParentNode::setOwnerDocument(DOMDocument* doc) { fOwnerDocument = doc; } DOMNodeList *DOMParentNode::getChildNodes() const { const DOMNodeList *ret = &fChildNodeList; return (DOMNodeList *)ret; // cast off const. }; DOMNode * DOMParentNode::getFirstChild() const { return fFirstChild; }; DOMNode * DOMParentNode::getLastChild() const { return lastChild(); }; DOMNode * DOMParentNode::lastChild() const { // last child is stored as the previous sibling of first child if (fFirstChild == 0) { return 0; } DOMChildNode *firstChild = castToChildImpl(fFirstChild); DOMNode *ret = firstChild->previousSibling; return ret; }; // // revisit. Is this function used anywhere? I don't see it. // void DOMParentNode::lastChild(DOMNode *node) { // store lastChild as previous sibling of first child if (fFirstChild != 0) { DOMChildNode *firstChild = castToChildImpl(fFirstChild); firstChild->previousSibling = node; } } bool DOMParentNode::hasChildNodes() const { return fFirstChild!=0; }; DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) { DOMNodeImpl *thisNodeImpl = castToNodeImpl(this); if (thisNodeImpl->isReadOnly()) throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0); if (newChild->getOwnerDocument() != fOwnerDocument) throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0); // Prevent cycles in the tree bool treeSafe=true; for(DOMNode *a=castToNode(this)->getParentNode(); treeSafe && a!=0; a=a->getParentNode()) treeSafe=(newChild!=a); if(!treeSafe) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); // refChild must in fact be a child of this node (or 0) if (refChild!=0 && refChild->getParentNode() != castToNode(this)) throw DOMException(DOMException::NOT_FOUND_ERR,0); if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. for(DOMNode *kid=newChild->getFirstChild(); // Prescan kid!=0; kid=kid->getNextSibling()) { if (!DOMDocumentImpl::isKidOK(castToNode(this), kid)) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); } while(newChild->hasChildNodes()) // Move insertBefore(newChild->getFirstChild(),refChild); } else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild)) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); else { DOMNode *oldparent=newChild->getParentNode(); if(oldparent!=0) oldparent->removeChild(newChild); // Attach up castToNodeImpl(newChild)->fOwnerNode = castToNode(this); castToNodeImpl(newChild)->isOwned(true); // Attach before and after // Note: fFirstChild.previousSibling == lastChild!! if (fFirstChild == 0) { // this our first and only child fFirstChild = newChild; castToNodeImpl(newChild)->isFirstChild(true); // castToChildImpl(newChild)->previousSibling = newChild; DOMChildNode *newChild_ci = castToChildImpl(newChild); newChild_ci->previousSibling = newChild; } else { if (refChild == 0) { // this is an append DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling; castToChildImpl(lastChild)->nextSibling = newChild; castToChildImpl(newChild)->previousSibling = lastChild; castToChildImpl(fFirstChild)->previousSibling = newChild; } else { // this is an insert if (refChild == fFirstChild) { // at the head of the list castToNodeImpl(fFirstChild)->isFirstChild(false); castToChildImpl(newChild)->nextSibling = fFirstChild; castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling; castToChildImpl(fFirstChild)->previousSibling = newChild; fFirstChild = newChild; castToNodeImpl(newChild)->isFirstChild(true); } else { // somewhere in the middle DOMNode *prev = castToChildImpl(refChild)->previousSibling; castToChildImpl(newChild)->nextSibling = refChild; castToChildImpl(prev)->nextSibling = newChild; castToChildImpl(refChild)->previousSibling = newChild; castToChildImpl(newChild)->previousSibling = prev; } } } } changed(); if (this->getOwnerDocument() != 0) { Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges(); if ( ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { ranges->elementAt(i)->updateRangeForInsertedNode(newChild); } } } } return newChild; }; DOMNode *DOMParentNode::removeChild(DOMNode *oldChild) { if (castToNodeImpl(this)->isReadOnly()) throw DOMException( DOMException::NO_MODIFICATION_ALLOWED_ERR, 0); if (oldChild != 0 && oldChild->getParentNode() != castToNode(this)) throw DOMException(DOMException::NOT_FOUND_ERR, 0); //fix other ranges for change before deleting the node if (this->getOwnerDocument() != 0 ) { Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges(); if (ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { if (ranges->elementAt(i) != 0) ranges->elementAt(i)->updateRangeForDeletedNode(oldChild); } } } } // Patch linked list around oldChild // Note: lastChild == fFirstChild->previousSibling if (oldChild == fFirstChild) { // removing first child castToNodeImpl(oldChild)->isFirstChild(false); fFirstChild = castToChildImpl(oldChild)->nextSibling; if (fFirstChild != 0) { castToNodeImpl(fFirstChild)->isFirstChild(true); castToChildImpl(fFirstChild)->previousSibling = castToChildImpl(oldChild)->previousSibling; } } else { DOMNode *prev = castToChildImpl(oldChild)->previousSibling; DOMNode *next = castToChildImpl(oldChild)->nextSibling; castToChildImpl(prev)->nextSibling = next; if (next == 0) { // removing last child castToChildImpl(fFirstChild)->previousSibling = prev; } else { // removing some other child in the middle castToChildImpl(next)->previousSibling = prev; } } // Remove oldChild's references to tree castToNodeImpl(oldChild)->fOwnerNode = fOwnerDocument; castToNodeImpl(oldChild)->isOwned(false); castToChildImpl(oldChild)->nextSibling = 0; castToChildImpl(oldChild)->previousSibling = 0; changed(); return oldChild; }; DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild) { insertBefore(newChild, oldChild); // changed() already done. return removeChild(oldChild); }; //Introduced in DOM Level 2 void DOMParentNode::normalize() { DOMNode *kid, *next; for (kid = fFirstChild; kid != 0; kid = next) { next = castToChildImpl(kid)->nextSibling; // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != 0 && kid->getNodeType() == DOMNode::TEXT_NODE && next->getNodeType() == DOMNode::TEXT_NODE ) { ((DOMTextImpl *) kid)->appendData(((DOMTextImpl *) next)->getData()); // revisit: // should I release the removed node? // not released in case user still referencing it externally removeChild(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid->getNodeType() == DOMNode::ELEMENT_NODE) kid->normalize(); }; // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. }; //Introduced in DOM Level 3 bool DOMParentNode::isEqualNode(const DOMNode* arg) { if (castToNodeImpl(this)->isEqualNode(arg)) { DOMNode *kid, *argKid; for (kid = fFirstChild, argKid = arg->getFirstChild(); kid != 0 && argKid != 0; kid = kid->getNextSibling(), argKid = argKid->getNextSibling()) { if (!kid->isEqualNode(argKid)) return false; } return true; } return false; } //Non-standard extension void DOMParentNode::release() { DOMNode *kid, *next; for (kid = fFirstChild; kid != 0; kid = next) { next = castToChildImpl(kid)->nextSibling; // set is Owned false before releasing its child castToNodeImpl(kid)->isToBeReleased(true); kid->release(); } } <commit_msg>isEqualNode: - check for NULL value. - if children length is not the same -> return false.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMException.hpp> #include <xercesc/dom/DOMNode.hpp> #include "DOMDocumentImpl.hpp" #include "DOMNodeListImpl.hpp" #include "DOMRangeImpl.hpp" #include "DOMParentNode.hpp" #include "DOMCasts.hpp" DOMParentNode::DOMParentNode(DOMDocument *ownerDoc) : fOwnerDocument(ownerDoc), fChildNodeList(castToNode(this)) { fFirstChild = 0; }; // This only makes a shallow copy, cloneChildren must also be called for a // deep clone DOMParentNode::DOMParentNode(const DOMParentNode &other) : fChildNodeList(castToNode(this)) { this->fOwnerDocument = other.fOwnerDocument; // Need to break the association w/ original kids this->fFirstChild = 0; }; void DOMParentNode::changed() { DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument()); doc->changed(); } int DOMParentNode::changes() const { DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument()); return doc->changes(); }; DOMNode * DOMParentNode::appendChild(DOMNode *newChild) { return insertBefore(newChild, 0); }; void DOMParentNode::cloneChildren(const DOMNode *other) { // for (DOMNode *mykid = other.getFirstChild(); for (DOMNode *mykid = other->getFirstChild(); mykid != 0; mykid = mykid->getNextSibling()) { appendChild(mykid->cloneNode(true)); } } DOMDocument * DOMParentNode::getOwnerDocument() const { return fOwnerDocument; } // unlike getOwnerDocument this is not overriden by DocumentImpl to return 0 DOMDocument * DOMParentNode::getDocument() const { return fOwnerDocument; } void DOMParentNode::setOwnerDocument(DOMDocument* doc) { fOwnerDocument = doc; } DOMNodeList *DOMParentNode::getChildNodes() const { const DOMNodeList *ret = &fChildNodeList; return (DOMNodeList *)ret; // cast off const. }; DOMNode * DOMParentNode::getFirstChild() const { return fFirstChild; }; DOMNode * DOMParentNode::getLastChild() const { return lastChild(); }; DOMNode * DOMParentNode::lastChild() const { // last child is stored as the previous sibling of first child if (fFirstChild == 0) { return 0; } DOMChildNode *firstChild = castToChildImpl(fFirstChild); DOMNode *ret = firstChild->previousSibling; return ret; }; // // revisit. Is this function used anywhere? I don't see it. // void DOMParentNode::lastChild(DOMNode *node) { // store lastChild as previous sibling of first child if (fFirstChild != 0) { DOMChildNode *firstChild = castToChildImpl(fFirstChild); firstChild->previousSibling = node; } } bool DOMParentNode::hasChildNodes() const { return fFirstChild!=0; }; DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) { DOMNodeImpl *thisNodeImpl = castToNodeImpl(this); if (thisNodeImpl->isReadOnly()) throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0); if (newChild->getOwnerDocument() != fOwnerDocument) throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0); // Prevent cycles in the tree bool treeSafe=true; for(DOMNode *a=castToNode(this)->getParentNode(); treeSafe && a!=0; a=a->getParentNode()) treeSafe=(newChild!=a); if(!treeSafe) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); // refChild must in fact be a child of this node (or 0) if (refChild!=0 && refChild->getParentNode() != castToNode(this)) throw DOMException(DOMException::NOT_FOUND_ERR,0); if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. for(DOMNode *kid=newChild->getFirstChild(); // Prescan kid!=0; kid=kid->getNextSibling()) { if (!DOMDocumentImpl::isKidOK(castToNode(this), kid)) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); } while(newChild->hasChildNodes()) // Move insertBefore(newChild->getFirstChild(),refChild); } else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild)) throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0); else { DOMNode *oldparent=newChild->getParentNode(); if(oldparent!=0) oldparent->removeChild(newChild); // Attach up castToNodeImpl(newChild)->fOwnerNode = castToNode(this); castToNodeImpl(newChild)->isOwned(true); // Attach before and after // Note: fFirstChild.previousSibling == lastChild!! if (fFirstChild == 0) { // this our first and only child fFirstChild = newChild; castToNodeImpl(newChild)->isFirstChild(true); // castToChildImpl(newChild)->previousSibling = newChild; DOMChildNode *newChild_ci = castToChildImpl(newChild); newChild_ci->previousSibling = newChild; } else { if (refChild == 0) { // this is an append DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling; castToChildImpl(lastChild)->nextSibling = newChild; castToChildImpl(newChild)->previousSibling = lastChild; castToChildImpl(fFirstChild)->previousSibling = newChild; } else { // this is an insert if (refChild == fFirstChild) { // at the head of the list castToNodeImpl(fFirstChild)->isFirstChild(false); castToChildImpl(newChild)->nextSibling = fFirstChild; castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling; castToChildImpl(fFirstChild)->previousSibling = newChild; fFirstChild = newChild; castToNodeImpl(newChild)->isFirstChild(true); } else { // somewhere in the middle DOMNode *prev = castToChildImpl(refChild)->previousSibling; castToChildImpl(newChild)->nextSibling = refChild; castToChildImpl(prev)->nextSibling = newChild; castToChildImpl(refChild)->previousSibling = newChild; castToChildImpl(newChild)->previousSibling = prev; } } } } changed(); if (this->getOwnerDocument() != 0) { Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges(); if ( ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { ranges->elementAt(i)->updateRangeForInsertedNode(newChild); } } } } return newChild; }; DOMNode *DOMParentNode::removeChild(DOMNode *oldChild) { if (castToNodeImpl(this)->isReadOnly()) throw DOMException( DOMException::NO_MODIFICATION_ALLOWED_ERR, 0); if (oldChild != 0 && oldChild->getParentNode() != castToNode(this)) throw DOMException(DOMException::NOT_FOUND_ERR, 0); //fix other ranges for change before deleting the node if (this->getOwnerDocument() != 0 ) { Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges(); if (ranges != 0) { XMLSize_t sz = ranges->size(); if (sz != 0) { for (XMLSize_t i =0; i<sz; i++) { if (ranges->elementAt(i) != 0) ranges->elementAt(i)->updateRangeForDeletedNode(oldChild); } } } } // Patch linked list around oldChild // Note: lastChild == fFirstChild->previousSibling if (oldChild == fFirstChild) { // removing first child castToNodeImpl(oldChild)->isFirstChild(false); fFirstChild = castToChildImpl(oldChild)->nextSibling; if (fFirstChild != 0) { castToNodeImpl(fFirstChild)->isFirstChild(true); castToChildImpl(fFirstChild)->previousSibling = castToChildImpl(oldChild)->previousSibling; } } else { DOMNode *prev = castToChildImpl(oldChild)->previousSibling; DOMNode *next = castToChildImpl(oldChild)->nextSibling; castToChildImpl(prev)->nextSibling = next; if (next == 0) { // removing last child castToChildImpl(fFirstChild)->previousSibling = prev; } else { // removing some other child in the middle castToChildImpl(next)->previousSibling = prev; } } // Remove oldChild's references to tree castToNodeImpl(oldChild)->fOwnerNode = fOwnerDocument; castToNodeImpl(oldChild)->isOwned(false); castToChildImpl(oldChild)->nextSibling = 0; castToChildImpl(oldChild)->previousSibling = 0; changed(); return oldChild; }; DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild) { insertBefore(newChild, oldChild); // changed() already done. return removeChild(oldChild); }; //Introduced in DOM Level 2 void DOMParentNode::normalize() { DOMNode *kid, *next; for (kid = fFirstChild; kid != 0; kid = next) { next = castToChildImpl(kid)->nextSibling; // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != 0 && kid->getNodeType() == DOMNode::TEXT_NODE && next->getNodeType() == DOMNode::TEXT_NODE ) { ((DOMTextImpl *) kid)->appendData(((DOMTextImpl *) next)->getData()); // revisit: // should I release the removed node? // not released in case user still referencing it externally removeChild(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid->getNodeType() == DOMNode::ELEMENT_NODE) kid->normalize(); }; // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. }; //Introduced in DOM Level 3 bool DOMParentNode::isEqualNode(const DOMNode* arg) { if (arg && castToNodeImpl(this)->isEqualNode(arg)) { DOMNode *kid, *argKid; for (kid = fFirstChild, argKid = arg->getFirstChild(); kid != 0 && argKid != 0; kid = kid->getNextSibling(), argKid = argKid->getNextSibling()) { if (!kid->isEqualNode(argKid)) return false; } return (kid || argKid) ? false : true; } return false; } //Non-standard extension void DOMParentNode::release() { DOMNode *kid, *next; for (kid = fFirstChild; kid != 0; kid = next) { next = castToChildImpl(kid)->nextSibling; // set is Owned false before releasing its child castToNodeImpl(kid)->isToBeReleased(true); kid->release(); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <JSON.h> #include <Hooks.h> #include <text.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () : _enabled (true) , _debug (0) { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { _debug = context.config.getInteger ("debug.hooks"); // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); if (_debug >= 1) { std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) context.debug ("Found hook script " + *i); } } else if (_debug >= 1) context.debug ("Hook directory not readable: " + d._data); _enabled = context.config.getBoolean ("hooks"); } //////////////////////////////////////////////////////////////////////////////// bool Hooks::enable (bool value) { bool old_value = _enabled; _enabled = value; return old_value; } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before any // processing occurs, i.e first // // Input: // - none // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onLaunch () { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string output; std::vector <std::string> args; int status = execute (*i, args, "", output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (isJSON (*line)) { if (_debug >= 2) context.debug ("Hook output: " + *line); // Only 'add' is possible. Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-exit event is triggered once, after all processing is complete, i.e. // last // // Input: // - read-only line of JSON for each task added/modified // // Output: // - any emitted JSON is ignored // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onExit () { if (! _enabled) return; context.timer_hooks.start (); std::vector <Task> changes; context.tdb2.get_changes (changes); std::string input = ""; std::vector <Task>::const_iterator t; for (t = changes.begin (); t != changes.end (); ++t) { std::string json = t->composeJSON (); if (_debug >= 2) context.debug ("Hook input: " + json); input += json + "\n"; } std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (! isJSON (*line)) { if (status == 0) context.footnote (*line); else context.error (*line); } } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - line of JSON for the task added // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onAdd (std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string input = changes.at(0).composeJSON (); if (_debug >= 2) context.debug ("Hook input: " + input); input += "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (isJSON (*line)) changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - line of JSON for the original task // - line of JSON for the modified task, the diff being the modification // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onModify (const Task& before, std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string beforeJSON = before.composeJSON (); std::string afterJSON = changes[0].composeJSON (); if (_debug >= 2) { context.debug ("Hook input: " + beforeJSON); context.debug ("Hook input: " + afterJSON); } std::string input = beforeJSON + "\n" + afterJSON + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (isJSON (*line)) changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// bool Hooks::isJSON (const std::string& input) const { if (input.length () && input[0] == '{' && input[input.length () - 1] == '}') { try { Task maybe (input); return true; } catch (const std::string& e) { if (_debug >= 1) context.debug ("Hook output looks like JSON, but is not a valid task."); if (_debug >= 2) context.debug ("JSON parser error: " + e); } catch (...) { if (_debug >= 1) context.debug ("Hook output looks like JSON, but fails to parse."); } } return false; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Hooks<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <JSON.h> #include <Hooks.h> #include <text.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () : _enabled (true) , _debug (0) { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { _debug = context.config.getInteger ("debug.hooks"); // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); if (_debug >= 1) { std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) context.debug ("Found hook script " + *i); } } else if (_debug >= 1) context.debug ("Hook directory not readable: " + d._data); _enabled = context.config.getBoolean ("hooks"); } //////////////////////////////////////////////////////////////////////////////// bool Hooks::enable (bool value) { bool old_value = _enabled; _enabled = value; return old_value; } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before any // processing occurs, i.e first // // Input: // - none // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onLaunch () { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string output; std::vector <std::string> args; int status = execute (*i, args, "", output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (isJSON (*line)) { if (_debug >= 2) context.debug ("Hook output: " + *line); // Only 'add' is possible. Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-exit event is triggered once, after all processing is complete, i.e. // last // // Input: // - read-only line of JSON for each task added/modified // // Output: // - any emitted JSON is ignored // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onExit () { if (! _enabled) return; context.timer_hooks.start (); std::vector <Task> changes; context.tdb2.get_changes (changes); std::string input = ""; std::vector <Task>::const_iterator t; for (t = changes.begin (); t != changes.end (); ++t) { std::string json = t->composeJSON (); if (_debug >= 2) context.debug ("Hook input: " + json); input += json + "\n"; } std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (! isJSON (*line)) { if (status == 0) context.footnote (*line); else context.error (*line); } } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - line of JSON for the task added // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onAdd (std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string input = changes.at(0).composeJSON (); if (_debug >= 2) context.debug ("Hook input: " + input); input += "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (isJSON (*line)) changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - line of JSON for the original task // - line of JSON for the modified task, the diff being the modification // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onModify (const Task& before, std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { if (_debug >= 1) context.debug ("Hooks: Calling " + *i); std::string beforeJSON = before.composeJSON (); std::string afterJSON = changes[0].composeJSON (); if (_debug >= 2) { context.debug ("Hook input: " + beforeJSON); context.debug ("Hook input: " + afterJSON); } std::string input = beforeJSON + "\n" + afterJSON + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); if (_debug >= 2) context.debug (format ("Hooks: Completed with status {1}", status)); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (_debug >= 2) context.debug ("Hook output: " + *line); if (isJSON (*line)) changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (! isJSON (*line)) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// bool Hooks::isJSON (const std::string& input) const { // Does it even look like JSON? {...} if (input.length () > 2 && input[0] == '{' && input[input.length () - 1] == '}') { try { // The absolute minimum a task needs is: bool foundDescription = false; bool foundStatus = false; // Parse the whole thing. json::value* root = json::parse (input); if (root->type () == json::j_object) { json::object* root_obj = (json::object*)root; // For each object element... json_object_iter i; for (i = root_obj->_data.begin (); i != root_obj->_data.end (); ++i) { // If the attribute is a recognized column. std::string type = Task::attributes[i->first]; if (type != "") { if (i->first == "description" && type == "string") foundDescription = true; if (i->first == "status" && type == "string") foundStatus = true; } } } // It's JSON, but is it a task? if (! foundDescription) throw std::string ("Missing 'description' attribute, of type 'string'."); if (! foundStatus) throw std::string ("Missing 'status' attribute, of type 'string'."); // Yep, looks like a JSON task. return true; } catch (const std::string& e) { if (_debug >= 1) context.error ("Hook output looks like JSON, but is not a valid task."); if (_debug >= 2) context.error ("JSON " + e); } catch (...) { if (_debug >= 1) context.error ("Hook output looks like JSON, but fails to parse."); } } return false; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "Matrix.h" #include "Vektor.h" #include <limits> #include <iostream> using namespace std; int Matrix::counter = 0; Matrix::Matrix(int m, int n) :m_Zeilen(m), m_Spalten(n), m_Element(new float[m * n]) { for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = 0; } counter++; } Matrix::Matrix(const Matrix& other) { m_Zeilen = other.m_Zeilen; m_Spalten = other.m_Spalten; m_Element = new float[m_Zeilen * m_Spalten]; for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = other.m_Element[i]; } } Matrix& Matrix::operator=(const Matrix& other) { if (this != &other) { m_Zeilen = other.m_Zeilen; m_Spalten = other.m_Spalten; delete [] m_Element; m_Element = new float[m_Zeilen * m_Spalten]; for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = other.m_Element[i]; } } return *this; } float& Matrix::operator()(int zeile, int spalte) { if (m_Zeilen <= m_Spalten) { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Spalten * (zeile - 1)) + (spalte - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } else { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Zeilen * (spalte - 1)) + (zeile - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } } const float& Matrix::operator()(int zeile, int spalte) const { if (m_Zeilen <= m_Spalten) { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Spalten * (zeile - 1)) + (spalte - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } else { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Zeilen * (spalte - 1)) + (zeile - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } } Matrix::~Matrix() { #ifdef DEBUG cout << "Matrix ("; ausgabe(false); cout << ") wird zerstoert" << endl; #endif delete [] m_Element; counter--; #ifdef DEBUG cout << "Matrix wurde zerstoert" << endl; #endif } void Matrix::ausgabe(bool endline) const { for (int i = 0; i < m_Zeilen * m_Spalten; i++) { cout << " " << m_Element[i]; } if (endline) { cout << endl; } } int Matrix::getCounter() { return counter; }<commit_msg>Cleanup & Formatted Output<commit_after>#include "Matrix.h" #include "Vektor.h" #include <limits> #include <iostream> using namespace std; int Matrix::counter = 0; Matrix::Matrix(int m, int n) :m_Zeilen(m), m_Spalten(n), m_Element(new float[m * n]) { for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = 0; } counter++; } Matrix::Matrix(const Matrix& other) { m_Zeilen = other.m_Zeilen; m_Spalten = other.m_Spalten; m_Element = new float[m_Zeilen * m_Spalten]; for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = other.m_Element[i]; } } Matrix& Matrix::operator=(const Matrix& other) { if (this != &other) { m_Zeilen = other.m_Zeilen; m_Spalten = other.m_Spalten; delete [] m_Element; m_Element = new float[m_Zeilen * m_Spalten]; for (int i = 0; i < m_Zeilen * m_Spalten; i++) { m_Element[i] = other.m_Element[i]; } } return *this; } float& Matrix::operator()(int zeile, int spalte) { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Spalten * (zeile - 1)) + (spalte - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } const float& Matrix::operator()(int zeile, int spalte) const { if (m_Zeilen >= zeile && m_Spalten >= spalte) { return m_Element[(m_Spalten * (zeile - 1)) + (spalte - 1)]; } else { throw numeric_limits<float>::quiet_NaN(); } } Matrix::~Matrix() { #ifdef DEBUG cout << "Matrix ("; ausgabe(false); cout << ") wird zerstoert" << endl; #endif delete [] m_Element; counter--; #ifdef DEBUG cout << "Matrix wurde zerstoert" << endl; #endif } void Matrix::ausgabe(bool endline) const { int count = 0; for (int i = 0; i < m_Zeilen * m_Spalten; i++) { count++; cout << " " << m_Element[i]; if (count >= m_Spalten) { cout << endl; count = 0; } } if (endline) { cout << endl; } } int Matrix::getCounter() { return counter; }<|endoftext|>
<commit_before>#include <build_properties.h> #include <private-key.h> #include "license-generator.h" #include "../base_lib/CryptoHelper.h" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> #include <iostream> #include <string.h> #include <boost/date_time.hpp> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/unordered_map.hpp> #include <boost/assign.hpp> #include <fstream> #include <regex> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace bt = boost::posix_time; namespace po = boost::program_options; using namespace std; namespace license { void LicenseGenerator::printHelp(const char* prog_name, const po::options_description& options) { cout << endl; cout << prog_name << " Version " << PROJECT_VERSION << endl << ". Usage:" << endl; cout << prog_name << " [options] product_name1 product_name2 ... " << endl << endl; cout << " product_name1 ... = Product name. This string must match the one passed by the software." << endl; cout << options << endl; } po::options_description LicenseGenerator::configureProgramOptions() { po::options_description common("General options"); common.add_options()("help,h", "print help message and exit.") // ("verbose,v", "print more information.") // ("output,o", po::value<string>(), "Output file name. If not specified the " "license will be printed in standard output"); // po::options_description licenseGeneration("License Generation"); licenseGeneration.add_options()("private_key,p", po::value<string>(), "Specify an alternate file for the primary key to be used. " "If not specified the internal primary key will be used.") // ("begin_date,b", po::value<string>(), "Specify the start of the validity for this license. " " Format YYYYMMDD. If not specified defaults to today") // ("expire_date,e", po::value<string>(), "Specify the expire date for this license. " " Format YYYYMMDD. If not specified the license won't expire") // ("client_signature,s", po::value<string>(), "The signature of the pc that requires the license. " "It should be in the format XXXX-XXXX-XXXX-XXXX." " If not specified the license " "won't be linked to a specific pc.") // ("start_version,t", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the first version of the software this license apply to.") // ("end_version,n", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the last version of the software this license apply to."); // po::options_description visibleOptions; visibleOptions.add(common).add(licenseGeneration); return visibleOptions; } vector<FullLicenseInfo> LicenseGenerator::parseLicenseInfo( const po::variables_map& vm) { string begin_date = FullLicenseInfo::UNUSED_TIME; string end_date = FullLicenseInfo::UNUSED_TIME; if (vm.count("expire_date")) { const std::string dt_end = vm["expire_date"].as<string>(); try { end_date = normalize_date(dt_end); char curdate[20]; time_t curtime = time(NULL); strftime(curdate, 20, "%Y-%m-%d", localtime(&curtime)); begin_date.assign(curdate); } catch (const invalid_argument &e) { cerr << endl << "End date not recognized: " << dt_end << " Please enter a valid date in format YYYYMMDD" << endl; exit(2); } } if (vm.count("begin_date")) { const std::string begin_date_str = vm["begin_date"].as<string>(); try { begin_date = normalize_date(begin_date_str); } catch (invalid_argument &e) { cerr << endl << "Begin date not recognized: " << begin_date_str << " Please enter a valid date in format YYYYMMDD" << endl; //print_usage(vm); exit(2); } } string client_signature = ""; if (vm.count("client_signature")) { client_signature = vm["client_signature"].as<string>(); //fixme match + and / /*regex e("(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}-(A-Za-z0-9){4}"); if (!regex_match(client_signature, e)) { cerr << endl << "Client signature not recognized: " << client_signature << " Please enter a valid signature in format XXXX-XXXX-XXXX-XXXX" << endl; exit(2); }*/ } string extra_data = ""; if (vm.count("extra_data")) { extra_data = vm["extra_data"].as<string>(); } unsigned int from_sw_version = vm["start_version"].as<unsigned int>(); unsigned int to_sw_version = vm["end_version"].as<unsigned int>(); if (vm.count("product") == 0) { cerr << endl << "Parameter [product] not found. " << endl; exit(2); } vector<string> products = vm["product"].as<vector<string>>(); vector<FullLicenseInfo> licInfo; licInfo.reserve(products.size()); for (auto it = products.begin(); it != products.end(); it++) { if (boost::algorithm::trim_copy(*it).length() > 0) { licInfo.push_back( FullLicenseInfo("", *it, "", PROJECT_INT_VERSION, begin_date, end_date, client_signature, from_sw_version, to_sw_version, extra_data)); } } return licInfo; } void LicenseGenerator::generateAndOutputLicenses(const po::variables_map& vm, ostream& outputFile) { vector<FullLicenseInfo> licenseInfo = parseLicenseInfo(vm); unique_ptr<CryptoHelper> helper = CryptoHelper::getInstance(); const char pkey[] = PRIVATE_KEY; size_t len = sizeof(pkey); for (auto it = licenseInfo.begin(); it != licenseInfo.end(); ++it) { const string license = it->printForSign(); string signature = helper->signString((const void *)pkey,len,license); it->license_signature = signature; it->printAsIni(outputFile); } } int LicenseGenerator::generateLicense(int argc, const char **argv) { po::options_description visibleOptions = configureProgramOptions(); //positional options must be added to standard options po::options_description allOptions; allOptions.add(visibleOptions).add_options()("product", po::value<vector<string>>(), "product names"); po::positional_options_description p; p.add("product", -1); po::variables_map vm; po::store( po::command_line_parser(argc, argv).options(allOptions).positional( p).run(), vm); po::notify(vm); if (vm.count("help") || argc == 1) { printHelp(argv[0], visibleOptions); return 0; } if (vm.count("output")) { const std::string fname = vm["output"].as<string>(); fstream ofstream(fname, std::ios::out | std::ios::trunc); if (!ofstream.is_open()) { cerr << "can't open file [" << fname << "] for output." << endl << " error: " << strerror( errno); exit(3); } generateAndOutputLicenses(vm, ofstream); ofstream.close(); } else { generateAndOutputLicenses(vm, cout); } return 0; } const std::string formats[] = { "%4u-%2u-%2u", "%4u/%2u/%2u", "%4u%2u%2u" }; const size_t formats_n = 3; string LicenseGenerator::normalize_date(const std::string& sDate) { if(sDate.size()<8) throw invalid_argument("Date string too small for known formats"); unsigned int year, month, day; bool found = false; for (size_t i = 0; i < formats_n && !found; ++i) { const int chread = sscanf(sDate.c_str(),formats[i].c_str(),&year,&month,&day); if(chread==3) { found = true; break; } } if(!found) throw invalid_argument("Date string did not match a known format"); ostringstream oss; oss << year << "-" << setfill('0') << std::setw(2) << month << "-" << setfill('0') << std::setw(2) << day; return oss.str(); } } <commit_msg>fix regex to check format of client signature<commit_after>#include <build_properties.h> #include <private-key.h> #include "license-generator.h" #include "../base_lib/CryptoHelper.h" #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> #include <iostream> #include <string.h> #include <boost/date_time.hpp> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/unordered_map.hpp> #include <boost/assign.hpp> #include <fstream> #include <regex> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace bt = boost::posix_time; namespace po = boost::program_options; using namespace std; namespace license { void LicenseGenerator::printHelp(const char* prog_name, const po::options_description& options) { cout << endl; cout << prog_name << " Version " << PROJECT_VERSION << endl << ". Usage:" << endl; cout << prog_name << " [options] product_name1 product_name2 ... " << endl << endl; cout << " product_name1 ... = Product name. This string must match the one passed by the software." << endl; cout << options << endl; } po::options_description LicenseGenerator::configureProgramOptions() { po::options_description common("General options"); common.add_options()("help,h", "print help message and exit.") // ("verbose,v", "print more information.") // ("output,o", po::value<string>(), "Output file name. If not specified the " "license will be printed in standard output"); // po::options_description licenseGeneration("License Generation"); licenseGeneration.add_options()("private_key,p", po::value<string>(), "Specify an alternate file for the primary key to be used. " "If not specified the internal primary key will be used.") // ("begin_date,b", po::value<string>(), "Specify the start of the validity for this license. " " Format YYYYMMDD. If not specified defaults to today") // ("expire_date,e", po::value<string>(), "Specify the expire date for this license. " " Format YYYYMMDD. If not specified the license won't expire") // ("client_signature,s", po::value<string>(), "The signature of the pc that requires the license. " "It should be in the format XXXX-XXXX-XXXX-XXXX." " If not specified the license " "won't be linked to a specific pc.") // ("start_version,t", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the first version of the software this license apply to.") // ("end_version,n", po::value<unsigned int>()->default_value(0 /*FullLicenseInfo.UNUSED_SOFTWARE_VERSION*/, "All Versions"), "Specify the last version of the software this license apply to."); // po::options_description visibleOptions; visibleOptions.add(common).add(licenseGeneration); return visibleOptions; } vector<FullLicenseInfo> LicenseGenerator::parseLicenseInfo( const po::variables_map& vm) { string begin_date = FullLicenseInfo::UNUSED_TIME; string end_date = FullLicenseInfo::UNUSED_TIME; if (vm.count("expire_date")) { const std::string dt_end = vm["expire_date"].as<string>(); try { end_date = normalize_date(dt_end); char curdate[20]; time_t curtime = time(NULL); strftime(curdate, 20, "%Y-%m-%d", localtime(&curtime)); begin_date.assign(curdate); } catch (const invalid_argument &e) { cerr << endl << "End date not recognized: " << dt_end << " Please enter a valid date in format YYYYMMDD" << endl; exit(2); } } if (vm.count("begin_date")) { const std::string begin_date_str = vm["begin_date"].as<string>(); try { begin_date = normalize_date(begin_date_str); } catch (invalid_argument &e) { cerr << endl << "Begin date not recognized: " << begin_date_str << " Please enter a valid date in format YYYYMMDD" << endl; //print_usage(vm); exit(2); } } string client_signature = ""; if (vm.count("client_signature")) { client_signature = vm["client_signature"].as<string>(); regex e("[A-Za-z0-9\\+/]{4}-[A-Za-z0-9\\+/]{4}-[A-Za-z0-9\\+/]{4}-[A-Za-z0-9\\+/]{4}"); if (!regex_match(client_signature, e)) { cerr << endl << "Client signature not recognized: " << client_signature << " Please enter a valid signature in format XXXX-XXXX-XXXX-XXXX" << endl; exit(2); } } string extra_data = ""; if (vm.count("extra_data")) { extra_data = vm["extra_data"].as<string>(); } unsigned int from_sw_version = vm["start_version"].as<unsigned int>(); unsigned int to_sw_version = vm["end_version"].as<unsigned int>(); if (vm.count("product") == 0) { cerr << endl << "Parameter [product] not found. " << endl; exit(2); } vector<string> products = vm["product"].as<vector<string>>(); vector<FullLicenseInfo> licInfo; licInfo.reserve(products.size()); for (auto it = products.begin(); it != products.end(); it++) { if (boost::algorithm::trim_copy(*it).length() > 0) { licInfo.push_back( FullLicenseInfo("", *it, "", PROJECT_INT_VERSION, begin_date, end_date, client_signature, from_sw_version, to_sw_version, extra_data)); } } return licInfo; } void LicenseGenerator::generateAndOutputLicenses(const po::variables_map& vm, ostream& outputFile) { vector<FullLicenseInfo> licenseInfo = parseLicenseInfo(vm); unique_ptr<CryptoHelper> helper = CryptoHelper::getInstance(); const char pkey[] = PRIVATE_KEY; size_t len = sizeof(pkey); for (auto it = licenseInfo.begin(); it != licenseInfo.end(); ++it) { const string license = it->printForSign(); string signature = helper->signString((const void *)pkey,len,license); it->license_signature = signature; it->printAsIni(outputFile); } } int LicenseGenerator::generateLicense(int argc, const char **argv) { po::options_description visibleOptions = configureProgramOptions(); //positional options must be added to standard options po::options_description allOptions; allOptions.add(visibleOptions).add_options()("product", po::value<vector<string>>(), "product names"); po::positional_options_description p; p.add("product", -1); po::variables_map vm; po::store( po::command_line_parser(argc, argv).options(allOptions).positional( p).run(), vm); po::notify(vm); if (vm.count("help") || argc == 1) { printHelp(argv[0], visibleOptions); return 0; } if (vm.count("output")) { const std::string fname = vm["output"].as<string>(); fstream ofstream(fname, std::ios::out | std::ios::trunc); if (!ofstream.is_open()) { cerr << "can't open file [" << fname << "] for output." << endl << " error: " << strerror( errno); exit(3); } generateAndOutputLicenses(vm, ofstream); ofstream.close(); } else { generateAndOutputLicenses(vm, cout); } return 0; } const std::string formats[] = { "%4u-%2u-%2u", "%4u/%2u/%2u", "%4u%2u%2u" }; const size_t formats_n = 3; string LicenseGenerator::normalize_date(const std::string& sDate) { if(sDate.size()<8) throw invalid_argument("Date string too small for known formats"); unsigned int year, month, day; bool found = false; for (size_t i = 0; i < formats_n && !found; ++i) { const int chread = sscanf(sDate.c_str(),formats[i].c_str(),&year,&month,&day); if(chread==3) { found = true; break; } } if(!found) throw invalid_argument("Date string did not match a known format"); ostringstream oss; oss << year << "-" << setfill('0') << std::setw(2) << month << "-" << setfill('0') << std::setw(2) << day; return oss.str(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartWidget.cxx /// \date 11/21/2006 #ifdef _MSC_VER // Disable warnings that Qt headers give. #pragma warning(disable:4127) #endif #include "vtkQtChartWidget.h" #include "vtkQtChartArea.h" #include "vtkQtChartLegend.h" #include "vtkQtChartTitle.h" #include <QGridLayout> #include <QHBoxLayout> #include <QPainter> #include <QPrinter> #include <QString> #include <QStringList> #include <QVBoxLayout> vtkQtChartWidget::vtkQtChartWidget(QWidget *widgetParent) : QWidget(widgetParent) { // Initialize the chart members this->Title = 0; this->Legend = 0; this->Charts = new vtkQtChartArea(this); this->LeftTitle = 0; this->TopTitle = 0; this->RightTitle = 0; this->BottomTitle = 0; // Set the background color. this->setBackgroundRole(QPalette::Base); this->setAutoFillBackground(true); // Set up the chart layout. this->TitleLayout = new QVBoxLayout(this); this->TitleLayout->setMargin(6); this->TitleLayout->setSpacing(4); this->LegendLayout = new QGridLayout(); this->LegendLayout->setMargin(0); this->LegendLayout->setSpacing(4); this->TopLayout = new QVBoxLayout(); this->TopLayout->setMargin(0); this->TopLayout->setSpacing(4); this->ChartLayout = new QHBoxLayout(); this->ChartLayout->setMargin(0); this->ChartLayout->setSpacing(4); this->TitleLayout->addLayout(this->LegendLayout); this->LegendLayout->addLayout(this->TopLayout, 1, 1); this->TopLayout->addLayout(this->ChartLayout); // Add the chart to its place in the layout. this->Charts->setObjectName("ChartArea"); this->ChartLayout->addWidget(this->Charts); this->setFocusPolicy(Qt::WheelFocus); } vtkQtChartWidget::~vtkQtChartWidget() { } void vtkQtChartWidget::setTitle(vtkQtChartTitle *title) { if(this->Title != title) { if(this->Title) { // Remove the current title from the layout. this->Title->hide(); this->TitleLayout->removeWidget(this->Title); } this->Title = title; if(this->Title) { // Make sure the new title has the proper parent. Then, insert // the new title in the layout. this->Title->setParent(this); this->TitleLayout->insertWidget(0, this->Title); this->Title->show(); } emit this->newChartTitle(this->Title); } } void vtkQtChartWidget::setLegend(vtkQtChartLegend *legend) { if(this->Legend != legend) { if(this->Legend) { // Remove the current legend from the layout. this->disconnect(this->Legend, 0, this, 0); this->Legend->hide(); this->LegendLayout->removeWidget(this->Legend); } this->Legend = legend; if(this->Legend) { this->Legend->setParent(this); if(this->Legend->getLocation() == vtkQtChartLegend::Left) { this->LegendLayout->addWidget(this->Legend, 1, 0); } else if(this->Legend->getLocation() == vtkQtChartLegend::Top) { this->LegendLayout->addWidget(this->Legend, 0, 1); } else if(this->Legend->getLocation() == vtkQtChartLegend::Right) { this->LegendLayout->addWidget(this->Legend, 1, 2); } else if(this->Legend->getLocation() == vtkQtChartLegend::Bottom) { this->LegendLayout->addWidget(this->Legend, 3, 1); } this->connect(this->Legend, SIGNAL(locationChanged()), this, SLOT(changeLegendLocation())); this->Legend->show(); } emit this->newChartLegend(this->Legend); } } vtkQtChartTitle *vtkQtChartWidget::getAxisTitle(vtkQtChartAxis::AxisLocation axis) const { if(axis == vtkQtChartAxis::Left) { return this->LeftTitle; } else if(axis == vtkQtChartAxis::Top) { return this->TopTitle; } else if(axis == vtkQtChartAxis::Right) { return this->RightTitle; } else { return this->BottomTitle; } } void vtkQtChartWidget::setAxisTitle(vtkQtChartAxis::AxisLocation axis, vtkQtChartTitle *title) { if(axis == vtkQtChartAxis::Left) { if(this->LeftTitle != title) { if(this->LeftTitle) { this->LeftTitle->hide(); this->ChartLayout->removeWidget(this->LeftTitle); } this->LeftTitle = title; if(this->LeftTitle) { this->LeftTitle->setParent(this); this->LeftTitle->setOrientation(Qt::Vertical); this->ChartLayout->insertWidget(0, this->LeftTitle); this->LeftTitle->show(); } emit this->newAxisTitle(axis, this->LeftTitle); } } else if(axis == vtkQtChartAxis::Top) { if(this->TopTitle != title) { if(this->TopTitle) { this->TopTitle->hide(); this->TopLayout->removeWidget(this->TopTitle); } this->TopTitle = title; if(this->TopTitle) { this->TopTitle->setParent(this); this->TopTitle->setOrientation(Qt::Horizontal); this->TopLayout->insertWidget(0, this->TopTitle); this->TopTitle->show(); } emit this->newAxisTitle(axis, this->TopTitle); } } else if(axis == vtkQtChartAxis::Right) { if(this->RightTitle != title) { if(this->RightTitle) { this->RightTitle->hide(); this->ChartLayout->removeWidget(this->RightTitle); } this->RightTitle = title; if(this->RightTitle) { this->RightTitle->setParent(this); this->RightTitle->setOrientation(Qt::Vertical); this->ChartLayout->addWidget(this->RightTitle); this->RightTitle->show(); } emit this->newAxisTitle(axis, this->RightTitle); } } else if(this->BottomTitle != title) { if(this->BottomTitle) { this->BottomTitle->hide(); this->TopLayout->removeWidget(this->BottomTitle); } this->BottomTitle = title; if(this->BottomTitle) { this->BottomTitle->setParent(this); this->BottomTitle->setOrientation(Qt::Horizontal); this->TopLayout->addWidget(this->BottomTitle); this->BottomTitle->show(); } emit this->newAxisTitle(axis, this->BottomTitle); } } QSize vtkQtChartWidget::sizeHint() const { this->ensurePolished(); return QSize(150, 150); } void vtkQtChartWidget::printChart(QPrinter &printer) { // Set up the painter for the printer. QSize viewportSize = this->size(); viewportSize.scale(printer.pageRect().size(), Qt::KeepAspectRatio); QPainter painter(&printer); painter.setWindow(this->rect()); painter.setViewport(QRect(QPoint(0, 0), viewportSize)); // Print each of the child components. if(this->Title) { painter.save(); painter.translate(this->Title->mapToParent(QPoint(0, 0))); this->Title->drawTitle(painter); painter.restore(); } if(this->Legend) { painter.save(); painter.translate(this->Legend->mapToParent(QPoint(0, 0))); this->Legend->drawLegend(painter); painter.restore(); } if(this->LeftTitle) { painter.save(); painter.translate(this->LeftTitle->mapToParent(QPoint(0, 0))); this->LeftTitle->drawTitle(painter); painter.restore(); } if(this->TopTitle) { painter.save(); painter.translate(this->TopTitle->mapToParent(QPoint(0, 0))); this->TopTitle->drawTitle(painter); painter.restore(); } if(this->RightTitle) { painter.save(); painter.translate(this->RightTitle->mapToParent(QPoint(0, 0))); this->RightTitle->drawTitle(painter); painter.restore(); } if(this->BottomTitle) { painter.save(); painter.translate(this->BottomTitle->mapToParent(QPoint(0, 0))); this->BottomTitle->drawTitle(painter); painter.restore(); } painter.translate(this->Charts->mapToParent(QPoint(0, 0))); this->Charts->render(&painter, this->Charts->rect()); } void vtkQtChartWidget::saveChart(const QStringList &files) { QStringList::ConstIterator iter = files.begin(); for( ; iter != files.end(); ++iter) { this->saveChart(*iter); } } void vtkQtChartWidget::saveChart(const QString &filename) { if(filename.endsWith(".pdf", Qt::CaseInsensitive)) { QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filename); this->printChart(printer); } else { QPixmap grab = QPixmap::grabWidget(this); grab.save(filename); } } void vtkQtChartWidget::changeLegendLocation() { // Remove the legend from its current location. this->LegendLayout->removeWidget(this->Legend); // Put the legend back in the appropriate spot. if(this->Legend->getLocation() == vtkQtChartLegend::Left) { this->LegendLayout->addWidget(this->Legend, 1, 0); } else if(this->Legend->getLocation() == vtkQtChartLegend::Top) { this->LegendLayout->addWidget(this->Legend, 0, 1); } else if(this->Legend->getLocation() == vtkQtChartLegend::Right) { this->LegendLayout->addWidget(this->Legend, 1, 2); } else if(this->Legend->getLocation() == vtkQtChartLegend::Bottom) { this->LegendLayout->addWidget(this->Legend, 3, 1); } } <commit_msg>COMP: Trying to reduce memory leaks in Qt classes.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartWidget.cxx /// \date 11/21/2006 #ifdef _MSC_VER // Disable warnings that Qt headers give. #pragma warning(disable:4127) #endif #include "vtkQtChartWidget.h" #include "vtkQtChartArea.h" #include "vtkQtChartLegend.h" #include "vtkQtChartTitle.h" #include <QGridLayout> #include <QHBoxLayout> #include <QPainter> #include <QPrinter> #include <QString> #include <QStringList> #include <QVBoxLayout> vtkQtChartWidget::vtkQtChartWidget(QWidget *widgetParent) : QWidget(widgetParent) { // Initialize the chart members this->Title = 0; this->Legend = 0; this->Charts = new vtkQtChartArea(this); this->LeftTitle = 0; this->TopTitle = 0; this->RightTitle = 0; this->BottomTitle = 0; // Set the background color. this->setBackgroundRole(QPalette::Base); this->setAutoFillBackground(true); // Set up the chart layout. this->TitleLayout = new QVBoxLayout(this); this->TitleLayout->setMargin(6); this->TitleLayout->setSpacing(4); this->LegendLayout = new QGridLayout(); this->LegendLayout->setMargin(0); this->LegendLayout->setSpacing(4); this->TopLayout = new QVBoxLayout(); this->TopLayout->setMargin(0); this->TopLayout->setSpacing(4); this->ChartLayout = new QHBoxLayout(); this->ChartLayout->setMargin(0); this->ChartLayout->setSpacing(4); this->TitleLayout->addLayout(this->LegendLayout); this->LegendLayout->addLayout(this->TopLayout, 1, 1); this->TopLayout->addLayout(this->ChartLayout); // Add the chart to its place in the layout. this->Charts->setObjectName("ChartArea"); this->ChartLayout->addWidget(this->Charts); this->setFocusPolicy(Qt::WheelFocus); } vtkQtChartWidget::~vtkQtChartWidget() { delete this->Charts; } void vtkQtChartWidget::setTitle(vtkQtChartTitle *title) { if(this->Title != title) { if(this->Title) { // Remove the current title from the layout. this->Title->hide(); this->TitleLayout->removeWidget(this->Title); } this->Title = title; if(this->Title) { // Make sure the new title has the proper parent. Then, insert // the new title in the layout. this->Title->setParent(this); this->TitleLayout->insertWidget(0, this->Title); this->Title->show(); } emit this->newChartTitle(this->Title); } } void vtkQtChartWidget::setLegend(vtkQtChartLegend *legend) { if(this->Legend != legend) { if(this->Legend) { // Remove the current legend from the layout. this->disconnect(this->Legend, 0, this, 0); this->Legend->hide(); this->LegendLayout->removeWidget(this->Legend); } this->Legend = legend; if(this->Legend) { this->Legend->setParent(this); if(this->Legend->getLocation() == vtkQtChartLegend::Left) { this->LegendLayout->addWidget(this->Legend, 1, 0); } else if(this->Legend->getLocation() == vtkQtChartLegend::Top) { this->LegendLayout->addWidget(this->Legend, 0, 1); } else if(this->Legend->getLocation() == vtkQtChartLegend::Right) { this->LegendLayout->addWidget(this->Legend, 1, 2); } else if(this->Legend->getLocation() == vtkQtChartLegend::Bottom) { this->LegendLayout->addWidget(this->Legend, 3, 1); } this->connect(this->Legend, SIGNAL(locationChanged()), this, SLOT(changeLegendLocation())); this->Legend->show(); } emit this->newChartLegend(this->Legend); } } vtkQtChartTitle *vtkQtChartWidget::getAxisTitle(vtkQtChartAxis::AxisLocation axis) const { if(axis == vtkQtChartAxis::Left) { return this->LeftTitle; } else if(axis == vtkQtChartAxis::Top) { return this->TopTitle; } else if(axis == vtkQtChartAxis::Right) { return this->RightTitle; } else { return this->BottomTitle; } } void vtkQtChartWidget::setAxisTitle(vtkQtChartAxis::AxisLocation axis, vtkQtChartTitle *title) { if(axis == vtkQtChartAxis::Left) { if(this->LeftTitle != title) { if(this->LeftTitle) { this->LeftTitle->hide(); this->ChartLayout->removeWidget(this->LeftTitle); } this->LeftTitle = title; if(this->LeftTitle) { this->LeftTitle->setParent(this); this->LeftTitle->setOrientation(Qt::Vertical); this->ChartLayout->insertWidget(0, this->LeftTitle); this->LeftTitle->show(); } emit this->newAxisTitle(axis, this->LeftTitle); } } else if(axis == vtkQtChartAxis::Top) { if(this->TopTitle != title) { if(this->TopTitle) { this->TopTitle->hide(); this->TopLayout->removeWidget(this->TopTitle); } this->TopTitle = title; if(this->TopTitle) { this->TopTitle->setParent(this); this->TopTitle->setOrientation(Qt::Horizontal); this->TopLayout->insertWidget(0, this->TopTitle); this->TopTitle->show(); } emit this->newAxisTitle(axis, this->TopTitle); } } else if(axis == vtkQtChartAxis::Right) { if(this->RightTitle != title) { if(this->RightTitle) { this->RightTitle->hide(); this->ChartLayout->removeWidget(this->RightTitle); } this->RightTitle = title; if(this->RightTitle) { this->RightTitle->setParent(this); this->RightTitle->setOrientation(Qt::Vertical); this->ChartLayout->addWidget(this->RightTitle); this->RightTitle->show(); } emit this->newAxisTitle(axis, this->RightTitle); } } else if(this->BottomTitle != title) { if(this->BottomTitle) { this->BottomTitle->hide(); this->TopLayout->removeWidget(this->BottomTitle); } this->BottomTitle = title; if(this->BottomTitle) { this->BottomTitle->setParent(this); this->BottomTitle->setOrientation(Qt::Horizontal); this->TopLayout->addWidget(this->BottomTitle); this->BottomTitle->show(); } emit this->newAxisTitle(axis, this->BottomTitle); } } QSize vtkQtChartWidget::sizeHint() const { this->ensurePolished(); return QSize(150, 150); } void vtkQtChartWidget::printChart(QPrinter &printer) { // Set up the painter for the printer. QSize viewportSize = this->size(); viewportSize.scale(printer.pageRect().size(), Qt::KeepAspectRatio); QPainter painter(&printer); painter.setWindow(this->rect()); painter.setViewport(QRect(QPoint(0, 0), viewportSize)); // Print each of the child components. if(this->Title) { painter.save(); painter.translate(this->Title->mapToParent(QPoint(0, 0))); this->Title->drawTitle(painter); painter.restore(); } if(this->Legend) { painter.save(); painter.translate(this->Legend->mapToParent(QPoint(0, 0))); this->Legend->drawLegend(painter); painter.restore(); } if(this->LeftTitle) { painter.save(); painter.translate(this->LeftTitle->mapToParent(QPoint(0, 0))); this->LeftTitle->drawTitle(painter); painter.restore(); } if(this->TopTitle) { painter.save(); painter.translate(this->TopTitle->mapToParent(QPoint(0, 0))); this->TopTitle->drawTitle(painter); painter.restore(); } if(this->RightTitle) { painter.save(); painter.translate(this->RightTitle->mapToParent(QPoint(0, 0))); this->RightTitle->drawTitle(painter); painter.restore(); } if(this->BottomTitle) { painter.save(); painter.translate(this->BottomTitle->mapToParent(QPoint(0, 0))); this->BottomTitle->drawTitle(painter); painter.restore(); } painter.translate(this->Charts->mapToParent(QPoint(0, 0))); this->Charts->render(&painter, this->Charts->rect()); } void vtkQtChartWidget::saveChart(const QStringList &files) { QStringList::ConstIterator iter = files.begin(); for( ; iter != files.end(); ++iter) { this->saveChart(*iter); } } void vtkQtChartWidget::saveChart(const QString &filename) { if(filename.endsWith(".pdf", Qt::CaseInsensitive)) { QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(filename); this->printChart(printer); } else { QPixmap grab = QPixmap::grabWidget(this); grab.save(filename); } } void vtkQtChartWidget::changeLegendLocation() { // Remove the legend from its current location. this->LegendLayout->removeWidget(this->Legend); // Put the legend back in the appropriate spot. if(this->Legend->getLocation() == vtkQtChartLegend::Left) { this->LegendLayout->addWidget(this->Legend, 1, 0); } else if(this->Legend->getLocation() == vtkQtChartLegend::Top) { this->LegendLayout->addWidget(this->Legend, 0, 1); } else if(this->Legend->getLocation() == vtkQtChartLegend::Right) { this->LegendLayout->addWidget(this->Legend, 1, 2); } else if(this->Legend->getLocation() == vtkQtChartLegend::Bottom) { this->LegendLayout->addWidget(this->Legend, 3, 1); } } <|endoftext|>
<commit_before>/* * SDL Hello World example for Gui-chan */ // Include all necessary headers. #include <iostream> #include <guichan.hpp> #include <guichan/sdl.hpp> #include <SDL/SDL.h> /* * Common stuff we need */ bool running = true; /* *SDL Stuff we need */ SDL_Surface* screen; SDL_Event event; /* * Gui-chan SDL stuff we need */ gcn::SDLInput* input; // Input driver gcn::SDLGraphics* graphics; // Graphics driver /* * Gui-chan stuff we need */ gcn::ImageLoader* imageLoader; // For loading images gcn::Gui* gui; // A Gui object gcn::Container* top; // A top container gcn::ImageFont* font; // A font gcn::Label* label; // And a label for the Hello World text /** * Initializes the Hello World */ void init() { /* * Here we initialize SDL as we would do with any SDL application. */ SDL_Init(SDL_INIT_VIDEO); screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE); // We want unicode SDL_EnableUNICODE(1); // We want to enable key repeat SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); /* * Now it's time for Gui-chan SDL stuff */ gcn::ImageLoader* imageLoader = new gcn::SDLImageLoader(); // The ImageLoader in use is static and must be set to be // able to load images gcn::Image::setImageLoader(imageLoader); graphics = new gcn::SDLGraphics(); // Set the target for the graphics object to be the screen. // In other words, we will draw to the screen. // Note, any surface will do, it doesn't have to be the screen. graphics->setTarget(screen); input = new gcn::SDLInput(); /* * Last but not least it's time to initialize and create the gui * with Gui-chan stuff. */ top = new gcn::Container(); // Set the dimension of the top container to match the screen. top->setDimension(gcn::Rectangle(0, 0, 640, 480)); gui = new gcn::Gui(); // Set gui to use the SDLGraphics object. gui->setGraphics(graphics); // Set gui to use the SDLInput object gui->setInput(input); // Set the top container gui->setTop(top); // Load the image font. font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); // The global font is static and must be set. gcn::Widget::setGlobalFont(font); // Create a label with test hello world label = new gcn::Label("Hello World"); // Set the labels position label->setPosition(280, 220); // Add the label to the top container top->add(label); } /** * Halts the application */ void halt() { /* * Destroy Gui-chan stuff */ delete label; delete font; delete top; delete gui; /* * Destroy Gui-chan SDL stuff */ delete input; delete graphics; delete imageLoader; /* * Destroy SDL stuff */ SDL_FreeSurface(screen); SDL_Quit(); } /** * Checks input. On escape halt the application. */ void checkInput() { /* * Poll SDL events */ while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { running = false; } if (event.key.keysym.sym == SDLK_f) { if (event.key.keysym.mod & KMOD_CTRL) { // Works with X11 only SDL_WM_ToggleFullScreen(screen); } } } else if(event.type == SDL_QUIT) { running = false; } /* * Now that we are done polling and using SDL events we pass * the leftovers to the SDLInput object to later be handled by * the Gui. (This example doesn't require us to do this 'cause a * label doesn't use input. But will do it anyway to show how to * set up an SDL application with Gui-chan.) */ input->pushInput(event); } } /** * Runs the application */ void run() { while(running) { // Poll input checkInput(); // Let the gui perform it's logic (like handle input) gui->logic(); // Draw the gui gui->draw(); // Update the screen SDL_Flip(screen); } } int main(int argc, char **argv) { try { init(); run(); halt(); } /* * Catch all Gui-chan exceptions */ catch (gcn::Exception e) { std::cout << e.getMessage() << std::endl; } /* * Catch all Std exceptions */ catch (std::exception e) { std::cout << "Std exception: " << e.what() << std::endl; } /* * Catch all Unknown exceptions */ catch (...) { std::cout << "Unknown exception" << std::endl; } return 0; } <commit_msg>Added a comment finalman found more appropriate (he always always has to complain about something...)<commit_after>/* * SDL Hello World example for Gui-chan */ // Include all necessary headers. #include <iostream> #include <guichan.hpp> #include <guichan/sdl.hpp> #include <SDL/SDL.h> /* * Common stuff we need */ bool running = true; /* *SDL Stuff we need */ SDL_Surface* screen; SDL_Event event; /* * Gui-chan SDL stuff we need */ gcn::SDLInput* input; // Input driver gcn::SDLGraphics* graphics; // Graphics driver /* * Gui-chan stuff we need */ gcn::ImageLoader* imageLoader; // For loading images gcn::Gui* gui; // A Gui object - binds it all together gcn::Container* top; // A top container gcn::ImageFont* font; // A font gcn::Label* label; // And a label for the Hello World text /** * Initializes the Hello World */ void init() { /* * Here we initialize SDL as we would do with any SDL application. */ SDL_Init(SDL_INIT_VIDEO); screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE); // We want unicode SDL_EnableUNICODE(1); // We want to enable key repeat SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); /* * Now it's time for Gui-chan SDL stuff */ gcn::ImageLoader* imageLoader = new gcn::SDLImageLoader(); // The ImageLoader in use is static and must be set to be // able to load images gcn::Image::setImageLoader(imageLoader); graphics = new gcn::SDLGraphics(); // Set the target for the graphics object to be the screen. // In other words, we will draw to the screen. // Note, any surface will do, it doesn't have to be the screen. graphics->setTarget(screen); input = new gcn::SDLInput(); /* * Last but not least it's time to initialize and create the gui * with Gui-chan stuff. */ top = new gcn::Container(); // Set the dimension of the top container to match the screen. top->setDimension(gcn::Rectangle(0, 0, 640, 480)); gui = new gcn::Gui(); // Set gui to use the SDLGraphics object. gui->setGraphics(graphics); // Set gui to use the SDLInput object gui->setInput(input); // Set the top container gui->setTop(top); // Load the image font. font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); // The global font is static and must be set. gcn::Widget::setGlobalFont(font); // Create a label with test hello world label = new gcn::Label("Hello World"); // Set the labels position label->setPosition(280, 220); // Add the label to the top container top->add(label); } /** * Halts the application */ void halt() { /* * Destroy Gui-chan stuff */ delete label; delete font; delete top; delete gui; /* * Destroy Gui-chan SDL stuff */ delete input; delete graphics; delete imageLoader; /* * Destroy SDL stuff */ SDL_FreeSurface(screen); SDL_Quit(); } /** * Checks input. On escape halt the application. */ void checkInput() { /* * Poll SDL events */ while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { running = false; } if (event.key.keysym.sym == SDLK_f) { if (event.key.keysym.mod & KMOD_CTRL) { // Works with X11 only SDL_WM_ToggleFullScreen(screen); } } } else if(event.type == SDL_QUIT) { running = false; } /* * Now that we are done polling and using SDL events we pass * the leftovers to the SDLInput object to later be handled by * the Gui. (This example doesn't require us to do this 'cause a * label doesn't use input. But will do it anyway to show how to * set up an SDL application with Gui-chan.) */ input->pushInput(event); } } /** * Runs the application */ void run() { while(running) { // Poll input checkInput(); // Let the gui perform it's logic (like handle input) gui->logic(); // Draw the gui gui->draw(); // Update the screen SDL_Flip(screen); } } int main(int argc, char **argv) { try { init(); run(); halt(); } /* * Catch all Gui-chan exceptions */ catch (gcn::Exception e) { std::cout << e.getMessage() << std::endl; } /* * Catch all Std exceptions */ catch (std::exception e) { std::cout << "Std exception: " << e.what() << std::endl; } /* * Catch all Unknown exceptions */ catch (...) { std::cout << "Unknown exception" << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mainWindow; mainWindow.show(); return app.exec(); } <commit_msg>Added Qt version check.<commit_after>#include <QApplication> #include <QMessageBox> #include "MainWindow.h" int main(int argc, char *argv[]) { QT_REQUIRE_VERSION(argc, argv, "4.7.0") QApplication app(argc, argv); MainWindow mainWindow; mainWindow.show(); return app.exec(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_tor.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _P9_TOR_H_ #define _P9_TOR_H_ #include "p9_ring_identification.H" #include "p9_ringId.H" #include "p9_infrastruct_help.H" #define NUM_RING_IDS P9_NUM_RINGS typedef struct { uint32_t sizeOfThis; uint16_t sizeOfCmsk; uint16_t sizeOfMeta; // Exact size of meta data. Arbitrary size. Not null terminated. } RingLayout_t; // // Temporary define until in TOR header by Giri. // // // Temporary define until in TOR header by Giri. // typedef struct { uint32_t TorNumDdLevels; uint32_t reserved; } TorNumDdLevels_t; typedef struct { uint32_t TorDdLevelAndOffset; uint32_t TorDdBlockSize; } TorDdLevelBlock_t; typedef struct { uint32_t TorPpeTypeOffset; uint32_t TorPpeBlockSize; } TorPpeBlock_t; #define MAX_CPLT_SBE 13 #define IMGBUILD_TGR_RING_FOUND 0 #define IMGBUILD_TGR_RING_BLOCKS_FOUND 0 #define IMGBUILD_TGR_RING_NOT_FOUND 1 // Ring is not found in HW image. #define IMGBUILD_TGR_INVALID_RING_ID 2 // Ring is invalid or mismatch. #define IMGBUILD_TGR_AMBIGUOUS_API_PARMS 3 // Ring search in HW iamge got ambiguous condition. #define IMGBUILD_TGR_SECTION_NOT_FOUND 4 #define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND 5 #define IMGBUILD_TGR_OP_BUFFER_INVALID 6 #define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED 7 #define IMGBUILD_INVALID_INSTANCEID 8 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME 10 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE 11 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL 12 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13 #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_) extern const char* ringVariantName[]; extern const char* ppeTypeName[]; typedef enum RingBlockType // Different options to extract data using tor_get_ring API { SINGLE_RING = 0x00, DD_LEVEL_RINGS = 0x01, PPE_LEVEL_RINGS = 0x02, CPLT_LEVEL_RINGS = 0x03 } RingBlockType_t; typedef enum RingType // Different type of Rings { COMMON = 0x00, INSTANCE = 0x01, ALLRING = 0x02 } RingType_t; typedef enum RingVariant // Base variables { BASE = 0x00, CC = 0x01, RL = 0x02, OVERRIDE = 0x03, OVERLAY = 0x04, NUM_RING_VARIANTS = 0x05 } RingVariant_t; // // PPE types // typedef enum PpeType { SBE = 0x00, // Ppe type partition in Ringsection CME = 0x01, SGPE = 0x02, NUM_PPE_TYPES = 0x03 } PpeType_t; typedef enum RingSectionId { SECTION_RING = 0x00, //.ring section ID SECTION_OVRD = 0x01, //.Override section ID SECTION_OVRL = 0x02 //.Overlay section ID } RingSectionId_t; typedef enum SbeTorId { PERV_CPLT = 0, N0_CPLT = 1, N1_CPLT = 2, N2_CPLT = 3, N3_CPLT = 4, XB_CPLT = 5, MC_CPLT = 6, OB_CPLT = 7, PCI0_CPLT = 8, PCI1_CPLT = 9, PCI2_CPLT = 10, EQ_CPLT = 11, EC_CPLT = 12, SBEALL = 13 } SbeTorId_t; typedef enum CmeTorId { CME0_CPLT = 0, CME1_CPLT = 1, CME2_CPLT = 2, CME3_CPLT = 3, CME4_CPLT = 4, CME5_CPLT = 5, CME6_CPLT = 6, CME7_CPLT = 7, CME8_CPLT = 8, CME9_CPLT = 9, CME10_CPLT = 10, CME11_CPLT = 11, CMEALL = 12 } CmeTorId_t; /// /// **************************************************************************** /// Function declares. /// **************************************************************************** /// int get_ring_from_sbe_image ( void* i_ringSectionPtr, // Image pointer uint64_t i_magic, // Image Magic Number RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int get_ring_from_sgpe_image ( void* i_ringSectionPtr, // Image pointer RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int get_ring_from_cme_image ( void* i_ringSectionPtr, // Image pointer RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int tor_get_ring( void* i_ringSectionPtr, // Ring address Ptr any of .rings, .overrides and .overlays. uint64_t i_magic, // Image Magic Number RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level info PpeType_t i_PpeType, // PPE type : SBE, CME, etc RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, Cache etc uint8_t& io_instanceId, // chiplet instance ID RingBlockType_t i_RingBlockType, // 0: single ring, 1: ring block void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize, // size of ring data char* o_ringName // Ring name ); int tor_get_single_ring ( void* i_ringSectionPt, // Ring address Ptr any of .rings, .overrides and .overlays. uint16_t i_ddLevel, // DD level info RingID i_ringId, // Unique ring ID PpeType_t i_PpeType, // ppe Type RingVariant_t i_RingVariant, // Base, cache contained, Risk level, Override and Overlay uint8_t i_instanceId, // Chiplet Instance ID void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize ); // size of ring data int tor_get_block_of_rings ( void* i_ringSectionPt, // Ring address Ptr any of .rings, .overrides and .overlays. uint16_t i_ddLevel, // DD level PpeType_t i_PpeType, // ppe Type RingType_t i_RingType, // Common Or Instance RingVariant_t i_RingVariant, // base,cache,etc uint8_t i_instanceId, // Chiplet Instance ID void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize // size of ring data ); #endif //_P9_TOR_H_ <commit_msg>Add P9_TOR namespace to avoid naming collisions<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_tor.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _P9_TOR_H_ #define _P9_TOR_H_ #include "p9_ring_identification.H" #include "p9_ringId.H" #include "p9_infrastruct_help.H" namespace P9_TOR { #define NUM_RING_IDS P9_NUM_RINGS typedef struct { uint32_t sizeOfThis; uint16_t sizeOfCmsk; uint16_t sizeOfMeta; // Exact size of meta data. Arbitrary size. Not null terminated. } RingLayout_t; // // Temporary define until in TOR header by Giri. // // // Temporary define until in TOR header by Giri. // typedef struct { uint32_t TorNumDdLevels; uint32_t reserved; } TorNumDdLevels_t; typedef struct { uint32_t TorDdLevelAndOffset; uint32_t TorDdBlockSize; } TorDdLevelBlock_t; typedef struct { uint32_t TorPpeTypeOffset; uint32_t TorPpeBlockSize; } TorPpeBlock_t; #define MAX_CPLT_SBE 13 #define IMGBUILD_TGR_RING_FOUND 0 #define IMGBUILD_TGR_RING_BLOCKS_FOUND 0 #define IMGBUILD_TGR_RING_NOT_FOUND 1 // Ring is not found in HW image. #define IMGBUILD_TGR_INVALID_RING_ID 2 // Ring is invalid or mismatch. #define IMGBUILD_TGR_AMBIGUOUS_API_PARMS 3 // Ring search in HW iamge got ambiguous condition. #define IMGBUILD_TGR_SECTION_NOT_FOUND 4 #define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND 5 #define IMGBUILD_TGR_OP_BUFFER_INVALID 6 #define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED 7 #define IMGBUILD_INVALID_INSTANCEID 8 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME 10 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE 11 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL 12 #define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13 #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_) extern const char* ringVariantName[]; extern const char* ppeTypeName[]; typedef enum RingBlockType // Different options to extract data using tor_get_ring API { SINGLE_RING = 0x00, DD_LEVEL_RINGS = 0x01, PPE_LEVEL_RINGS = 0x02, CPLT_LEVEL_RINGS = 0x03 } RingBlockType_t; typedef enum RingType // Different type of Rings { COMMON = 0x00, INSTANCE = 0x01, ALLRING = 0x02 } RingType_t; typedef enum RingVariant // Base variables { BASE = 0x00, CC = 0x01, RL = 0x02, OVERRIDE = 0x03, OVERLAY = 0x04, NUM_RING_VARIANTS = 0x05 } RingVariant_t; // // PPE types // typedef enum PpeType { SBE = 0x00, // Ppe type partition in Ringsection CME = 0x01, SGPE = 0x02, NUM_PPE_TYPES = 0x03 } PpeType_t; typedef enum RingSectionId { SECTION_RING = 0x00, //.ring section ID SECTION_OVRD = 0x01, //.Override section ID SECTION_OVRL = 0x02 //.Overlay section ID } RingSectionId_t; typedef enum SbeTorId { PERV_CPLT = 0, N0_CPLT = 1, N1_CPLT = 2, N2_CPLT = 3, N3_CPLT = 4, XB_CPLT = 5, MC_CPLT = 6, OB_CPLT = 7, PCI0_CPLT = 8, PCI1_CPLT = 9, PCI2_CPLT = 10, EQ_CPLT = 11, EC_CPLT = 12, SBEALL = 13 } SbeTorId_t; typedef enum CmeTorId { CME0_CPLT = 0, CME1_CPLT = 1, CME2_CPLT = 2, CME3_CPLT = 3, CME4_CPLT = 4, CME5_CPLT = 5, CME6_CPLT = 6, CME7_CPLT = 7, CME8_CPLT = 8, CME9_CPLT = 9, CME10_CPLT = 10, CME11_CPLT = 11, CMEALL = 12 } CmeTorId_t; /// /// **************************************************************************** /// Function declares. /// **************************************************************************** /// int get_ring_from_sbe_image ( void* i_ringSectionPtr, // Image pointer uint64_t i_magic, // Image Magic Number RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int get_ring_from_sgpe_image ( void* i_ringSectionPtr, // Image pointer RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int get_ring_from_cme_image ( void* i_ringSectionPtr, // Image pointer RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level details RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, cache contained, Risk level, // Override and Overlay uint8_t& io_instanceId, // required Instance RingBlockType_t RingBlockType, // 0: single ring, 1: ddLevel block void** io_ringBlockPtr, // RS4 Container data or block data uint32_t& io_ringBlockSize, // size of data copied into ring block pointer char* o_ringName, // Name of ring uint32_t dbgl); // Debug option int tor_get_ring( void* i_ringSectionPtr, // Ring address Ptr any of .rings, .overrides and .overlays. uint64_t i_magic, // Image Magic Number RingID i_ringId, // Unique ring ID uint16_t i_ddLevel, // DD level info PpeType_t i_PpeType, // PPE type : SBE, CME, etc RingType_t& io_RingType, // 0: Common 1: Instance RingVariant_t i_RingVariant, // Base, Cache etc uint8_t& io_instanceId, // chiplet instance ID RingBlockType_t i_RingBlockType, // 0: single ring, 1: ring block void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize, // size of ring data char* o_ringName // Ring name ); int tor_get_single_ring ( void* i_ringSectionPt, // Ring address Ptr any of .rings, .overrides and .overlays. uint16_t i_ddLevel, // DD level info RingID i_ringId, // Unique ring ID PpeType_t i_PpeType, // ppe Type RingVariant_t i_RingVariant, // Base, cache contained, Risk level, Override and Overlay uint8_t i_instanceId, // Chiplet Instance ID void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize ); // size of ring data int tor_get_block_of_rings ( void* i_ringSectionPt, // Ring address Ptr any of .rings, .overrides and .overlays. uint16_t i_ddLevel, // DD level PpeType_t i_PpeType, // ppe Type RingType_t i_RingType, // Common Or Instance RingVariant_t i_RingVariant, // base,cache,etc uint8_t i_instanceId, // Chiplet Instance ID void** io_ringBlockPtr, // Addr of ring buffer uint32_t& io_ringBlockSize // size of ring data ); }; #endif //_P9_TOR_H_ <|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <thread> char field[20][40]; struct point { int x = 0, y = 0; } start, dest, current, goal; int main() { //sramim se. int q, e, r, t, steps; std::cout << "Unesite a.x, a.y, b.x, b.y s razmacima izmedu brojeva (a 0-19, b 0-39): "; std::cin >> q >> e >> r >> t; //sanitize input?? start = { q,e }; dest = { r,t }; current = start; field[5][1] = '*'; field[5][2] = '*'; field[5][3] = '*'; field[5][4] = '*'; for(;;) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); system("CLS"); if (current.x != goal.x && field[current.x + 1][current.y] != '*') current.x++; else if (current.y != goal.y && field[current.x][current.y + 1] != '*') current.y++; steps++; for (int i = 0; i < 20; ++i) {//fill array for (int j = 0; j < 40; ++j) { if (field[i][j] == 'B') goal = { i,j }; if (i == start.x && j == start.y) field[i][j] = 'A'; else if (i == dest.x && j == dest.y) field[i][j] = 'B'; else if (i == 0 || j == 0 || i == 19 || j == 39) field[i][j] = '*'; else { if (field[i][j] != 'x' && field[i][j] != '*') field[i][j] = '-'; field[current.x][current.y] = 'x'; } } } for (int i = 0; i < 20; ++i) { for (int j = 0; j < 40; ++j) std::cout << field[i][j]; std::cout << "\n"; } if (current.x == goal.x && current.y == goal.y) break; } std::cout << "done in: " << steps << " steps." << "\n"; return 0; } <commit_msg>Update Source.cpp<commit_after>#include <iostream> #include <chrono> #include <thread> char field[20][40]; int q, e, r, t, steps; struct point { int x = 0, y = 0; } start, dest, atm, goal; int main() { //sramim se. std::cout << "Unesite a.x, a.y, b.x, b.y s razmacima izmedu brojeva (a 0-19, b 0-39): "; std::cin >> q >> e >> r >> t; //sanitize input?? start = { q,e }, dest = { r,t }, atm = start; field[5][1] = '*'; field[5][2] = '*'; field[5][3] = '*'; field[5][4] = '*'; while (!(atm.x == goal.x && atm.y == goal.y)) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); (atm.x != goal.x && field[atm.x + 1][atm.y] != '*') ? atm.x++ : (atm.y != goal.y && field[atm.x][atm.y + 1] != '*') ? atm.y++ : 0; system("CLS"); steps++; for (int i = 0; i < 20; ++i) {//fill array for (int j = 0; j < 40; ++j) { if (field[i][j] == 'B') goal = { i,j }; if (i == start.x && j == start.y) field[i][j] = 'A'; else if (i == dest.x && j == dest.y) field[i][j] = 'B'; else if (i == 0 || j == 0 || i == 19 || j == 39) field[i][j] = '*'; else { if (field[i][j] != 'x' && field[i][j] != '*') field[i][j] = '-'; field[atm.x][atm.y] = 'x'; } std::cout << field[i][j]; } std::cout << "\n"; } } std::cout << "done in: " << steps << " steps." << "\n"; return 0; } <|endoftext|>
<commit_before>//penser à garder la racine qqpart //demander si besoin de regex std::map<std::string, Xsl::Instruction*> xslInstructions; Xml::Document xslTransform(Xml::Document& xmlDoc, Xml::Document& xslDoc ) { Xml::Document result = new Xml::Document(); Vector <Xml::Node*> resultNodes; applyDefaultTemplate(xmlDoc.root(), resultNodes); if (resultNodes.size() == 1) { result.setRoot(resultNodes[0]); return result; } else { throw Exception(); } } Vector <Xml::Node*> applyDefaultTemplate(Xml::Node* context, Vector<Node*> resultNodes) { // TODO : faire ça autrement... if (isinstance(context, Text)) { return [context]; } for (auto child : context.children()) { Xsl::Element xslTemplate = this.getTemplate(child); applyTemplate(xslTemplate, child, resultNodes); } return resultNodes; } Vector <Xml::Node*> applyTemplate (const Xml::Element& xslTemplate, const Xml::Node* context, Vector<Node*> resultNodes) { if (xslTemplate == null) { return applyDefaultTemplate(context, resultNodes); } // Attention, ici on parcours des éléments XSL, et pas le document XML qu'on transforme for (auto node : xslTemplate.children()) { if (node.iselement() && node.namespace() != 'xsl') { resultNodes.push(node); } else { xslInstructions[node->name()]->(context, node, resultNodes); } } } void Xsl::ValueOf::operator () (Xml::Node* context, Xml::Element xslElement, Vector <Xml::Node*> resultNodes) { resultNodes.push(context.select(xslElement.attr('select').text())); }<commit_msg>push of pseudo code xsl<commit_after>#include <"" std::map<std::string, Xsl::Instruction*> xslInstructions; Xml::Document xslTransform(Xml::Document& xmlDoc, Xml::Document& xslDoc ) { Xml::Document result = new Xml::Document(); Vector <Xml::Node*> resultNodes; applyDefaultTemplate(xmlDoc.root(), resultNodes); if (resultNodes.size() == 1) { result.setRoot(resultNodes[0]); return result; } else { throw Exception(); } } void applyDefaultTemplate(Xml::Node* context, Vector<Node*> resultNodes) { // TODO : faire ça autrement... if (isinstance(context, Text)) { resultNodes.push(context); } for (auto child : context.children()) { Xsl::Element xslTemplate = this.getTemplate(child); if (xslTemplate == null) { applyDefaultTemplate(context, resultNodes); return ; } else{ applyTemplate(xslTemplate, child, resultNodes); return ; } } } void applyTemplate (const Xml::Element& xslTemplate, const Xml::Node* context, Vector<Node*> resultNodes) { // Attention, ici on parcours des éléments XSL, et pas le document XML qu'on transforme for (auto node : xslTemplate.children()) { if (node.iselement() && node.namespace() != 'xsl') { resultNodes.push(node); } else { xslInstructions[node->name()]->(context, node, resultNodes); } } } void Xsl::ValueOf::operator () (Xml::Node* context, Xml::Element valueOfElement, Vector <Xml::Node*> resultNodes) { resultNodes.push(context.select(valueOfElement.attr('select').text())); } void Xsl::ForEach::operator () (Xml::Node* context, Xml::Element forEachElement, Vector <Xml::Node*> resultNodes) { Vector <Xml::Node*> matchingNodes = context.select(forEachElement.attr('select')); for (auto node : matchingNodes) { applyTemplate(forEachElement, node, resultNodes); } } void Xsl::ApplyTemplate::operator () (Xml::Node* context, Xml::Element applyTemplatehElement, Vector <Xml::Node*> resultNodes) { Vector <Xml::Node*> matchingNodes = context.select(forEachElement.attr('select')); for (auto node ; matchingNodes){ Xsl::Element xslTemplate = DOCUMENT.getTemplate(node); applyTemplate(xslTemplate, node, resultNodes) } }<|endoftext|>
<commit_before>#include <stingray/toolkit/Factory.h> #include <stingray/toolkit/any.h> #include <stingray/app/PushVideoOnDemand.h> #include <stingray/app/application_context/AppChannel.h> #include <stingray/app/application_context/ChannelList.h> #include <stingray/app/scheduler/ScheduledEvents.h> #include <stingray/app/tests/AutoFilter.h> #include <stingray/app/zapper/User.h> #include <stingray/ca/BasicSubscription.h> #include <stingray/crypto/PlainCipherKey.h> #include <stingray/hdmi/IHDMI.h> #include <stingray/media/ImageFileMediaData.h> #include <stingray/media/MediaInfoBase.h> #include <stingray/media/Mp3MediaInfo.h> #include <stingray/media/formats/flv/MediaInfo.h> #include <stingray/media/formats/mp4/MediaInfo.h> #include <stingray/media/formats/mp4/Stream.h> #include <stingray/media/formats/mp4/StreamDescriptors.h> #include <stingray/mpeg/Stream.h> #include <stingray/net/DHCPInterfaceConfiguration.h> #include <stingray/net/IgnoredInterfaceConfiguration.h> #include <stingray/net/LinkLocalInterfaceConfiguration.h> #include <stingray/net/ManualInterfaceConfiguration.h> #include <stingray/parentalcontrol/AgeRating.h> #ifdef PLATFORM_EMU # include <stingray/platform/emu/scanner/Channel.h> #endif #ifdef PLATFORM_MSTAR # include <stingray/platform/mstar/crypto/HardwareCipherKey.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/Certificate.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/EvpKey.h> #endif #ifdef PLATFORM_STAPI # include <stingray/platform/stapi/crypto/HardwareCipherKey.h> #endif #include <stingray/records/FileSystemRecord.h> #include <stingray/rpc/UrlObjectId.h> #include <stingray/scanner/DVBServiceId.h> #include <stingray/scanner/DefaultDVBTBandInfo.h> #include <stingray/scanner/DefaultMpegService.h> #include <stingray/scanner/DefaultMpegStreamDescriptor.h> #include <stingray/scanner/DefaultScanParams.h> #include <stingray/scanner/DreCasGeographicRegion.h> #include <stingray/scanner/LybidScanParams.h> #include <stingray/scanner/TerrestrialScanParams.h> #include <stingray/scanner/TricolorGeographicRegion.h> #include <stingray/scanner/TricolorScanParams.h> #include <stingray/scanner/lybid/LybidServiceMetaInfo.h> #include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h> #include <stingray/stats/ChannelViewingEventInfo.h> #include <stingray/streams/PlaybackStreamContent.h> #include <stingray/streams/RecordStreamContent.h> #include <stingray/streams/RecordStreamMetaInfo.h> #include <stingray/tuners/TunerState.h> #include <stingray/tuners/dvbs/Antenna.h> #include <stingray/tuners/dvbs/DefaultDVBSTransport.h> #include <stingray/tuners/dvbs/Satellite.h> #include <stingray/tuners/dvbt/DVBTTransport.h> #include <stingray/tuners/ip/TsOverIpTransport.h> #include <stingray/update/VersionRequirement.h> #include <stingray/update/system/EraseFlashPartition.h> #include <stingray/update/system/WriteFlashPartition.h> /* WARNING! This is autogenerated file, DO NOT EDIT! */ namespace stingray { namespace Detail { void Factory::RegisterTypes() { #ifdef BUILD_SHARED_LIB /*nothing*/ #else TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey); TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase); TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating); #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel); #endif #ifdef PLATFORM_MSTAR TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey); #endif #ifdef PLATFORM_STAPI TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey); #endif TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement); TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition); TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition); #endif } }} <commit_msg>update factory classes<commit_after>#include <stingray/toolkit/Factory.h> #include <stingray/toolkit/any.h> #include <stingray/app/PushVideoOnDemand.h> #include <stingray/app/application_context/AppChannel.h> #include <stingray/app/application_context/ChannelList.h> #include <stingray/app/scheduler/ScheduledEvents.h> #include <stingray/app/tests/AutoFilter.h> #include <stingray/app/zapper/User.h> #include <stingray/ca/BasicSubscription.h> #include <stingray/crypto/PlainCipherKey.h> #include <stingray/hdmi/IHDMI.h> #include <stingray/media/ImageFileMediaData.h> #include <stingray/media/MediaInfoBase.h> #include <stingray/media/Mp3MediaInfo.h> #include <stingray/media/formats/flv/MediaInfo.h> #include <stingray/media/formats/mp4/MediaInfo.h> #include <stingray/media/formats/mp4/Stream.h> #include <stingray/media/formats/mp4/StreamDescriptors.h> #include <stingray/mpeg/Stream.h> #include <stingray/net/DHCPInterfaceConfiguration.h> #include <stingray/net/IgnoredInterfaceConfiguration.h> #include <stingray/net/LinkLocalInterfaceConfiguration.h> #include <stingray/net/ManualInterfaceConfiguration.h> #include <stingray/parentalcontrol/AgeRating.h> #ifdef PLATFORM_EMU # include <stingray/platform/emu/scanner/Channel.h> #endif #ifdef PLATFORM_MSTAR # include <stingray/platform/mstar/crypto/HardwareCipherKey.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/Certificate.h> #endif #ifdef PLATFORM_OPENSSL # include <stingray/platform/openssl/crypto/EvpKey.h> #endif #ifdef PLATFORM_STAPI # include <stingray/platform/stapi/crypto/HardwareCipherKey.h> #endif #include <stingray/records/FileSystemRecord.h> #include <stingray/rpc/UrlObjectId.h> #include <stingray/scanner/DVBServiceId.h> #include <stingray/scanner/DefaultDVBTBandInfo.h> #include <stingray/scanner/DefaultMpegService.h> #include <stingray/scanner/DefaultMpegStreamDescriptor.h> #include <stingray/scanner/DefaultScanParams.h> #include <stingray/scanner/DreCasGeographicRegion.h> #include <stingray/scanner/LybidScanParams.h> #include <stingray/scanner/TerrestrialScanParams.h> #include <stingray/scanner/TricolorGeographicRegion.h> #include <stingray/scanner/TricolorScanParams.h> #include <stingray/scanner/lybid/LybidServiceMetaInfo.h> #include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h> #include <stingray/stats/ChannelViewingEventInfo.h> #include <stingray/streams/PlaybackStreamContent.h> #include <stingray/streams/RecordStreamContent.h> #include <stingray/streams/RecordStreamMetaInfo.h> #include <stingray/tuners/TunerState.h> #include <stingray/tuners/dvbs/Antenna.h> #include <stingray/tuners/dvbs/DefaultDVBSTransport.h> #include <stingray/tuners/dvbs/Satellite.h> #include <stingray/tuners/dvbt/DVBTTransport.h> #include <stingray/tuners/ip/TsOverIpTransport.h> #include <stingray/update/VersionRequirement.h> #include <stingray/update/system/CopyFile.h> #include <stingray/update/system/EraseFlashPartition.h> #include <stingray/update/system/MoveFile.h> #include <stingray/update/system/RemoveFile.h> #include <stingray/update/system/WriteFlashPartition.h> /* WARNING! This is autogenerated file, DO NOT EDIT! */ namespace stingray { namespace Detail { void Factory::RegisterTypes() { #ifdef BUILD_SHARED_LIB /*nothing*/ #else TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter); TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription); TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey); TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview); TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase); TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream); TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration); TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating); #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor); #endif #ifdef PLATFORM_EMU TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel); #endif #ifdef PLATFORM_MSTAR TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate); #endif #ifdef PLATFORM_OPENSSL TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey); #endif #ifdef PLATFORM_STAPI TOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey); #endif TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord); TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams); TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ChannelViewingEventInfo>); TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent); TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo); TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState); TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna); TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite); TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport); TOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement); TOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition); TOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile); TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition); #endif } }} <|endoftext|>
<commit_before>#include "GameDBSyncService.h" #include "Common/Servers/HandlerLocator.h" #include "Common/Servers/MessageBus.h" #include "Common/Servers/InternalEvents.h" #include "GameData/serialization_common.h" #include "GameDBSyncEvents.h" #include "Character.h" #include "GameData/chardata_serializers.h" #include "GameData/entitydata_serializers.h" #include "GameData/playerdata_definitions.h" #include "GameData/playerdata_serializers.h" #include "GameData/gui_serializers.h" #include "GameData/keybind_serializers.h" #include "GameData/clientoptions_serializers.h" bool GameDBSyncService::per_thread_setup() { //GameDbSyncContext &db_ctx(m_db_context.localData()); //bool result = db_ctx.loadAndConfigure(); bool result = true; if(!result) postGlobalEvent(new ServiceStatusMessage({"GameDbSyncService failed to load/configure",-1})); else postGlobalEvent(new ServiceStatusMessage({"GameDbSyncService loaded/configured",0})); return result; } void GameDBSyncService::dispatch(SEGSEvent *ev) { // We are servicing a request from message queue, using dispatchSync as a common processing point. // nullptr result means that the given message is one-way switch (ev->type()) { default: assert(false); break; } } void GameDBSyncService::set_db_handler(const uint8_t id) { m_db_handler = static_cast<GameDBSyncHandler*>( HandlerLocator::getGame_DB_Handler(id)); } void GameDBSyncService::on_update_timer(const ACE_Time_Value &tick_timer) { // unused at the moment... but this works similarly to World::update } void GameDBSyncService::on_destroy() { updateEntities(); } void GameDBSyncService::updateEntities() { ACE_Guard<ACE_Thread_Mutex> guard_buffer(ref_entity_mgr.getEntitiesMutex()); for(Entity * e : ref_entity_mgr.m_live_entlist) { // These are ordered based on how much data is sent depending on those flags if (e->m_db_store_flags & uint32_t(DbStoreFlags::Full)) { sendCharacterUpdateToHandler(e); continue; } // Full character update and PlayerData update encompass Gui, Options and Keybinds already // And so, we should just not check for the three below anymore if this is true if (e->m_db_store_flags & uint32_t(DbStoreFlags::PlayerData)) { sendPlayerUpdateToHandler(e); continue; } } } void GameDBSyncService::updateEntity(Entity* e) { if (e->m_db_store_flags & uint32_t(DbStoreFlags::Full)) sendCharacterUpdateToHandler(e); if (e->m_db_store_flags & uint32_t(DbStoreFlags::PlayerData)) sendPlayerUpdateToHandler(e); } void GameDBSyncService::sendPlayerUpdateToHandler(Entity* e) { QString cerealizedPlayerData; PlayerData playerData = PlayerData({ e->m_player->m_gui, e->m_player->m_keybinds, e->m_player->m_options }); serializeToQString(playerData, cerealizedPlayerData); PlayerUpdateMessage* msg = new PlayerUpdateMessage( PlayerUpdateData({ e->m_char->m_db_id, cerealizedPlayerData }), (uint64_t)1); m_db_handler->putq(msg); unmarkEntityForDbStore(e, DbStoreFlags::PlayerData); } void GameDBSyncService::sendCharacterUpdateToHandler(Entity* e) { QString cerealizedCharData, cerealizedEntityData, cerealizedPlayerData; PlayerData playerData = PlayerData({ e->m_player->m_gui, e->m_player->m_keybinds, e->m_player->m_options }); serializeToQString(e->m_char->m_char_data, cerealizedCharData); serializeToQString(e->m_entity_data, cerealizedEntityData); serializeToQString(playerData, cerealizedPlayerData); CharacterUpdateMessage* msg = new CharacterUpdateMessage( CharacterUpdateData({ e->m_char->getName(), // cerealized blobs cerealizedCharData, cerealizedEntityData, cerealizedPlayerData, // plain values e->m_char->getCurrentCostume()->m_body_type, e->m_char->getCurrentCostume()->m_height, e->m_char->getCurrentCostume()->m_physique, (uint32_t)e->m_supergroup.m_SG_id, e->m_char->m_db_id }), (uint64_t)1); m_db_handler->putq(msg); unmarkEntityForDbStore(e, DbStoreFlags::Full); } <commit_msg>A temporary solution to enable automatic updates (Doesn't check for flags)<commit_after>#include "GameDBSyncService.h" #include "Common/Servers/HandlerLocator.h" #include "Common/Servers/MessageBus.h" #include "Common/Servers/InternalEvents.h" #include "GameData/serialization_common.h" #include "GameDBSyncEvents.h" #include "Character.h" #include "GameData/chardata_serializers.h" #include "GameData/entitydata_serializers.h" #include "GameData/playerdata_definitions.h" #include "GameData/playerdata_serializers.h" #include "GameData/gui_serializers.h" #include "GameData/keybind_serializers.h" #include "GameData/clientoptions_serializers.h" bool GameDBSyncService::per_thread_setup() { //GameDbSyncContext &db_ctx(m_db_context.localData()); //bool result = db_ctx.loadAndConfigure(); bool result = true; if(!result) postGlobalEvent(new ServiceStatusMessage({"GameDbSyncService failed to load/configure",-1})); else postGlobalEvent(new ServiceStatusMessage({"GameDbSyncService loaded/configured",0})); return result; } void GameDBSyncService::dispatch(SEGSEvent *ev) { // We are servicing a request from message queue, using dispatchSync as a common processing point. // nullptr result means that the given message is one-way switch (ev->type()) { default: assert(false); break; } } void GameDBSyncService::set_db_handler(const uint8_t id) { m_db_handler = static_cast<GameDBSyncHandler*>( HandlerLocator::getGame_DB_Handler(id)); } void GameDBSyncService::on_update_timer(const ACE_Time_Value &tick_timer) { // unused at the moment... but this works similarly to World::update } void GameDBSyncService::on_destroy() { updateEntities(); } void GameDBSyncService::updateEntities() { ACE_Guard<ACE_Thread_Mutex> guard_buffer(ref_entity_mgr.getEntitiesMutex()); for(Entity * e : ref_entity_mgr.m_live_entlist) { sendCharacterUpdateToHandler(e); /* TODO: Set the flags for entities on other functions, like maybe World::updateEntity, etc etc * at the moment I will make a full update for the characters no matter what the flag it // These are ordered based on how much data is sent depending on those flags if (e->m_db_store_flags & uint32_t(DbStoreFlags::Full)) { sendCharacterUpdateToHandler(e); continue; } // Full character update and PlayerData update encompass Gui, Options and Keybinds already // And so, we should just not check for the three below anymore if this is true if (e->m_db_store_flags & uint32_t(DbStoreFlags::PlayerData)) { sendPlayerUpdateToHandler(e); continue; } */ } } void GameDBSyncService::updateEntity(Entity* e) { if (e->m_db_store_flags & uint32_t(DbStoreFlags::Full)) sendCharacterUpdateToHandler(e); if (e->m_db_store_flags & uint32_t(DbStoreFlags::PlayerData)) sendPlayerUpdateToHandler(e); } void GameDBSyncService::sendPlayerUpdateToHandler(Entity* e) { QString cerealizedPlayerData; PlayerData playerData = PlayerData({ e->m_player->m_gui, e->m_player->m_keybinds, e->m_player->m_options }); serializeToQString(playerData, cerealizedPlayerData); PlayerUpdateMessage* msg = new PlayerUpdateMessage( PlayerUpdateData({ e->m_char->m_db_id, cerealizedPlayerData }), (uint64_t)1); m_db_handler->putq(msg); unmarkEntityForDbStore(e, DbStoreFlags::PlayerData); } void GameDBSyncService::sendCharacterUpdateToHandler(Entity* e) { QString cerealizedCharData, cerealizedEntityData, cerealizedPlayerData; PlayerData playerData = PlayerData({ e->m_player->m_gui, e->m_player->m_keybinds, e->m_player->m_options }); serializeToQString(e->m_char->m_char_data, cerealizedCharData); serializeToQString(e->m_entity_data, cerealizedEntityData); serializeToQString(playerData, cerealizedPlayerData); CharacterUpdateMessage* msg = new CharacterUpdateMessage( CharacterUpdateData({ e->m_char->getName(), // cerealized blobs cerealizedCharData, cerealizedEntityData, cerealizedPlayerData, // plain values e->m_char->getCurrentCostume()->m_body_type, e->m_char->getCurrentCostume()->m_height, e->m_char->getCurrentCostume()->m_physique, (uint32_t)e->m_supergroup.m_SG_id, e->m_char->m_db_id }), (uint64_t)1); m_db_handler->putq(msg); unmarkEntityForDbStore(e, DbStoreFlags::Full); } <|endoftext|>
<commit_before>/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Application icoFoam Description Transient solver for incompressible, laminar flow of Newtonian fluids. \*---------------------------------------------------------------------------*/ # include "fvCFD.H" # include "pisoControl.H" # include "regionProperties.H" # include "turbulentTemperatureCoupledBaffleMixedFvPatchScalarField.H" # include "temperatureCoupledBase.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // int main(int argc, char *argv[]) { #include "setRootCase.H" #include "createTime.H" regionProperties rp(runTime); if (rp["fluid"].size() > 1) { cerr << "This solver currently doesn't " << "support more than one fluid region!!" << endl; exit(EXIT_FAILURE); } if (rp["solid"].size() > 1) { cerr << "This solver currently doesn't " << "support more than one fluid region!!" << endl; exit(EXIT_FAILURE); } # include "createRegionMeshes.H" # include "createSolverControls.H" # include "createParameters.H" # include "createRegionFields.H" # include "initContinuityErrs.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Info<< "\nCalculating dimensionless electric potential, ep\n" << endl; scalar initRes1 = 1.; int maxI = 0; while ((initRes1 > 5e-5) && (maxI < 10000)) { maxI ++; Info<< "Iteration = " << maxI << nl << endl; initRes1 = solve ( fvm::laplacian(epFluid) ).initialResidual(); solve ( fvm::laplacian(epSolid) ); } if (maxI == 1000000) { cerr << "Electric potential solver diverged!" << endl; exit(EXIT_FAILURE); } Info<< "\nCalculating dimensionless charge density, rhoc\n" << endl; initRes1 = 1.; maxI = 0; while ((initRes1 > 1e-7) && (maxI < 10000)) { maxI ++; Info<< "Iteration = " << maxI << nl << endl; solve ( fvm::laplacian(rhocSolid) ); initRes1 = solve ( fvm::laplacian(rhocFluid) == fvm::Sp(1. / (lambdaFluid * lambdaFluid * epsFluid), rhocFluid) ).initialResidual(); } if (maxI == 1000000) { cerr << "Charge Density solver diverged!" << endl; exit(EXIT_FAILURE); } volVectorField EFluid ( IOobject ( "EFluid", runTime.timeName(), fluidMesh, IOobject::NO_READ, IOobject::AUTO_WRITE ), - fvc::grad(epFluid) ); Info<< "\nCalculating time-independent force field\n" << endl; volVectorField fFluid ( IOobject ( "fFluid", runTime.timeName(), fluidMesh, IOobject::NO_READ, IOobject::AUTO_WRITE ), rhocMax * epMax * rhocFluid * EFluid / rhoFluid ); fvMesh &mesh = fluidMesh; volScalarField &p = pFluid; volVectorField &U = UFluid; dimensionedScalar &nu = nuFluid; Info<< "\nStarting time loop\n" << endl; while (runTime.loop()) { Info<< "Time = " << runTime.timeName() << nl << endl; #include "CourantNo.H" // Momentum predictor fvVectorMatrix UEqn ( fvm::ddt(U) + fvm::div(phi, U) - fvm::laplacian(nu, U) ); if (piso.momentumPredictor()) { Info << "Solve momentum predictor" << endl; solve ( UEqn == - fvc::grad(p) + fFluid * std::pow( std::sin(2 * M_PI * omega.value() * runTime.value()), 2) ); } // --- PISO loop while (piso.correct()) { volScalarField rAU(1.0/UEqn.A()); volVectorField HbyA("HbyA", U); HbyA = rAU*UEqn.H(); surfaceScalarField phiHbyA ( "phiHbyA", (fvc::interpolate(HbyA) & mesh.Sf()) + fvc::interpolate(rAU)*fvc::ddtCorr(U, phi) ); adjustPhi(phiHbyA, U, p); // Non-orthogonal pressure corrector loop while (piso.correctNonOrthogonal()) { // Pressure corrector fvScalarMatrix pEqn ( fvm::laplacian(rAU, p) == fvc::div(phiHbyA) ); pEqn.setReference(pRefCell, pRefValue); pEqn.solve(mesh.solver(p.select(piso.finalInnerIter()))); if (piso.finalNonOrthogonalIter()) { phi = phiHbyA - pEqn.flux(); } } #include "continuityErrs.H" U = HbyA - rAU*fvc::grad(p); U.correctBoundaryConditions(); } runTime.write(); Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s" << " ClockTime = " << runTime.elapsedClockTime() << " s" << nl << endl; } Info<< "End\n" << endl; return 0; } /* */ // ************************************************************************* // <commit_msg>update header comment information<commit_after>/*---------------------------------------------------------------------------*\ Application actuatorFoam Description Couple plasma actuator model (Suzen et. al, 2007) with PISO flow solver. This code needs to be compiled with OpenFOAM libraries. \*---------------------------------------------------------------------------*/ # include "fvCFD.H" # include "pisoControl.H" # include "regionProperties.H" # include "turbulentTemperatureCoupledBaffleMixedFvPatchScalarField.H" # include "temperatureCoupledBase.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // int main(int argc, char *argv[]) { #include "setRootCase.H" #include "createTime.H" regionProperties rp(runTime); if (rp["fluid"].size() > 1) { cerr << "This solver currently doesn't " << "support more than one fluid region!!" << endl; exit(EXIT_FAILURE); } if (rp["solid"].size() > 1) { cerr << "This solver currently doesn't " << "support more than one fluid region!!" << endl; exit(EXIT_FAILURE); } # include "createRegionMeshes.H" # include "createSolverControls.H" # include "createParameters.H" # include "createRegionFields.H" # include "initContinuityErrs.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Info<< "\nCalculating dimensionless electric potential, ep\n" << endl; scalar initRes1 = 1.; int maxI = 0; while ((initRes1 > 5e-5) && (maxI < 10000)) { maxI ++; Info<< "Iteration = " << maxI << nl << endl; initRes1 = solve ( fvm::laplacian(epFluid) ).initialResidual(); solve ( fvm::laplacian(epSolid) ); } if (maxI == 1000000) { cerr << "Electric potential solver diverged!" << endl; exit(EXIT_FAILURE); } Info<< "\nCalculating dimensionless charge density, rhoc\n" << endl; initRes1 = 1.; maxI = 0; while ((initRes1 > 1e-7) && (maxI < 10000)) { maxI ++; Info<< "Iteration = " << maxI << nl << endl; solve ( fvm::laplacian(rhocSolid) ); initRes1 = solve ( fvm::laplacian(rhocFluid) == fvm::Sp(1. / (lambdaFluid * lambdaFluid * epsFluid), rhocFluid) ).initialResidual(); } if (maxI == 1000000) { cerr << "Charge Density solver diverged!" << endl; exit(EXIT_FAILURE); } volVectorField EFluid ( IOobject ( "EFluid", runTime.timeName(), fluidMesh, IOobject::NO_READ, IOobject::AUTO_WRITE ), - fvc::grad(epFluid) ); Info<< "\nCalculating time-independent force field\n" << endl; volVectorField fFluid ( IOobject ( "fFluid", runTime.timeName(), fluidMesh, IOobject::NO_READ, IOobject::AUTO_WRITE ), rhocMax * epMax * rhocFluid * EFluid / rhoFluid ); fvMesh &mesh = fluidMesh; volScalarField &p = pFluid; volVectorField &U = UFluid; dimensionedScalar &nu = nuFluid; Info<< "\nStarting time loop\n" << endl; while (runTime.loop()) { Info<< "Time = " << runTime.timeName() << nl << endl; #include "CourantNo.H" // Momentum predictor fvVectorMatrix UEqn ( fvm::ddt(U) + fvm::div(phi, U) - fvm::laplacian(nu, U) ); if (piso.momentumPredictor()) { Info << "Solve momentum predictor" << endl; solve ( UEqn == - fvc::grad(p) + fFluid * std::pow( std::sin(2 * M_PI * omega.value() * runTime.value()), 2) ); } // --- PISO loop while (piso.correct()) { volScalarField rAU(1.0/UEqn.A()); volVectorField HbyA("HbyA", U); HbyA = rAU*UEqn.H(); surfaceScalarField phiHbyA ( "phiHbyA", (fvc::interpolate(HbyA) & mesh.Sf()) + fvc::interpolate(rAU)*fvc::ddtCorr(U, phi) ); adjustPhi(phiHbyA, U, p); // Non-orthogonal pressure corrector loop while (piso.correctNonOrthogonal()) { // Pressure corrector fvScalarMatrix pEqn ( fvm::laplacian(rAU, p) == fvc::div(phiHbyA) ); pEqn.setReference(pRefCell, pRefValue); pEqn.solve(mesh.solver(p.select(piso.finalInnerIter()))); if (piso.finalNonOrthogonalIter()) { phi = phiHbyA - pEqn.flux(); } } #include "continuityErrs.H" U = HbyA - rAU*fvc::grad(p); U.correctBoundaryConditions(); } runTime.write(); Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s" << " ClockTime = " << runTime.elapsedClockTime() << " s" << nl << endl; } Info<< "End\n" << endl; return 0; } /* */ // ************************************************************************* // <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mtoolbar.h" #include <MToolBar> #include <MToolBarView> #include <MApplication> #include <MApplicationWindow> #include <MButton> #include <MTextEdit> #include <MSlider> #include <MButtonGroup> #include <MWidgetAction> #include "mtoolbar_p.h" MApplication *app(NULL); // TODO: remove this when unneeded in MTextEdit's constructor MApplicationWindow *appWin(NULL); void Ut_MToolBar::init() { m_subject = new MToolBar(); } void Ut_MToolBar::cleanup() { delete m_subject; m_subject = 0; } void Ut_MToolBar::initTestCase() { static int argc = 1; static char *app_name[1] = { (char *) "./ut_mtoolbar" }; app = new MApplication(argc, app_name); appWin = new MApplicationWindow; } void Ut_MToolBar::cleanupTestCase() { delete appWin; delete app; } void Ut_MToolBar::testConstructor() { QVERIFY(m_subject); } void Ut_MToolBar::testConstructor2() { class InheritedMToolBar : public MToolBar { public: explicit InheritedMToolBar() : MToolBar(new MToolBarPrivate(),new MWidgetModel(),NULL) {}; }; //testing protected constructor: MToolBar(MToolBarPrivate *dd, MWidgetModel *model, QGraphicsItem *parent); InheritedMToolBar* inheritedMToolBar = new InheritedMToolBar(); QVERIFY(inheritedMToolBar); delete inheritedMToolBar; } void Ut_MToolBar::testDestructor() { MToolBar *toolbar = new MToolBar(); delete toolbar; } void Ut_MToolBar::testAddAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // return value action MAction *action; // test addAction(const QString &text) MAction *action0 = new MAction("TEXTONLY", m_subject); m_subject->addAction(action0); action = qobject_cast<MAction *>(m_subject->actions().at(0)); // must be one QVERIFY(m_subject->actions().count() == 1); QVERIFY(action == action0); QVERIFY(action->text() == "TEXTONLY"); // test addAction(const QString &icon, const QString &text) MAction *action1 = new MAction("Icon-list-view-on", "TEXT", m_subject); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action == action1); QVERIFY(action->iconID() == "Icon-list-view-on"); QVERIFY(action->text() == "TEXT"); testValue = false; senderAction = NULL; connect(action1, SIGNAL(triggered(bool)), this, SLOT(actionSlot(bool))); action1->trigger(); QVERIFY(testValue); QVERIFY(senderAction == action1); // test addAction(MAction* action) MAction *action2 = new MAction("Icon-time-line-on", "TEXT4", NULL); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 3); action = qobject_cast<MAction *>(m_subject->actions().at(2)); QVERIFY(action == action2); delete action2; } void Ut_MToolBar::testAddTextEditAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // test addAction(Text Edit) MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(0)); // must be one QVERIFY(m_subject->actions().count() == 1); QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(widgetAction->widget() == textEntry); } void Ut_MToolBar::testInsertAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //adding text edit MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); //first action, indx 0 //adding actions MAction *action0 = new MAction("action0", m_subject); m_subject->addAction(action0); //second action, indx 1 MAction *action1 = new MAction("action1", m_subject); m_subject->insertAction(action0, action1); //third action, indx1 -> action0 goes to indx 2 QVERIFY(m_subject->actions().count() == 3); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(0)); // getting indx 0 MAction *action = qobject_cast<MAction *>(m_subject->actions().at(1)); //getting indx 1 //veryfing: QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(action); QVERIFY(action == action1); action = qobject_cast<MAction *>(m_subject->actions().at(2)); //getting indx 2 QVERIFY(action); QVERIFY(action == action0); } void Ut_MToolBar::testActionVisiblity() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //adding actions: MAction *action0 = new MAction("action0", m_subject); m_subject->addAction(action0); //first action, indx 0 MAction *action1 = new MAction("action1", m_subject); m_subject->addAction(action1); //second action, indx 1 MAction *action2 = new MAction("action2", m_subject); m_subject->addAction(action2); //third action, indx 2 MAction *action3 = new MAction("action3", m_subject); m_subject->addAction(action3); //fourth action, indx 3 QVERIFY(m_subject->actions().count() == 4); MAction *action; //needed for veryfing action0->setVisible(false); action1->setVisible(false); QVERIFY(m_subject->actions().count() == 4); action = qobject_cast<MAction *>(m_subject->actions().at(0)); QVERIFY(action); QVERIFY(action == action0); QVERIFY(action->isVisible() == false); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action); QVERIFY(action == action1); QVERIFY(action->isVisible() == false); action = qobject_cast<MAction *>(m_subject->actions().at(2)); QVERIFY(action); QVERIFY(action == action2); QVERIFY(action->isVisible() == true); action = qobject_cast<MAction *>(m_subject->actions().at(3)); QVERIFY(action); QVERIFY(action == action3); QVERIFY(action->isVisible() == true); //text entry: MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(4)); QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(widgetAction->isVisible() == true); action0->setVisible(true); action = qobject_cast<MAction *>(m_subject->actions().at(0)); QVERIFY(action); QVERIFY(action == action0); QVERIFY(action->isVisible() == true); action1->setVisible(true); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action); QVERIFY(action == action1); QVERIFY(action->isVisible() == true); QVERIFY(widgetAction); QVERIFY(widgetAction->widget()->isVisible() == false); //visiblity should be changed, because there is no room for this anymore } void Ut_MToolBar::testAddTabAction() { m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); m_subject->setViewType(MToolBar::tabType); MAction *action0 = new MAction("action0", m_subject); action0->setLocation(MAction::ToolBarLandscapeLocation); action0->setCheckable(true); action0->setChecked(true); m_subject->addAction(action0); QVERIFY(m_subject->actions().count() == 1); MAction *action1 = new MAction("action1", m_subject); action1->setLocation(MAction::ToolBarPortraitLocation); action1->setCheckable(true); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); MAction *action2 = new MAction("action2", m_subject); action2->setLocation(MAction::ToolBarLocation); action2->setCheckable(true); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 3); } void Ut_MToolBar::testRemoveTabAction() { m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); m_subject->setViewType(MToolBar::tabType); MAction *action0 = new MAction("action0", m_subject); action0->setLocation(MAction::ToolBarLandscapeLocation); action0->setCheckable(true); action0->setChecked(true); m_subject->addAction(action0); QVERIFY(m_subject->actions().count() == 1); MAction *action1 = new MAction("action1", m_subject); action1->setLocation(MAction::ToolBarPortraitLocation); action1->setCheckable(true); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); m_subject->removeAction(action1); QVERIFY(m_subject->actions().count() == 1); MAction *action2 = new MAction("action2", m_subject); action2->setLocation(MAction::ToolBarLocation); action2->setCheckable(true); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 2); m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); } void Ut_MToolBar::actionSlot(bool) { senderAction = qobject_cast<MAction *>(sender()); testValue = true; } void Ut_MToolBar::testNoLocation() { //Add an action to everywhere and then change it to nowhere, to test that this does not crash etc m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //Add a normal action MAction *action0 = new MAction("action0", m_subject); action0->setCheckable(true); action0->setChecked(true); appWin->addAction(action0); //Add a widget action MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); appWin->addAction(actionTextEdit); QCOMPARE(action0->location(), MAction::EveryLocation); QCOMPARE(actionTextEdit->location(), MAction::EveryLocation); //Now remove both actions action0->setLocation(MAction::NoLocation); actionTextEdit->setLocation(MAction::NoLocation); } void Ut_MToolBar::testPropertyChange() { // Add an action then set the Property which is triggered by the AppMenu when it is opened and closed m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // Add a normal action MAction *action = new MAction("action", m_subject); action->setLocation(MAction::ToolBarLocation); action->setEnabled(true); action->setVisible(true); m_subject->addAction(action); // Retrieve the widget associated with the action const MToolBarView *view = dynamic_cast<const MToolBarView *>(m_subject->view()); QVERIFY(view); MWidget *widget = view->getWidget(action); QVERIFY(widget); QVERIFY(widget->isEnabled()); // Test that enabled state is restored, this is called i.e. when appmenu is opened // widget/action starting as enabled m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(false)); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(true)); QVERIFY(widget->isEnabled()); // widget/action starting as disabled action->setEnabled(false); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(false)); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(true)); QVERIFY(!widget->isEnabled()); } QTEST_APPLESS_MAIN(Ut_MToolBar) <commit_msg>Changes: fixing coverity errors (CID#1164, CID#1149)<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mtoolbar.h" #include <MToolBar> #include <MToolBarView> #include <MApplication> #include <MApplicationWindow> #include <MButton> #include <MTextEdit> #include <MSlider> #include <MButtonGroup> #include <MWidgetAction> #include "mtoolbar_p.h" MApplication *app(NULL); // TODO: remove this when unneeded in MTextEdit's constructor MApplicationWindow *appWin(NULL); void Ut_MToolBar::init() { m_subject = new MToolBar(); } void Ut_MToolBar::cleanup() { delete m_subject; m_subject = 0; } void Ut_MToolBar::initTestCase() { static int argc = 1; static char *app_name[1] = { (char *) "./ut_mtoolbar" }; app = new MApplication(argc, app_name); appWin = new MApplicationWindow; } void Ut_MToolBar::cleanupTestCase() { delete appWin; delete app; } void Ut_MToolBar::testConstructor() { QVERIFY(m_subject); } void Ut_MToolBar::testConstructor2() { class InheritedMToolBar : public MToolBar { public: explicit InheritedMToolBar() : MToolBar(new MToolBarPrivate(),new MWidgetModel(),NULL) {}; }; //testing protected constructor: MToolBar(MToolBarPrivate *dd, MWidgetModel *model, QGraphicsItem *parent); InheritedMToolBar* inheritedMToolBar = new InheritedMToolBar(); QVERIFY(inheritedMToolBar); delete inheritedMToolBar; } void Ut_MToolBar::testDestructor() { MToolBar *toolbar = new MToolBar(); delete toolbar; } void Ut_MToolBar::testAddAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // return value action MAction *action; // test addAction(const QString &text) MAction *action0 = new MAction("TEXTONLY", m_subject); m_subject->addAction(action0); action = qobject_cast<MAction *>(m_subject->actions().at(0)); // must be one QVERIFY(m_subject->actions().count() == 1); QVERIFY(action == action0); QVERIFY(action->text() == "TEXTONLY"); // test addAction(const QString &icon, const QString &text) MAction *action1 = new MAction("Icon-list-view-on", "TEXT", m_subject); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action == action1); QVERIFY(action->iconID() == "Icon-list-view-on"); QVERIFY(action->text() == "TEXT"); testValue = false; senderAction = NULL; connect(action1, SIGNAL(triggered(bool)), this, SLOT(actionSlot(bool))); action1->trigger(); QVERIFY(testValue); QVERIFY(senderAction == action1); // test addAction(MAction* action) MAction *action2 = new MAction("Icon-time-line-on", "TEXT4", NULL); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 3); action = qobject_cast<MAction *>(m_subject->actions().at(2)); QVERIFY(action == action2); delete action2; } void Ut_MToolBar::testAddTextEditAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // test addAction(Text Edit) MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(0)); // must be one QVERIFY(m_subject->actions().count() == 1); QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(widgetAction->widget() == textEntry); } void Ut_MToolBar::testInsertAction() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //adding text edit MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); //first action, indx 0 //adding actions MAction *action0 = new MAction("action0", m_subject); m_subject->addAction(action0); //second action, indx 1 MAction *action1 = new MAction("action1", m_subject); m_subject->insertAction(action0, action1); //third action, indx1 -> action0 goes to indx 2 QVERIFY(m_subject->actions().count() == 3); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(0)); // getting indx 0 MAction *action = qobject_cast<MAction *>(m_subject->actions().at(1)); //getting indx 1 //veryfing: QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(action); QVERIFY(action == action1); action = qobject_cast<MAction *>(m_subject->actions().at(2)); //getting indx 2 QVERIFY(action); QVERIFY(action == action0); } void Ut_MToolBar::testActionVisiblity() { // empty action list, check m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //adding actions: MAction *action0 = new MAction("action0", m_subject); m_subject->addAction(action0); //first action, indx 0 MAction *action1 = new MAction("action1", m_subject); m_subject->addAction(action1); //second action, indx 1 MAction *action2 = new MAction("action2", m_subject); m_subject->addAction(action2); //third action, indx 2 MAction *action3 = new MAction("action3", m_subject); m_subject->addAction(action3); //fourth action, indx 3 QVERIFY(m_subject->actions().count() == 4); MAction *action; //needed for veryfing action0->setVisible(false); action1->setVisible(false); QVERIFY(m_subject->actions().count() == 4); action = qobject_cast<MAction *>(m_subject->actions().at(0)); QVERIFY(action); QVERIFY(action == action0); QVERIFY(action->isVisible() == false); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action); QVERIFY(action == action1); QVERIFY(action->isVisible() == false); action = qobject_cast<MAction *>(m_subject->actions().at(2)); QVERIFY(action); QVERIFY(action == action2); QVERIFY(action->isVisible() == true); action = qobject_cast<MAction *>(m_subject->actions().at(3)); QVERIFY(action); QVERIFY(action == action3); QVERIFY(action->isVisible() == true); //text entry: MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); m_subject->addAction(actionTextEdit); MWidgetAction *widgetAction = qobject_cast<MWidgetAction *>(m_subject->actions().at(4)); QVERIFY(widgetAction); QVERIFY(widgetAction == actionTextEdit); QVERIFY(widgetAction->isVisible() == true); action0->setVisible(true); action = qobject_cast<MAction *>(m_subject->actions().at(0)); QVERIFY(action); QVERIFY(action == action0); QVERIFY(action->isVisible() == true); action1->setVisible(true); action = qobject_cast<MAction *>(m_subject->actions().at(1)); QVERIFY(action); QVERIFY(action == action1); QVERIFY(action->isVisible() == true); QVERIFY(widgetAction); QVERIFY(widgetAction->widget()->isVisible() == false); //visiblity should be changed, because there is no room for this anymore } void Ut_MToolBar::testAddTabAction() { m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); m_subject->setViewType(MToolBar::tabType); MAction *action0 = new MAction("action0", m_subject); action0->setLocation(MAction::ToolBarLandscapeLocation); action0->setCheckable(true); action0->setChecked(true); m_subject->addAction(action0); QVERIFY(m_subject->actions().count() == 1); MAction *action1 = new MAction("action1", m_subject); action1->setLocation(MAction::ToolBarPortraitLocation); action1->setCheckable(true); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); MAction *action2 = new MAction("action2", m_subject); action2->setLocation(MAction::ToolBarLocation); action2->setCheckable(true); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 3); } void Ut_MToolBar::testRemoveTabAction() { m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); m_subject->setViewType(MToolBar::tabType); MAction *action0 = new MAction("action0", m_subject); action0->setLocation(MAction::ToolBarLandscapeLocation); action0->setCheckable(true); action0->setChecked(true); m_subject->addAction(action0); QVERIFY(m_subject->actions().count() == 1); MAction *action1 = new MAction("action1", m_subject); action1->setLocation(MAction::ToolBarPortraitLocation); action1->setCheckable(true); m_subject->addAction(action1); QVERIFY(m_subject->actions().count() == 2); m_subject->removeAction(action1); QVERIFY(m_subject->actions().count() == 1); MAction *action2 = new MAction("action2", m_subject); action2->setLocation(MAction::ToolBarLocation); action2->setCheckable(true); m_subject->addAction(action2); QVERIFY(m_subject->actions().count() == 2); m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); } void Ut_MToolBar::actionSlot(bool) { senderAction = qobject_cast<MAction *>(sender()); testValue = true; } void Ut_MToolBar::testNoLocation() { //Add an action to everywhere and then change it to nowhere, to test that this does not crash etc m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); //Add a normal action MAction *action0 = new MAction("action0", m_subject); action0->setCheckable(true); action0->setChecked(true); appWin->addAction(action0); //Add a widget action MTextEdit *textEntry = new MTextEdit(); MWidgetAction *actionTextEdit = new MWidgetAction(m_subject); actionTextEdit->setWidget(textEntry); appWin->addAction(actionTextEdit); QCOMPARE(action0->location(), MAction::EveryLocation); QCOMPARE(actionTextEdit->location(), MAction::EveryLocation); //Now remove both actions action0->setLocation(MAction::NoLocation); actionTextEdit->setLocation(MAction::NoLocation); } void Ut_MToolBar::testPropertyChange() { // Add an action then set the Property which is triggered by the AppMenu when it is opened and closed m_subject->clearActions(); QVERIFY(m_subject->actions().count() == 0); // Add a normal action MAction *action = new MAction("action", m_subject); action->setLocation(MAction::ToolBarLocation); action->setEnabled(true); action->setVisible(true); m_subject->addAction(action); // Retrieve the widget associated with the action const MToolBarView *view = dynamic_cast<const MToolBarView *>(m_subject->view()); Q_ASSERT(view); MWidget *widget = view->getWidget(action); QVERIFY(widget); QVERIFY(widget->isEnabled()); // Test that enabled state is restored, this is called i.e. when appmenu is opened // widget/action starting as enabled m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(false)); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(true)); QVERIFY(widget->isEnabled()); // widget/action starting as disabled action->setEnabled(false); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(false)); QVERIFY(!widget->isEnabled()); m_subject->setProperty(_M_IsEnabledPreservingSelection, QVariant(true)); QVERIFY(!widget->isEnabled()); } QTEST_APPLESS_MAIN(Ut_MToolBar) <|endoftext|>
<commit_before>/* * File: Result.cpp * Author: cjg * * Created on October 18, 2009, 1:23 PM */ #include "Result.h" Result::Result(cudaError_t exit_code) { mExitCode = exit_code; mpOutputBuffer = new Buffer(); } Result::Result(cudaError_t exit_code, const Buffer* output_buffer) { mExitCode = exit_code; mpOutputBuffer = const_cast<Buffer *>(output_buffer); } Result::Result(const Result& orig) { } Result::Result(std::istream & in) { in.read((char *) &mExitCode, sizeof(cudaError_t)); mpOutputBuffer = new Buffer(in); } Result::~Result() { } cudaError_t Result::GetExitCode() { return mExitCode; } const Buffer * Result::GetOutputBufffer() const { return mpOutputBuffer; } void Result::Dump(std::ostream& out) { out.write((char *) &mExitCode, sizeof(cudaError_t)); mpOutputBuffer->Dump(out); } <commit_msg>avoiding usage of an empy Buffer when isn't needed in Result<commit_after>/* * File: Result.cpp * Author: cjg * * Created on October 18, 2009, 1:23 PM */ #include "Result.h" Result::Result(cudaError_t exit_code) { mExitCode = exit_code; mpOutputBuffer = NULL; } Result::Result(cudaError_t exit_code, const Buffer* output_buffer) { mExitCode = exit_code; mpOutputBuffer = const_cast<Buffer *>(output_buffer); } Result::Result(const Result& orig) { } Result::Result(std::istream & in) { in.read((char *) &mExitCode, sizeof(cudaError_t)); mpOutputBuffer = new Buffer(in); } Result::~Result() { } cudaError_t Result::GetExitCode() { return mExitCode; } const Buffer * Result::GetOutputBufffer() const { return mpOutputBuffer; } void Result::Dump(std::ostream& out) { out.write((char *) &mExitCode, sizeof(cudaError_t)); if(mpOutputBuffer != NULL) mpOutputBuffer->Dump(out); else { size_t size = 0; out.write((char *) &size, sizeof(size_t)); out.flush(); } } <|endoftext|>
<commit_before>// Disable warnings for fopen #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "Image.hpp" #include <png.h> #include <memory> #include <functional> #include <cassert> #include "Utils.hpp" // Stores the message from callback function thread_local static const char* message = nullptr; Image Image::load(const std::string& file) { auto f = finalize(fopen(file.c_str(), "rb"), fclose); if (!f) throw std::runtime_error(combine("failed to open file (\"", file, "\")")); png_byte sig[8]; if (!fread(sig, 8, 1, f.get()) || !png_check_sig(sig, 8)) throw std::runtime_error(combine("invalid png file (\"", file, "\")")); message = nullptr; auto png = finalize(png_create_read_struct( PNG_LIBPNG_VER_STRING, nullptr, [](auto png, auto msg) { message = msg; longjmp(png_jmpbuf(png), 1); }, nullptr ), [](auto png) { png_destroy_read_struct(&png, nullptr, nullptr); }); if (!png) throw std::bad_alloc(); if (setjmp(png_jmpbuf(png.get()))) { if (!message) throw std::runtime_error(combine("libpng failed (\"", file, "\")")); throw std::runtime_error(combine("loading png file failed (\"", file, "\"): ", message)); } auto info = finalize(png_create_info_struct(png.get()), [](auto info) { png_destroy_read_struct(nullptr, &info, nullptr); }); if (!info) throw std::bad_alloc(); png_init_io(png.get(), f.get()); png_set_sig_bytes(png.get(), 8); png_read_info(png.get(), info.get()); Image img(png_get_image_width(png.get(), info.get()), png_get_image_height(png.get(), info.get())); auto type = png_get_color_type(png.get(), info.get()); auto depth = png_get_bit_depth(png.get(), info.get()); if (depth == 16) png_set_strip_16(png.get()); if (type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png.get()); if (type == PNG_COLOR_TYPE_GRAY && depth < 8) png_set_expand_gray_1_2_4_to_8(png.get()); if (png_get_valid(png.get(), info.get(), PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png.get()); if (type == PNG_COLOR_TYPE_RGB || type == PNG_COLOR_TYPE_GRAY || type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png.get(), 0xFF, PNG_FILLER_AFTER); if (type == PNG_COLOR_TYPE_GRAY || type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png.get()); png_read_update_info(png.get(), info.get()); auto rowBytes = png_get_rowbytes(png.get(), info.get()); img.m_data.resize(rowBytes * img.m_height); std::unique_ptr<png_bytep[]> rowPointers(new png_bytep[img.m_height]); for (unsigned int i = 0; i < img.m_height; i++) rowPointers[i] = (png_bytep) img.data() + i * rowBytes; png_read_image(png.get(), rowPointers.get()); return img; } void Image::save(const std::string& file) const { auto f = finalize(fopen(file.c_str(), "wb"), fclose); if (!f) throw std::runtime_error(combine("failed to open file (\"", file, "\")")); message = nullptr; auto png = finalize(png_create_write_struct( PNG_LIBPNG_VER_STRING, nullptr, [](auto png, auto msg) { message = msg; longjmp(png_jmpbuf(png), 1); }, nullptr ), [](auto png) { png_destroy_write_struct(&png, nullptr); }); if (!png) throw std::bad_alloc(); if (setjmp(png_jmpbuf(png.get()))) { if (!message) throw std::runtime_error(combine("libpng failed (\"", file, "\")")); throw std::runtime_error(combine("saving png file failed (\"", file, "\"): ", message)); } auto info = finalize(png_create_info_struct(png.get()), [](auto info) { png_destroy_write_struct(nullptr, &info); }); if (!info) throw std::bad_alloc(); png_set_IHDR( png.get(), info.get(), m_width, m_height, 8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); auto rowBytes = 4 * m_width; std::unique_ptr<png_bytep[]> rowPointers(new png_bytep[m_height]); for (unsigned int i = 0; i < m_height; i++) rowPointers[i] = (png_bytep) m_data.data() + i * rowBytes; png_init_io(png.get(), f.get()); png_set_rows(png.get(), info.get(), rowPointers.get()); png_write_png(png.get(), info.get(), PNG_TRANSFORM_IDENTITY, nullptr); } Rectangle Image::getBounds() const { unsigned int x1 = 0, y1 = 0, x2 = m_width - 1, y2 = m_height - 1; // Search for upper border for (; y1 < m_height; ++y1) { unsigned int i; for (i = 0; i < m_width; ++i) if (at(i, y1) & 0xFF000000) break; if (i < m_width) break; } // If y1 is greater equal height the image is empty if (y1 >= m_height) return { 0, 0, 0, 0 }; // Search for lower border for (; y2 > y1; --y2) { unsigned int i; for (i = 0; i < m_width; ++i) if (at(i, y2) & 0xFF000000) break; if (i < m_width) break; } // Search for left border for (; x1 < m_width; ++x1) { unsigned int i; for (i = y1; i <= y2; ++i) if (at(x1, i) & 0xFF000000) break; if (i <= y2) break; } // Search for lower border for (; x2 > x1; --x2) { unsigned int i; for (i = y1; i <= y2; ++i) if (at(x2, i) & 0xFF000000) break; if (i <= y2) break; } return { x1, y1, x2 - x1 + 1, y2 - y1 + 1 }; } void Image::copy(const Image& img, unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int dx, unsigned int dy) { assert(x + w <= img.width()); assert(y + h <= img.height()); assert(dx + w <= width()); assert(dy + h <= height()); auto pointerSrc = &img.at(x, y); auto strideSrc = img.width() - w; auto pointerDst = &at(dx, dy); auto strideDst = width() - w; for (unsigned int j = 0; j < h; ++j) { for (unsigned int i = 0; i < w; ++i) *pointerDst++ = *pointerSrc++; pointerSrc += strideSrc; pointerDst += strideDst; } } void Image::copyFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int dx, unsigned int dy) { assert(x + w <= img.width()); assert(y + h <= img.height()); // h and w swapped because the image gets flipped assert(dx + h <= width()); assert(dy + w <= height()); auto pointerSrc = &img.at(img.width() - y - 1, x); auto strideSrc = h * img.width() + 1; auto innerStrideSrc = img.width(); auto pointerDst = &at(dx, dy); auto strideDst = width() - h; for (unsigned int j = 0; j < w; ++j) { for (unsigned int i = 0; i < h; ++i) { *pointerDst++ = *pointerSrc; pointerSrc += innerStrideSrc; } pointerSrc -= strideSrc; pointerDst += strideDst; } } void Image::fill(unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int color) { assert(x + w <= width()); assert(y + h <= height()); auto pointerDst = &at(x, y); auto strideDst = width() - w; for (unsigned int j = 0; j < h; ++j) { for (unsigned int i = 0; i < w; ++i) *pointerDst++ = color; pointerDst += strideDst; } } void Image::copyLineHor(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x + length <= img.width()); assert(y < img.height()); assert(dx + length <= width()); assert(dy < height()); auto pointerSrc = &img.at(x, y); auto pointerDst = &at(dx, dy); for (unsigned int i = 0; i < length; ++i) *pointerDst++ = *pointerSrc++; } void Image::copyLineVert(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x < img.width()); assert(y + length <= img.height()); assert(dx < width()); assert(dy + length <= height()); auto pointerSrc = &img.at(x, y); auto strideSrc = img.width(); auto pointerDst = &at(dx, dy); auto strideDst = width(); for (unsigned int i = 0; i < length; ++i) { *pointerDst = *pointerSrc; pointerSrc += strideSrc; pointerDst += strideDst; } } void Image::copyLineHorFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x + length <= img.height()); assert(y < img.width()); assert(dx + length <= width()); assert(dy < height()); auto pointerSrc = &img.at(img.width() - y - 1, x); auto strideSrc = img.width(); auto pointerDst = &at(dx, dy); for (unsigned int i = 0; i < length; ++i) { *pointerDst++ = *pointerSrc; pointerSrc += strideSrc; } } void Image::copyLineVertFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x < img.height()); assert(y + length <= img.width()); assert(dx < width()); assert(dy + length <= height()); auto pointerSrc = &img.at(img.width() - y - 1, x); auto pointerDst = &at(dx, dy); auto strideDst = width(); for (unsigned int i = 0; i < length; ++i) { *pointerDst = *pointerSrc--; pointerDst += strideDst; } } <commit_msg>Change at to atFlipped<commit_after>// Disable warnings for fopen #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "Image.hpp" #include <png.h> #include <memory> #include <functional> #include <cassert> #include "Utils.hpp" // Stores the message from callback function thread_local static const char* message = nullptr; Image Image::load(const std::string& file) { auto f = finalize(fopen(file.c_str(), "rb"), fclose); if (!f) throw std::runtime_error(combine("failed to open file (\"", file, "\")")); png_byte sig[8]; if (!fread(sig, 8, 1, f.get()) || !png_check_sig(sig, 8)) throw std::runtime_error(combine("invalid png file (\"", file, "\")")); message = nullptr; auto png = finalize(png_create_read_struct( PNG_LIBPNG_VER_STRING, nullptr, [](auto png, auto msg) { message = msg; longjmp(png_jmpbuf(png), 1); }, nullptr ), [](auto png) { png_destroy_read_struct(&png, nullptr, nullptr); }); if (!png) throw std::bad_alloc(); if (setjmp(png_jmpbuf(png.get()))) { if (!message) throw std::runtime_error(combine("libpng failed (\"", file, "\")")); throw std::runtime_error(combine("loading png file failed (\"", file, "\"): ", message)); } auto info = finalize(png_create_info_struct(png.get()), [](auto info) { png_destroy_read_struct(nullptr, &info, nullptr); }); if (!info) throw std::bad_alloc(); png_init_io(png.get(), f.get()); png_set_sig_bytes(png.get(), 8); png_read_info(png.get(), info.get()); Image img(png_get_image_width(png.get(), info.get()), png_get_image_height(png.get(), info.get())); auto type = png_get_color_type(png.get(), info.get()); auto depth = png_get_bit_depth(png.get(), info.get()); if (depth == 16) png_set_strip_16(png.get()); if (type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png.get()); if (type == PNG_COLOR_TYPE_GRAY && depth < 8) png_set_expand_gray_1_2_4_to_8(png.get()); if (png_get_valid(png.get(), info.get(), PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png.get()); if (type == PNG_COLOR_TYPE_RGB || type == PNG_COLOR_TYPE_GRAY || type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png.get(), 0xFF, PNG_FILLER_AFTER); if (type == PNG_COLOR_TYPE_GRAY || type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png.get()); png_read_update_info(png.get(), info.get()); auto rowBytes = png_get_rowbytes(png.get(), info.get()); img.m_data.resize(rowBytes * img.m_height); std::unique_ptr<png_bytep[]> rowPointers(new png_bytep[img.m_height]); for (unsigned int i = 0; i < img.m_height; i++) rowPointers[i] = (png_bytep) img.data() + i * rowBytes; png_read_image(png.get(), rowPointers.get()); return img; } void Image::save(const std::string& file) const { auto f = finalize(fopen(file.c_str(), "wb"), fclose); if (!f) throw std::runtime_error(combine("failed to open file (\"", file, "\")")); message = nullptr; auto png = finalize(png_create_write_struct( PNG_LIBPNG_VER_STRING, nullptr, [](auto png, auto msg) { message = msg; longjmp(png_jmpbuf(png), 1); }, nullptr ), [](auto png) { png_destroy_write_struct(&png, nullptr); }); if (!png) throw std::bad_alloc(); if (setjmp(png_jmpbuf(png.get()))) { if (!message) throw std::runtime_error(combine("libpng failed (\"", file, "\")")); throw std::runtime_error(combine("saving png file failed (\"", file, "\"): ", message)); } auto info = finalize(png_create_info_struct(png.get()), [](auto info) { png_destroy_write_struct(nullptr, &info); }); if (!info) throw std::bad_alloc(); png_set_IHDR( png.get(), info.get(), m_width, m_height, 8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); auto rowBytes = 4 * m_width; std::unique_ptr<png_bytep[]> rowPointers(new png_bytep[m_height]); for (unsigned int i = 0; i < m_height; i++) rowPointers[i] = (png_bytep) m_data.data() + i * rowBytes; png_init_io(png.get(), f.get()); png_set_rows(png.get(), info.get(), rowPointers.get()); png_write_png(png.get(), info.get(), PNG_TRANSFORM_IDENTITY, nullptr); } Rectangle Image::getBounds() const { unsigned int x1 = 0, y1 = 0, x2 = m_width - 1, y2 = m_height - 1; // Search for upper border for (; y1 < m_height; ++y1) { unsigned int i; for (i = 0; i < m_width; ++i) if (at(i, y1) & 0xFF000000) break; if (i < m_width) break; } // If y1 is greater equal height the image is empty if (y1 >= m_height) return { 0, 0, 0, 0 }; // Search for lower border for (; y2 > y1; --y2) { unsigned int i; for (i = 0; i < m_width; ++i) if (at(i, y2) & 0xFF000000) break; if (i < m_width) break; } // Search for left border for (; x1 < m_width; ++x1) { unsigned int i; for (i = y1; i <= y2; ++i) if (at(x1, i) & 0xFF000000) break; if (i <= y2) break; } // Search for lower border for (; x2 > x1; --x2) { unsigned int i; for (i = y1; i <= y2; ++i) if (at(x2, i) & 0xFF000000) break; if (i <= y2) break; } return { x1, y1, x2 - x1 + 1, y2 - y1 + 1 }; } void Image::copy(const Image& img, unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int dx, unsigned int dy) { assert(x + w <= img.width()); assert(y + h <= img.height()); assert(dx + w <= width()); assert(dy + h <= height()); auto pointerSrc = &img.at(x, y); auto strideSrc = img.width() - w; auto pointerDst = &at(dx, dy); auto strideDst = width() - w; for (unsigned int j = 0; j < h; ++j) { for (unsigned int i = 0; i < w; ++i) *pointerDst++ = *pointerSrc++; pointerSrc += strideSrc; pointerDst += strideDst; } } void Image::copyFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int dx, unsigned int dy) { assert(x + w <= img.width()); assert(y + h <= img.height()); // h and w swapped because the image gets flipped assert(dx + h <= width()); assert(dy + w <= height()); auto pointerSrc = &img.atFlipped(x, y); auto strideSrc = h * img.width() + 1; auto innerStrideSrc = img.width(); auto pointerDst = &at(dx, dy); auto strideDst = width() - h; for (unsigned int j = 0; j < w; ++j) { for (unsigned int i = 0; i < h; ++i) { *pointerDst++ = *pointerSrc; pointerSrc += innerStrideSrc; } pointerSrc -= strideSrc; pointerDst += strideDst; } } void Image::fill(unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned int color) { assert(x + w <= width()); assert(y + h <= height()); auto pointerDst = &at(x, y); auto strideDst = width() - w; for (unsigned int j = 0; j < h; ++j) { for (unsigned int i = 0; i < w; ++i) *pointerDst++ = color; pointerDst += strideDst; } } void Image::copyLineHor(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x + length <= img.width()); assert(y < img.height()); assert(dx + length <= width()); assert(dy < height()); auto pointerSrc = &img.at(x, y); auto pointerDst = &at(dx, dy); for (unsigned int i = 0; i < length; ++i) *pointerDst++ = *pointerSrc++; } void Image::copyLineVert(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x < img.width()); assert(y + length <= img.height()); assert(dx < width()); assert(dy + length <= height()); auto pointerSrc = &img.at(x, y); auto strideSrc = img.width(); auto pointerDst = &at(dx, dy); auto strideDst = width(); for (unsigned int i = 0; i < length; ++i) { *pointerDst = *pointerSrc; pointerSrc += strideSrc; pointerDst += strideDst; } } void Image::copyLineHorFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x + length <= img.height()); assert(y < img.width()); assert(dx + length <= width()); assert(dy < height()); auto pointerSrc = &img.atFlipped(x, y); auto strideSrc = img.width(); auto pointerDst = &at(dx, dy); for (unsigned int i = 0; i < length; ++i) { *pointerDst++ = *pointerSrc; pointerSrc += strideSrc; } } void Image::copyLineVertFlipped(const Image& img, unsigned int x, unsigned int y, unsigned int length, unsigned int dx, unsigned int dy) { assert(x < img.height()); assert(y + length <= img.width()); assert(dx < width()); assert(dy + length <= height()); auto pointerSrc = &img.atFlipped(x, y); auto pointerDst = &at(dx, dy); auto strideDst = width(); for (unsigned int i = 0; i < length; ++i) { *pointerDst = *pointerSrc--; pointerDst += strideDst; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/size.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/mat/meta/length_mvt.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/scal/fun/inv_logit.hpp> #include <stan/math/prim/scal/fun/log1p_exp.hpp> #include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_greater.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <vector> namespace stan { namespace math { /** * Returns the (natural) log probability of the specified array * of integers given the vector of continuous locations and * specified cutpoints in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome * \f[ \frac{\partial }{\partial \lambda} = \left\{\begin{array} \\ -\mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1, \\ ((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) + ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)) & \mathrm{if } 1 < k < K, \mathrm{and} \\ \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K. \end{array}\right. \f] \f[ \frac{\partial }{\partial \mathrm{c_{K}}} = \left\{\begin{array} \\ \mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1, \\ \frac{\partial }{\partial \mathrm{c_{K-2}}} = ((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) \\ \frac{\partial }{\partial \mathrm{c_{K-1}}} = ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)) & \mathrm{if } 1 < k < K, \mathrm{and} \\ -\mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K. \end{array}\right. \f] * * @tparam propto True if calculating up to a proportion. * @tparam T_y Y variable type (integer or array of integers). * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Array of integers * @param lambda Vector of continuous location variables. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. * @throw std::invalid_argument If y and lambda are different * lengths. */ template <bool propto, typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type<T_loc, T_cut>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; scalar_seq_view<T_loc> lam_vec(lambda); scalar_seq_view<T_y> y_vec(y); vector_seq_view<T_cut> c_vec(c); int K = c_vec[0].size() + 1; int N = length(lambda); int C_l = length_mvt(c); check_consistent_sizes(function, "Integers", y, "Locations", lambda); if (C_l > 1) check_size_match(function, "Length of location variables ", N, "Number of cutpoint vectors ", C_l); int size_c_old = c_vec[0].size(); for (int i = 1; i < C_l; i++) { int size_c_new = c_vec[i].size(); check_size_match(function, "Size of one of the vectors of cutpoints ", size_c_new, "Size of another vector of the cutpoints ", size_c_old); } for (int n = 0; n < N; n++) { check_bounded(function, "Random variable", y_vec[n], 1, K); check_finite(function, "Location parameter", lam_vec[n]); } for (int i = 0; i < C_l; i++) { check_ordered(function, "Cut-points", c_vec[i]); check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0); check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1)); check_finite(function, "First cut-point", c_vec[i](0)); } operands_and_partials<T_loc, T_cut> ops_partials(lambda, c); T_partials_return logp(0.0); T_partials_vec c_dbl = value_of(c_vec[0]).template cast<T_partials_return>(); for (int n = 0; n < N; ++n) { if (C_l > 1) c_dbl = value_of(c_vec[n]).template cast<T_partials_return>(); T_partials_return lam_dbl = value_of(lam_vec[n]); if (y_vec[n] == 1) { logp -= log1p_exp(lam_dbl - c_dbl[0]); T_partials_return d = inv_logit(lam_dbl - c_dbl[0]); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] -= d; if (!is_constant_struct<T_cut>::value) ops_partials.edge2_.partials_vec_[n](0) = d; } else if (y_vec[n] == K) { logp -= log1p_exp(c_dbl[K - 2] - lam_dbl); T_partials_return d = inv_logit(c_dbl[K - 2] - lam_dbl); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] = d; if (!is_constant_struct<T_cut>::value) ops_partials.edge2_.partials_vec_[n](K - 2) -= d; } else { T_partials_return d1 = inv(1 - exp(c_dbl[y_vec[n] - 1] - c_dbl[y_vec[n] - 2])) - inv_logit(c_dbl[y_vec[n] - 2] - lam_dbl); T_partials_return d2 = inv(1 - exp(c_dbl[y_vec[n] - 2] - c_dbl[y_vec[n] - 1])) - inv_logit(c_dbl[y_vec[n] - 1] - lam_dbl); logp += log_inv_logit_diff(lam_dbl - c_dbl[y_vec[n] - 2], lam_dbl - c_dbl[y_vec[n] - 1]); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] -= d1 + d2; if (!is_constant_struct<T_cut>::value) { ops_partials.edge2_.partials_vec_[n](y_vec[n] - 2) += d1; ops_partials.edge2_.partials_vec_[n](y_vec[n] - 1) += d2; } } } return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/size.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/mat/meta/length_mvt.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/scal/fun/inv_logit.hpp> #include <stan/math/prim/scal/fun/log1p_exp.hpp> #include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_greater.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <vector> namespace stan { namespace math { /** * Returns the (natural) log probability of the specified array * of integers given the vector of continuous locations and * specified cutpoints in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome * \f[ \frac{\partial }{\partial \lambda} = \left\{\begin{array} \\ -\mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1, \\ ((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) + ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)) & \mathrm{if } 1 < k < K, \mathrm{and} \\ \mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K. \end{array}\right. \f] \f[ \frac{\partial }{\partial \mathrm{c_{K}}} = \left\{\begin{array} \\ \mathrm{logit}^{-1}(\lambda - c_1) & \mbox{if } k = 1, \\ \frac{\partial }{\partial \mathrm{c_{K-2}}} = ((1-e^{c_{k-1}-c_{k-2}})^{-1} - \mathrm{logit}^{-1}(c_{k-2}-\lambda)) \\ \frac{\partial }{\partial \mathrm{c_{K-1}}} = ((1-e^{c_{k-2}-c_{k-1}})^{-1} - \mathrm{logit}^{-1}(c_{k-1}-\lambda)) & \mathrm{if } 1 < k < K, \mathrm{and} \\ -\mathrm{logit}^{-1}(c_{K-2}-\lambda) & \mathrm{if } k = K. \end{array}\right. \f] * * @tparam propto True if calculating up to a proportion. * @tparam T_y Y variable type (integer or array of integers). * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Array of integers * @param lambda Vector of continuous location variables. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. * @throw std::invalid_argument If y and lambda are different * lengths. */ template <bool propto, typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type<T_loc, T_cut>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; scalar_seq_view<T_loc> lam_vec(lambda); scalar_seq_view<T_y> y_vec(y); vector_seq_view<T_cut> c_vec(c); int K = c_vec[0].size() + 1; int N = length(lambda); int C_l = length_mvt(c); check_consistent_sizes(function, "Integers", y, "Locations", lambda); if (C_l > 1) check_size_match(function, "Length of location variables ", N, "Number of cutpoint vectors ", C_l); int size_c_old = c_vec[0].size(); for (int i = 1; i < C_l; i++) { int size_c_new = c_vec[i].size(); check_size_match(function, "Size of one of the vectors of cutpoints ", size_c_new, "Size of another vector of the cutpoints ", size_c_old); } for (int n = 0; n < N; n++) { check_bounded(function, "Random variable", y_vec[n], 1, K); check_finite(function, "Location parameter", lam_vec[n]); } for (int i = 0; i < C_l; i++) { check_ordered(function, "Cut-points", c_vec[i]); check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0); check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1)); check_finite(function, "First cut-point", c_vec[i](0)); } operands_and_partials<T_loc, T_cut> ops_partials(lambda, c); T_partials_return logp(0.0); T_partials_vec c_dbl = value_of(c_vec[0]).template cast<T_partials_return>(); for (int n = 0; n < N; ++n) { if (C_l > 1) c_dbl = value_of(c_vec[n]).template cast<T_partials_return>(); T_partials_return lam_dbl = value_of(lam_vec[n]); if (y_vec[n] == 1) { logp -= log1p_exp(lam_dbl - c_dbl[0]); T_partials_return d = inv_logit(lam_dbl - c_dbl[0]); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] -= d; if (!is_constant_struct<T_cut>::value) ops_partials.edge2_.partials_vec_[n](0) = d; } else if (y_vec[n] == K) { logp -= log1p_exp(c_dbl[K - 2] - lam_dbl); T_partials_return d = inv_logit(c_dbl[K - 2] - lam_dbl); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] = d; if (!is_constant_struct<T_cut>::value) ops_partials.edge2_.partials_vec_[n](K - 2) -= d; } else { T_partials_return d1 = inv(1 - exp(c_dbl[y_vec[n] - 1] - c_dbl[y_vec[n] - 2])) - inv_logit(c_dbl[y_vec[n] - 2] - lam_dbl); T_partials_return d2 = inv(1 - exp(c_dbl[y_vec[n] - 2] - c_dbl[y_vec[n] - 1])) - inv_logit(c_dbl[y_vec[n] - 1] - lam_dbl); logp += log_inv_logit_diff(lam_dbl - c_dbl[y_vec[n] - 2], lam_dbl - c_dbl[y_vec[n] - 1]); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] -= d1 + d2; if (!is_constant_struct<T_cut>::value) { ops_partials.edge2_.partials_vec_[n](y_vec[n] - 2) += d1; ops_partials.edge2_.partials_vec_[n](y_vec[n] - 1) += d2; } } } return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "SFData.h" sf::RenderWindow *SFData::Window; sf::RenderTexture *SFData::FieldTexture; sf::Shader SFData::FieldShader; sf::UdpSocket SFData::Socket; std::map<std::string, sf::Texture> SFData::Textures; std::vector<sf::Sprite> SFData::Sprites; std::vector<sf::Font> SFData::Fonts; std::vector<sf::IpAddress> SFData::Addresses; const sf::Texture &SFData::GetTexture(std::string path) { std::map<std::string, sf::Texture>::iterator i = Textures.find(path); if (i == Textures.end()) { sf::Texture texture; texture.loadFromFile(path); Textures[path] = texture; return Textures[path]; } else { return i->second; } } <commit_msg>Black in spritesheet is now transparent<commit_after>#include "SFData.h" sf::RenderWindow *SFData::Window; sf::RenderTexture *SFData::FieldTexture; sf::Shader SFData::FieldShader; sf::UdpSocket SFData::Socket; std::map<std::string, sf::Texture> SFData::Textures; std::vector<sf::Sprite> SFData::Sprites; std::vector<sf::Font> SFData::Fonts; std::vector<sf::IpAddress> SFData::Addresses; const sf::Texture &SFData::GetTexture(std::string path) { std::map<std::string, sf::Texture>::iterator i = Textures.find(path); if (i == Textures.end()) { sf::Image image; image.loadFromFile(path); image.createMaskFromColor(sf::Color(0, 0, 0)); sf::Texture texture; texture.loadFromImage(image); Textures[path] = texture; return Textures[path]; } else { return i->second; } } <|endoftext|>
<commit_before>#include "Image.h" #include <cassert> #include <iostream> using namespace std; using namespace canvas; std::shared_ptr<Image> Image::changeFormat(const ImageFormat & target_format) const { assert(format.getBytesPerPixel() == 4); assert(target_format.getBytesPerPixel() == 2); unsigned int n = width * height; unsigned char * tmp = new unsigned char[target_format.getBytesPerPixel() * n]; unsigned short * output_data = (unsigned short *)tmp; const unsigned int * input_data = (const unsigned int *)data; if (target_format.getNumChannels() == 2) { for (unsigned int i = 0; i < n; i++) { int v = input_data[i]; int red = RGBA_TO_RED(v); int green = RGBA_TO_GREEN(v); int blue = RGBA_TO_BLUE(v); int alpha = RGBA_TO_ALPHA(v); int lum = (red + green + blue) / 3; if (lum >= 255) lum = 255; *output_data++ = (lum << 8) | alpha; } } else { for (unsigned int i = 0; i < n; i++) { int v = input_data[i]; int red = RGBA_TO_RED(v) >> 3; int green = RGBA_TO_GREEN(v) >> 2; int blue = RGBA_TO_BLUE(v) >> 3; *output_data++ = PACK_RGB565(red, green, blue); } } auto r = std::shared_ptr<Image>(new Image(getWidth(), getHeight(), tmp, target_format)); delete tmp; return r; } <commit_msg>change component orders and temporarily disable green and blue from luminance<commit_after>#include "Image.h" #include <cassert> #include <iostream> using namespace std; using namespace canvas; std::shared_ptr<Image> Image::changeFormat(const ImageFormat & target_format) const { assert(format.getBytesPerPixel() == 4); assert(target_format.getBytesPerPixel() == 2); unsigned int n = width * height; unsigned char * tmp = new unsigned char[target_format.getBytesPerPixel() * n]; unsigned short * output_data = (unsigned short *)tmp; const unsigned int * input_data = (const unsigned int *)data; if (target_format.getNumChannels() == 2) { for (unsigned int i = 0; i < n; i++) { int v = input_data[i]; int red = RGBA_TO_RED(v); int green = RGBA_TO_GREEN(v); int blue = RGBA_TO_BLUE(v); int alpha = RGBA_TO_ALPHA(v); // int lum = (red + green + blue) / 3; // if (lum >= 255) lum = 255; *output_data++ = (alpha << 8) | red; } } else { for (unsigned int i = 0; i < n; i++) { int v = input_data[i]; int red = RGBA_TO_RED(v) >> 3; int green = RGBA_TO_GREEN(v) >> 2; int blue = RGBA_TO_BLUE(v) >> 3; *output_data++ = PACK_RGB565(blue, green, red); } } auto r = std::shared_ptr<Image>(new Image(getWidth(), getHeight(), tmp, target_format)); delete tmp; return r; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_META_IS_VAR_OR_ARITHMETIC_HPP #define STAN_MATH_PRIM_SCAL_META_IS_VAR_OR_ARITHMETIC_HPP #include <stan/math/prim/scal/meta/is_var.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <type_traits> namespace stan { template <typename T1, typename T2 = double, typename T3 = double, typename T4 = double, typename T5 = double, typename T6 = double> struct is_var_or_arithmetic { enum { value = (is_var<typename scalar_type<T1>::type>::value || std::is_arithmetic<typename scalar_type<T1>::type>::value) && (is_var<typename scalar_type<T2>::type>::value || std::is_arithmetic<typename scalar_type<T2>::type>::value) && (is_var<typename scalar_type<T3>::type>::value || std::is_arithmetic<typename scalar_type<T3>::type>::value) && (is_var<typename scalar_type<T4>::type>::value || std::is_arithmetic<typename scalar_type<T4>::type>::value) && (is_var<typename scalar_type<T5>::type>::value || std::is_arithmetic<typename scalar_type<T5>::type>::value) && (is_var<typename scalar_type<T6>::type>::value || std::is_arithmetic<typename scalar_type<T6>::type>::value) }; }; } // namespace stan #endif <commit_msg>added is_var_or_arithmetic<commit_after>#ifndef STAN_MATH_PRIM_SCAL_META_IS_VAR_OR_ARITHMETIC_HPP #define STAN_MATH_PRIM_SCAL_META_IS_VAR_OR_ARITHMETIC_HPP #include <stan/math/prim/scal/meta/is_var.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <stan/math/prim/arr/meta/and.hpp> #include <type_traits> namespace stan { template <typename T> struct is_var_or_arithmetic_ { enum { value = (is_var<typename scalar_type<T>::type>::value || std::is_arithmetic<typename scalar_type<T>::type>::value) }; }; template<typename... T> using is_var_or_arithmetic = and_<is_var_or_arithmetic_<T>...>; } // namespace stan #endif <|endoftext|>
<commit_before>#include "BooPHF.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <sys/types.h> #include <random> #include <algorithm> using namespace std; //example with user provided custom hasher for uint64_t type : class Custom_string_Hasher { public: // the class should have operator () with this signature : uint64_t operator () (std::string key, uint64_t seed=0) const { uint64_t hash = hash_fn(key); hash ^= seed; return hash; } std::hash<std::string> hash_fn; }; //then tell BBhash to use this custom hash : (also appears below, line 104) typedef boomphf::mphf< std::string, Custom_string_Hasher > boophf_t; //from http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int main (int argc, char* argv[]){ //PARAMETERS u_int64_t nelem = 1000000; uint nthreads = 1; if(argc !=3 ){ printf("Usage :\n"); printf("%s <nelem> <nthreads> \n",argv[0]); return EXIT_FAILURE; } if(argc ==3 ){ nelem = strtoul(argv[1], NULL,0); nthreads = atoi(argv[2]); } uint64_t ii, jj; std::vector<std::string> data; int string_size = 100; ///// generation of random strings char * tempchar = (char *) malloc(sizeof(string_size)*sizeof(char)); for (u_int64_t i = 0; i < nelem; i++){ gen_random(tempchar,string_size); data.push_back( std::string(tempchar)); //printf("%s\n",data[i].c_str()); } ////////////////// // at this point, array data contains a set of nelem random unique keys boophf_t * bphf = NULL; double t_begin,t_end; struct timeval timet; printf("Construct a BooPHF with %lli elements \n",nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); // mphf takes as input a c++ range. A std::vector is already a c++ range double gammaFactor = 2.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query // gamma = 2 is a good tradeoff (leads to approx 3.7 bits/key ) //build the mphf bphf = new boomphf::mphf<std::string,Custom_string_Hasher>(nelem,data,nthreads,gammaFactor); gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed = t_end - t_begin; printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed); printf("boophf bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem); //query mphf like this uint64_t idx = bphf->lookup(data[0]); printf(" example query %s -----> %llu \n",data[0].c_str(),idx); delete bphf; return EXIT_SUCCESS; } <commit_msg>bench strings for example<commit_after>#include "BooPHF.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <sys/types.h> #include <random> #include <algorithm> #include <fstream> using namespace std; //example with user provided custom hasher for uint64_t type : class Custom_string_Hasher { public: // the class should have operator () with this signature : uint64_t operator () (std::string key, uint64_t seed=0) const { uint64_t hash = hash_fn(key); hash ^= seed; return hash; } std::hash<std::string> hash_fn; }; //then tell BBhash to use this custom hash : (also appears below, line 104) typedef boomphf::mphf< std::string, Custom_string_Hasher > boophf_t; //from http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int main (int argc, char* argv[]){ //PARAMETERS u_int64_t nelem = 1000000; uint nthreads = 1; if(argc !=3 ){ printf("Usage :\n"); printf("%s <nelem> <nthreads> \n",argv[0]); return EXIT_FAILURE; } if(argc ==3 ){ nelem = strtoul(argv[1], NULL,0); nthreads = atoi(argv[2]); } uint64_t ii, jj; std::vector<std::string> data; int string_size = 18; ///// generation of random strings char * tempchar = (char *) malloc(sizeof(string_size)*sizeof(char)); string lolstr; ifstream inputfile("StringFile.txt",ios::in); for (u_int64_t i = 0; i < nelem; i++){ //RANDOM STRINGS //~ gen_random(tempchar,string_size); //~ data.push_back((string)tempchar); //STRING READ FROM FILE getline(inputfile,lolstr); data.push_back(lolstr); } ////////////////// // at this point, array data contains a set of nelem random unique keys boophf_t * bphf = NULL; double t_begin,t_end; struct timeval timet; printf("Construct a BooPHF with %lli elements \n",nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); // mphf takes as input a c++ range. A std::vector is already a c++ range double gammaFactor = 2.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query // gamma = 2 is a good tradeoff (leads to approx 3.7 bits/key ) //build the mphf bphf = new boomphf::mphf<std::string,Custom_string_Hasher>(nelem,data,nthreads,gammaFactor); gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed = t_end - t_begin; printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed); printf("boophf bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); //query mphf like this for (u_int64_t i = 0; i < 1000000; i++){ uint64_t idx = bphf->lookup(data[i]); } gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed2 = t_end - t_begin; printf("Query of 1M key in %.2fs\n", nelem,elapsed2); delete bphf; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/test/call_test.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/encoder_settings.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; class BitrateEstimatorTest : public test::CallTest { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { Trace::CreateTrace(); Trace::SetTraceCallback(&receiver_trace_); // Reduce the chance that spurious traces will ruin the test. Trace::set_level_filter(kTraceTerseInfo); Call::Config receiver_call_config(&receive_transport_); receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = VideoSendStream::Config(); send_config_.rtp.ssrcs.push_back(kSendSsrcs[0]); // Encoders will be set separately per stream. send_config_.encoder_settings.encoder = NULL; send_config_.encoder_settings.payload_name = "FAKE"; send_config_.encoder_settings.payload_type = kFakeSendPayloadType; video_streams_ = test::CreateVideoStreams(1); receive_config_ = VideoReceiveStream::Config(); assert(receive_config_.codecs.empty()); VideoCodec codec = test::CreateDecoderVideoCodec(send_config_.encoder_settings); receive_config_.codecs.push_back(codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } receiver_call_.reset(); Trace::SetTraceCallback(NULL); Trace::ReturnTrace(); } protected: friend class Stream; class TraceObserver : public TraceCallback { public: TraceObserver() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), received_log_lines_(), expected_log_lines_(), done_(EventWrapper::Create()) { } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped lock(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(kDefaultTimeoutMs); } private: typedef std::list<std::string> Strings; const scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_ GUARDED_BY(crit_sect_); Strings expected_log_lines_ GUARDED_BY(crit_sect_); scoped_ptr<EventWrapper> done_; }; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder_settings.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream( test_->send_config_, test_->video_streams_, NULL); assert(test_->video_streams_.size() == 1); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->video_streams_[0].width, test_->video_streams_[0].height, 30, Clock::GetRealTimeClock())); send_stream_->Start(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.encoder_settings.payload_type; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->Start(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->Stop(); receive_stream_->Stop(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, ImmediatelySwitchToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <commit_msg>Fix data races related with traces in bitrate estimator test.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <functional> #include <list> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/call.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/test/call_test.h" #include "webrtc/test/direct_transport.h" #include "webrtc/test/encoder_settings.h" #include "webrtc/test/fake_decoder.h" #include "webrtc/test/fake_encoder.h" #include "webrtc/test/frame_generator_capturer.h" namespace webrtc { namespace { // Note: consider to write tests that don't depend on the trace system instead // of re-using this class. class TraceObserver { public: TraceObserver() { Trace::set_level_filter(kTraceTerseInfo); Trace::CreateTrace(); Trace::SetTraceCallback(&callback_); // Call webrtc trace to initialize the tracer that would otherwise trigger a // data-race if left to be initialized by multiple threads (i.e. threads // spawned by test::DirectTransport members in BitrateEstimatorTest). WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Instantiate without data races."); } ~TraceObserver() { Trace::SetTraceCallback(NULL); Trace::ReturnTrace(); } void PushExpectedLogLine(const std::string& expected_log_line) { callback_.PushExpectedLogLine(expected_log_line); } EventTypeWrapper Wait() { return callback_.Wait(); } private: class Callback : public TraceCallback { public: Callback() : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), done_(EventWrapper::Create()) {} virtual void Print(TraceLevel level, const char* message, int length) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); std::string msg(message); if (msg.find("BitrateEstimator") != std::string::npos) { received_log_lines_.push_back(msg); } int num_popped = 0; while (!received_log_lines_.empty() && !expected_log_lines_.empty()) { std::string a = received_log_lines_.front(); std::string b = expected_log_lines_.front(); received_log_lines_.pop_front(); expected_log_lines_.pop_front(); num_popped++; EXPECT_TRUE(a.find(b) != std::string::npos); } if (expected_log_lines_.size() <= 0) { if (num_popped > 0) { done_->Set(); } return; } } EventTypeWrapper Wait() { return done_->Wait(test::CallTest::kDefaultTimeoutMs); } void PushExpectedLogLine(const std::string& expected_log_line) { CriticalSectionScoped lock(crit_sect_.get()); expected_log_lines_.push_back(expected_log_line); } private: typedef std::list<std::string> Strings; const scoped_ptr<CriticalSectionWrapper> crit_sect_; Strings received_log_lines_ GUARDED_BY(crit_sect_); Strings expected_log_lines_ GUARDED_BY(crit_sect_); scoped_ptr<EventWrapper> done_; }; Callback callback_; }; } // namespace static const int kTOFExtensionId = 4; static const int kASTExtensionId = 5; class BitrateEstimatorTest : public test::CallTest { public: BitrateEstimatorTest() : receiver_trace_(), send_transport_(), receive_transport_(), sender_call_(), receiver_call_(), receive_config_(), streams_() { } virtual ~BitrateEstimatorTest() { EXPECT_TRUE(streams_.empty()); } virtual void SetUp() { Call::Config receiver_call_config(&receive_transport_); receiver_call_.reset(Call::Create(receiver_call_config)); Call::Config sender_call_config(&send_transport_); sender_call_.reset(Call::Create(sender_call_config)); send_transport_.SetReceiver(receiver_call_->Receiver()); receive_transport_.SetReceiver(sender_call_->Receiver()); send_config_ = VideoSendStream::Config(); send_config_.rtp.ssrcs.push_back(kSendSsrcs[0]); // Encoders will be set separately per stream. send_config_.encoder_settings.encoder = NULL; send_config_.encoder_settings.payload_name = "FAKE"; send_config_.encoder_settings.payload_type = kFakeSendPayloadType; video_streams_ = test::CreateVideoStreams(1); receive_config_ = VideoReceiveStream::Config(); assert(receive_config_.codecs.empty()); VideoCodec codec = test::CreateDecoderVideoCodec(send_config_.encoder_settings); receive_config_.codecs.push_back(codec); // receive_config_.external_decoders will be set by every stream separately. receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0]; receive_config_.rtp.local_ssrc = kReceiverLocalSsrc; receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receive_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); } virtual void TearDown() { std::for_each(streams_.begin(), streams_.end(), std::mem_fun(&Stream::StopSending)); send_transport_.StopSending(); receive_transport_.StopSending(); while (!streams_.empty()) { delete streams_.back(); streams_.pop_back(); } receiver_call_.reset(); } protected: friend class Stream; class Stream { public: explicit Stream(BitrateEstimatorTest* test) : test_(test), is_sending_receiving_(false), send_stream_(NULL), receive_stream_(NULL), frame_generator_capturer_(), fake_encoder_(Clock::GetRealTimeClock()), fake_decoder_() { test_->send_config_.rtp.ssrcs[0]++; test_->send_config_.encoder_settings.encoder = &fake_encoder_; send_stream_ = test_->sender_call_->CreateVideoSendStream( test_->send_config_, test_->video_streams_, NULL); assert(test_->video_streams_.size() == 1); frame_generator_capturer_.reset( test::FrameGeneratorCapturer::Create(send_stream_->Input(), test_->video_streams_[0].width, test_->video_streams_[0].height, 30, Clock::GetRealTimeClock())); send_stream_->Start(); frame_generator_capturer_->Start(); ExternalVideoDecoder decoder; decoder.decoder = &fake_decoder_; decoder.payload_type = test_->send_config_.encoder_settings.payload_type; test_->receive_config_.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0]; test_->receive_config_.rtp.local_ssrc++; test_->receive_config_.external_decoders.push_back(decoder); receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream( test_->receive_config_); receive_stream_->Start(); is_sending_receiving_ = true; } ~Stream() { frame_generator_capturer_.reset(NULL); test_->sender_call_->DestroyVideoSendStream(send_stream_); send_stream_ = NULL; test_->receiver_call_->DestroyVideoReceiveStream(receive_stream_); receive_stream_ = NULL; } void StopSending() { if (is_sending_receiving_) { frame_generator_capturer_->Stop(); send_stream_->Stop(); receive_stream_->Stop(); is_sending_receiving_ = false; } } private: BitrateEstimatorTest* test_; bool is_sending_receiving_; VideoSendStream* send_stream_; VideoReceiveStream* receive_stream_; scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_; test::FakeEncoder fake_encoder_; test::FakeDecoder fake_decoder_; }; TraceObserver receiver_trace_; test::DirectTransport send_transport_; test::DirectTransport receive_transport_; scoped_ptr<Call> sender_call_; scoped_ptr<Call> receiver_call_; VideoReceiveStream::Config receive_config_; std::vector<Stream*> streams_; }; TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefault) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, ImmediatelySwitchToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToAST) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOF) { send_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kTOffset, kTOFExtensionId)); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId); receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE."); receiver_trace_.PushExpectedLogLine( "AbsoluteSendTimeRemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); send_config_.rtp.extensions[0] = RtpExtension(RtpExtension::kTOffset, kTOFExtensionId); receiver_trace_.PushExpectedLogLine( "WrappingBitrateEstimator: Switching to transmission time offset RBE."); receiver_trace_.PushExpectedLogLine( "RemoteBitrateEstimatorFactory: Instantiating."); streams_.push_back(new Stream(this)); streams_[0]->StopSending(); streams_[1]->StopSending(); EXPECT_EQ(kEventSignaled, receiver_trace_.Wait()); } } // namespace webrtc <|endoftext|>
<commit_before>#include "Sensor/DrawerSensor.h" #include "Data/ForwardData.h" DrawerSensor::DrawerSensor(string port, int baudrate) : Sensor("Drawer Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)), dataMutex(), dataReceived(), dataToForward() { std::lock_guard<std::mutex> lock(dataMutex); if (conn->isConnected()) { char data[256]; int bytesRead = conn->read(data, 256); // Decode the incoming data R2Protocol::Packet params; std::vector<unsigned char> input(data, data + bytesRead); R2Protocol::decode(input, params); if (params.destination == DEVICE_NAME) { // Data is sent here dataReceived[params.source] = params.data; } else { // Data should be forwarded dataToForward[params.destination] = params; } } } DrawerSensor::~DrawerSensor() { } bool DrawerSensor::ping() { return conn->isConnected() == 1; } void DrawerSensor::fillData(smap<void*>& sensorData) { // TODO }<commit_msg>add drawers<commit_after>#include "Sensor/DrawerSensor.h" #include "Data/ForwardData.h" DrawerSensor::DrawerSensor(string port, int baudrate) : Sensor("Drawer Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)), dataMutex(), dataReceived(), dataToForward() { } DrawerSensor::~DrawerSensor() { } bool DrawerSensor::ping() { return conn->isConnected() == 1; } void DrawerSensor::fillData(smap<void*>& sensorData) { }<|endoftext|>
<commit_before>// rm -f galice.root ; aliroot -l -q -b $ALICE_SOURCE/HLT/global/physics/macros/testConfigOnlineCalib.C $ALICE_ROOT/HLT/exa/recraw-local.C'("raw.root","local:///opt/HLT-DEV/HCDB", 23, 23, "HLT", "chains=RootWriter ignore-hltout")' void testConfigOnlineCalib() { AliHLTSystem* pHLT = AliHLTPluginBase::GetInstance(); if (1) { AliHLTConfiguration calib1("myCalibration1", "HLTAnalysisManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3 -MinTracks=5 -QueueDepth=0 AddTaskMacro=$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C(\"TPCCalib:CalibTimeDrift\")"); // AliHLTConfiguration calib2("myCalibration2", "TPCCalibManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3"); AliHLTConfiguration calibmerge("myCalibrationMerger" , "RootObjectMerger" , "myCalibration1" , "-QueueDepth 0 -cumulative"); AliHLTConfiguration preproc("myTPCOfflinePreprocessor" , "TPCOfflinePreprocessorWrapper" , "myCalibrationMerger" , "-QueueDepth 0"); AliHLTConfiguration eventTrigger("myCustomTrigger", "Zero", "TPC-DP", ""); AliHLTConfiguration zmqsink("myZMQsink", "ZMQsink", "myTPCOfflinePreprocessor", "out=PUB@tcp://*:60203"); AliHLTConfiguration zmqsource("myZMQsource", "ZMQsource", "myCustomTrigger", "in=SUB+tcp://localhost:60203"); AliHLTConfiguration mapPrepare1("myMapPrepare1", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 0 -MaxSector 35 -NoInitialObject"); AliHLTConfiguration mapPrepare2("myMapPrepare2", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 36 -MaxSector 71 -NoInitialObject"); AliHLTConfiguration mapPreparemerge("myMapPrepare", "RootObjectMerger", "myMapPrepare1 myMapPrepare2", "-QueueDepth 0"); TString clusterTransformation = "TPC-ClusterTransformation"; AliHLTConfiguration overrideClusterTransformation(clusterTransformation.Data(), "TPCClusterTransformation", "TPC-HWCFDecoder myMapPrepare", "-update-object-on-the-fly"); AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalibrationMerger myTPCOfflinePreprocessor myZMQsink GLOBAL-esd-converter", "-directory testDir -datafile test.root"); } else if (0) { AliHLTConfiguration calib("myCalib", "TPCCalibManagerComponent", "GLOBAL-esd-converter", ""); AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalib", "-directory testDir -datafile test-calib.root"); } else { AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "GLOBAL-esd-converter", "-directory testDir -datafile test-esdevent.root"); } } <commit_msg>fix test macro for online calib<commit_after>// rm -f galice.root ; aliroot -l -q -b $ALICE_SOURCE/HLT/global/physics/macros/testConfigOnlineCalib.C $ALICE_ROOT/HLT/exa/recraw-local.C'("raw.root","local:///opt/HLT-DEV/HCDB", 23, 23, "HLT", "chains=RootWriter ignore-hltout")' void testConfigOnlineCalib() { AliHLTSystem* pHLT = AliHLTPluginBase::GetInstance(); if (1) { AliHLTConfiguration calib1("myCalibration1", "HLTAnalysisManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3 -MinTracks=5 -QueueDepth=0 AddTaskMacro=$ALICE_PHYSICS/PWGPP/CalibMacros/CPass0/AddTaskTPCCalib.C(\"TPCCalib:CalibTimeDrift\")"); // AliHLTConfiguration calib2("myCalibration2", "TPCCalibManagerComponent", "GLOBAL-flat-esd-converter", "-fPushEventModulo=3"); AliHLTConfiguration calibmerge("myCalibrationMerger" , "RootObjectMerger" , "myCalibration1" , "-QueueDepth 0 -cumulative"); AliHLTConfiguration preproc("myTPCOfflinePreprocessor" , "TPCOfflinePreprocessorWrapper" , "myCalibrationMerger" , "-QueueDepth 0"); AliHLTConfiguration eventTrigger("myCustomTrigger", "Zero", "TPC-DP", ""); AliHLTConfiguration zmqsink("myZMQsink", "ZMQsink", "myTPCOfflinePreprocessor", "out=PUB@tcp://*:60203"); AliHLTConfiguration zmqsource("myZMQsource", "ZMQsource", "myCustomTrigger", "in=SUB+tcp://localhost:60203"); AliHLTConfiguration mapPrepare1("myMapPrepare1", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 0 -MaxSector 35 -NoInitialObject"); AliHLTConfiguration mapPrepare2("myMapPrepare2", "TPCClusterTransformationPrepare", "myZMQsource", "-QueueDepth 0 -MinSector 36 -MaxSector 71 -NoInitialObject"); AliHLTConfiguration mapPreparemerge("myMapPrepare", "RootObjectMerger", "myMapPrepare1 myMapPrepare2", "-QueueDepth 0"); TString clusterTransformation = "TPC-ClusterTransformation"; AliHLTConfiguration overrideClusterTransformation(clusterTransformation.Data(), "TPCClusterTransformation", "TPC-HWCFDecoder myMapPrepare", "-update-object-on-the-fly -offline-mode"); AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalibrationMerger myTPCOfflinePreprocessor myZMQsink GLOBAL-esd-converter", "-directory testDir -datafile test.root"); } else if (0) { AliHLTConfiguration calib("myCalib", "TPCCalibManagerComponent", "GLOBAL-esd-converter", ""); AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "myCalib", "-directory testDir -datafile test-calib.root"); } else { AliHLTConfiguration rootWriter("RootWriter", "ROOTFileWriter", "GLOBAL-esd-converter", "-directory testDir -datafile test-esdevent.root"); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTextActor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTextActor.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTextActor, "1.3"); vtkStandardNewMacro(vtkTextActor); // ---------------------------------------------------------------------------- vtkTextActor::vtkTextActor() { // to remain compatible with code using vtkActor2D, we must set // position coord to Viewport, not Normalized Viewport // so...compute equivalent coords for initial position this->PositionCoordinate->SetCoordinateSystemToViewport(); // this->AdjustedPositionCoordinate = vtkCoordinate::New(); this->AdjustedPositionCoordinate->SetCoordinateSystemToNormalizedViewport(); // create default text mapper vtkTextMapper *mapper = vtkTextMapper::New(); this->SetMapper(mapper); mapper->Delete(); // this->LastOrigin[0] = 0; this->LastOrigin[1] = 0; this->LastSize[0] = 0; this->LastSize[1] = 0; this->MinimumSize[0] = 10; this->MinimumSize[1] = 10; this->MaximumLineHeight = 1.0; this->ScaledText = 0; this->AlignmentPoint = 0; } // ---------------------------------------------------------------------------- vtkTextActor::~vtkTextActor() { this->AdjustedPositionCoordinate->Delete(); } // ---------------------------------------------------------------------------- void vtkTextActor::SetMapper(vtkTextMapper *mapper) { // this is the public method this->vtkActor2D::SetMapper( mapper ); } // ---------------------------------------------------------------------------- void vtkTextActor::SetMapper(vtkMapper2D *mapper) { if (mapper->IsA("vtkTextMapper")) { this->SetMapper( (vtkTextMapper *)mapper ); } else { vtkErrorMacro("Must use vtkTextMapper for this class"); } } // ---------------------------------------------------------------------------- void vtkTextActor::ShallowCopy(vtkProp *prop) { vtkTextActor *a = vtkTextActor::SafeDownCast(prop); if ( a != NULL ) { this->SetPosition2(a->GetPosition2()); this->SetMinimumSize(a->GetMinimumSize()); this->SetMaximumLineHeight(a->GetMaximumLineHeight()); this->SetScaledText(a->GetScaledText()); this->SetAlignmentPoint(a->GetAlignmentPoint()); } // Now do superclass (mapper is handled by it as well). this->vtkActor2D::ShallowCopy(prop); } // ---------------------------------------------------------------------------- // Release any graphics resources that are being consumed by this actor. // The parameter window could be used to determine which graphic // resources to release. void vtkTextActor::ReleaseGraphicsResources(vtkWindow *win) { this->vtkActor2D::ReleaseGraphicsResources(win); } // ---------------------------------------------------------------------------- int vtkTextActor::RenderOverlay(vtkViewport *viewport) { // Everything is built in RenderOpaqueGeometry, just have to render this->vtkActor2D::RenderOverlay(viewport); return 1; } // ---------------------------------------------------------------------------- int vtkTextActor::RenderOpaqueGeometry(vtkViewport *viewport) { int size[2]; int fontSize=0, oldfontsize=0; vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (!mapper) { return 0; } // we don't need to do anything additional, just pass the call // right through to the actor if (!this->ScaledText) { int *point1, *point2; float u, v; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; switch (this->AlignmentPoint) { case 0: u = point1[0]; v = point1[1]; break; case 1: u = point1[0] + size[0]/2; v = point1[1]; break; case 2: u = point2[0]; v = point1[1]; break; case 3: u = point1[0]; v = point1[1] + size[1]/2; break; case 4: u = point1[0] + size[0]/2; v = point1[1] + size[1]/2; break; case 5: u = point2[0]; v = point1[1] + size[1]/2; break; case 6: u = point1[0]; v = point2[1]; break; case 7: u = point1[0] + size[0]/2; v = point2[1]; break; case 8: u = point2[0]; v = point2[1]; break; } viewport->ViewportToNormalizedViewport(u, v); this->AdjustedPositionCoordinate->SetValue(u,v); this->vtkActor2D::RenderOpaqueGeometry(viewport); return 1; } // Check to see whether we have to rebuild everything if (viewport->GetMTime() > this->BuildTime || ( viewport->GetVTKWindow() && viewport->GetVTKWindow()->GetMTime() > this->BuildTime ) ) { // if the viewport has changed we may - or may not need // to rebuild, it depends on if the projected coords change int *point1, *point2; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; if (this->LastSize[0] != size[0] || this->LastSize[1] != size[1] || this->LastOrigin[0] != point1[0] || this->LastOrigin[1] != point1[1]) { this->Modified(); } } // Check to see whether we have to rebuild everything if ( this->GetMTime() > this->BuildTime) { vtkDebugMacro(<<"Rebuilding text"); // get the viewport size in display coordinates int *point1, *point2; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; this->LastOrigin[0] = point1[0]; this->LastOrigin[1] = point1[1]; // Lets try to minimize the number of times we change the font size. // If the width of the font box has not changed by more than a pixel // (numerical issues) do not recompute font size. if (this->LastSize[0] < size[0]-1 || this->LastSize[1] < size[1]-1 || this->LastSize[0] > size[0]+1 || this->LastSize[1] > size[1]+1) { this->LastSize[0] = size[0]; this->LastSize[1] = size[1]; // limit by minimum size if (this->MinimumSize[0] > size[0]) { size[0] = this->MinimumSize[0]; } if (this->MinimumSize[1] > size[1]) { size[1] = this->MinimumSize[1]; } // Update all the composing objects // find the best size for the font int tempi[2]; // use the last size as a first guess fontSize = mapper->GetFontSize(); oldfontsize = fontSize; mapper->GetSize(viewport,tempi); int lineMax = (int)(size[1]*this->MaximumLineHeight * mapper->GetNumberOfLines()); // while the size is too small increase it while (tempi[1] < size[1] && tempi[0] < size[0] && tempi[1] < lineMax && fontSize < 100) { fontSize++; mapper->SetFontSize(fontSize); mapper->GetSize(viewport,tempi); } // while the size is too large decrease it while ((tempi[1] > size[1] || tempi[0] > size[0] || tempi[1] > lineMax) && fontSize > 0) { fontSize--; mapper->SetFontSize(fontSize); mapper->GetSize(viewport,tempi); } } if (oldfontsize!=fontSize) { // don't do this after this->BuildTime.Modified(); !!!! this->Modified(); } // now set the position of the Text int fpos[2]; switch (mapper->GetJustification()) { case VTK_TEXT_LEFT: fpos[0] = point1[0]; break; case VTK_TEXT_CENTERED: fpos[0] = point1[0] + size[0]/2; break; case VTK_TEXT_RIGHT: fpos[0] = point1[0]+size[0]; break; } switch (mapper->GetVerticalJustification()) { case VTK_TEXT_TOP: fpos[1] = point1[1] + size[1]; break; case VTK_TEXT_CENTERED: fpos[1] = point1[1] + size[1]/2; break; case VTK_TEXT_BOTTOM: fpos[1] = point1[1]; break; } float u = fpos[0], v = fpos[1]; viewport->ViewportToNormalizedViewport(u, v); this->AdjustedPositionCoordinate->SetValue(u,v); this->BuildTime.Modified(); } // Everything is built, just have to render this->vtkActor2D::RenderOpaqueGeometry(viewport); return 1; } // ---------------------------------------------------------------------------- void vtkTextActor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "MaximumLineHeight: " << this->MaximumLineHeight << endl; os << indent << "MinimumSize: " << this->MinimumSize[0] << " " << this->MinimumSize[1] << endl; } // ---------------------------------------------------------------------------- #define SetStuffMacro(function,param) \ vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); \ if (!mapper) { return; } \ unsigned long mtime1 = mapper->GetMTime(); \ mapper->Set##function(param); \ unsigned long mtime2 = mapper->GetMTime(); \ if (mtime1 != mtime2) \ { \ this->Modified(); \ } #define GetStuffMacro(function,default) \ vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); \ if (!mapper) { return default; } \ return mapper->Get##function(); \ void vtkTextActor::SetInput(const char *inputString) { SetStuffMacro(Input,inputString); } // ---------------------------------------------------------------------------- char *vtkTextActor::GetInput(void) { GetStuffMacro(Input,NULL); } // ---------------------------------------------------------------------------- void vtkTextActor::SetFontSize(int size) { SetStuffMacro(FontSize,size); } // ---------------------------------------------------------------------------- int vtkTextActor::GetFontSize(void) { GetStuffMacro(FontSize,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetBold(int val) { SetStuffMacro(Bold,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetBold(void) { GetStuffMacro(Bold,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetItalic(int val) { SetStuffMacro(Italic,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetItalic(void) { GetStuffMacro(Italic,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetShadow(int val) { SetStuffMacro(Shadow,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetShadow(void) { GetStuffMacro(Shadow,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetFontFamily(int val) { SetStuffMacro(FontFamily,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetFontFamily(void) { GetStuffMacro(FontFamily,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetJustification(int val) { SetStuffMacro(Justification,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetJustification(void) { GetStuffMacro(Justification,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetVerticalJustification(int val) { SetStuffMacro(VerticalJustification,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetVerticalJustification(void) { GetStuffMacro(VerticalJustification,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetLineOffset(float val) { SetStuffMacro(LineOffset,val); } // ---------------------------------------------------------------------------- float vtkTextActor::GetLineOffset(void) { GetStuffMacro(LineOffset,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetLineSpacing(float val) { SetStuffMacro(LineSpacing,val); } // ---------------------------------------------------------------------------- float vtkTextActor::GetLineSpacing(void) { GetStuffMacro(LineSpacing,0); } // ---------------------------------------------------------------------------- int vtkTextActor::GetNumberOfLines(const char *input) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetNumberOfLines(input); } else { return 0; } } // ---------------------------------------------------------------------------- int vtkTextActor::GetNumberOfLines(void) { GetStuffMacro(NumberOfLines,0); } // ---------------------------------------------------------------------------- void vtkTextActor::GetSize(vtkViewport *v, int size[2]) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { mapper->GetSize(v, size); } } // ---------------------------------------------------------------------------- int vtkTextActor::GetWidth(vtkViewport*v) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetWidth(v); } else { return 0; } } // ---------------------------------------------------------------------------- int vtkTextActor::GetHeight(vtkViewport*v) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetHeight(v); } else { return 0; } } <commit_msg>ERR: Printself Defects<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTextActor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTextActor.h" #include "vtkObjectFactory.h" vtkCxxRevisionMacro(vtkTextActor, "1.4"); vtkStandardNewMacro(vtkTextActor); // ---------------------------------------------------------------------------- vtkTextActor::vtkTextActor() { // to remain compatible with code using vtkActor2D, we must set // position coord to Viewport, not Normalized Viewport // so...compute equivalent coords for initial position this->PositionCoordinate->SetCoordinateSystemToViewport(); // this->AdjustedPositionCoordinate = vtkCoordinate::New(); this->AdjustedPositionCoordinate->SetCoordinateSystemToNormalizedViewport(); // create default text mapper vtkTextMapper *mapper = vtkTextMapper::New(); this->SetMapper(mapper); mapper->Delete(); // this->LastOrigin[0] = 0; this->LastOrigin[1] = 0; this->LastSize[0] = 0; this->LastSize[1] = 0; this->MinimumSize[0] = 10; this->MinimumSize[1] = 10; this->MaximumLineHeight = 1.0; this->ScaledText = 0; this->AlignmentPoint = 0; } // ---------------------------------------------------------------------------- vtkTextActor::~vtkTextActor() { this->AdjustedPositionCoordinate->Delete(); } // ---------------------------------------------------------------------------- void vtkTextActor::SetMapper(vtkTextMapper *mapper) { // this is the public method this->vtkActor2D::SetMapper( mapper ); } // ---------------------------------------------------------------------------- void vtkTextActor::SetMapper(vtkMapper2D *mapper) { if (mapper->IsA("vtkTextMapper")) { this->SetMapper( (vtkTextMapper *)mapper ); } else { vtkErrorMacro("Must use vtkTextMapper for this class"); } } // ---------------------------------------------------------------------------- void vtkTextActor::ShallowCopy(vtkProp *prop) { vtkTextActor *a = vtkTextActor::SafeDownCast(prop); if ( a != NULL ) { this->SetPosition2(a->GetPosition2()); this->SetMinimumSize(a->GetMinimumSize()); this->SetMaximumLineHeight(a->GetMaximumLineHeight()); this->SetScaledText(a->GetScaledText()); this->SetAlignmentPoint(a->GetAlignmentPoint()); } // Now do superclass (mapper is handled by it as well). this->vtkActor2D::ShallowCopy(prop); } // ---------------------------------------------------------------------------- // Release any graphics resources that are being consumed by this actor. // The parameter window could be used to determine which graphic // resources to release. void vtkTextActor::ReleaseGraphicsResources(vtkWindow *win) { this->vtkActor2D::ReleaseGraphicsResources(win); } // ---------------------------------------------------------------------------- int vtkTextActor::RenderOverlay(vtkViewport *viewport) { // Everything is built in RenderOpaqueGeometry, just have to render this->vtkActor2D::RenderOverlay(viewport); return 1; } // ---------------------------------------------------------------------------- int vtkTextActor::RenderOpaqueGeometry(vtkViewport *viewport) { int size[2]; int fontSize=0, oldfontsize=0; vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (!mapper) { return 0; } // we don't need to do anything additional, just pass the call // right through to the actor if (!this->ScaledText) { int *point1, *point2; float u, v; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; switch (this->AlignmentPoint) { case 0: u = point1[0]; v = point1[1]; break; case 1: u = point1[0] + size[0]/2; v = point1[1]; break; case 2: u = point2[0]; v = point1[1]; break; case 3: u = point1[0]; v = point1[1] + size[1]/2; break; case 4: u = point1[0] + size[0]/2; v = point1[1] + size[1]/2; break; case 5: u = point2[0]; v = point1[1] + size[1]/2; break; case 6: u = point1[0]; v = point2[1]; break; case 7: u = point1[0] + size[0]/2; v = point2[1]; break; case 8: u = point2[0]; v = point2[1]; break; } viewport->ViewportToNormalizedViewport(u, v); this->AdjustedPositionCoordinate->SetValue(u,v); this->vtkActor2D::RenderOpaqueGeometry(viewport); return 1; } // Check to see whether we have to rebuild everything if (viewport->GetMTime() > this->BuildTime || ( viewport->GetVTKWindow() && viewport->GetVTKWindow()->GetMTime() > this->BuildTime ) ) { // if the viewport has changed we may - or may not need // to rebuild, it depends on if the projected coords change int *point1, *point2; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; if (this->LastSize[0] != size[0] || this->LastSize[1] != size[1] || this->LastOrigin[0] != point1[0] || this->LastOrigin[1] != point1[1]) { this->Modified(); } } // Check to see whether we have to rebuild everything if ( this->GetMTime() > this->BuildTime) { vtkDebugMacro(<<"Rebuilding text"); // get the viewport size in display coordinates int *point1, *point2; point1 = this->PositionCoordinate->GetComputedViewportValue(viewport); point2 = this->Position2Coordinate->GetComputedViewportValue(viewport); size[0] = point2[0] - point1[0]; size[1] = point2[1] - point1[1]; this->LastOrigin[0] = point1[0]; this->LastOrigin[1] = point1[1]; // Lets try to minimize the number of times we change the font size. // If the width of the font box has not changed by more than a pixel // (numerical issues) do not recompute font size. if (this->LastSize[0] < size[0]-1 || this->LastSize[1] < size[1]-1 || this->LastSize[0] > size[0]+1 || this->LastSize[1] > size[1]+1) { this->LastSize[0] = size[0]; this->LastSize[1] = size[1]; // limit by minimum size if (this->MinimumSize[0] > size[0]) { size[0] = this->MinimumSize[0]; } if (this->MinimumSize[1] > size[1]) { size[1] = this->MinimumSize[1]; } // Update all the composing objects // find the best size for the font int tempi[2]; // use the last size as a first guess fontSize = mapper->GetFontSize(); oldfontsize = fontSize; mapper->GetSize(viewport,tempi); int lineMax = (int)(size[1]*this->MaximumLineHeight * mapper->GetNumberOfLines()); // while the size is too small increase it while (tempi[1] < size[1] && tempi[0] < size[0] && tempi[1] < lineMax && fontSize < 100) { fontSize++; mapper->SetFontSize(fontSize); mapper->GetSize(viewport,tempi); } // while the size is too large decrease it while ((tempi[1] > size[1] || tempi[0] > size[0] || tempi[1] > lineMax) && fontSize > 0) { fontSize--; mapper->SetFontSize(fontSize); mapper->GetSize(viewport,tempi); } } if (oldfontsize!=fontSize) { // don't do this after this->BuildTime.Modified(); !!!! this->Modified(); } // now set the position of the Text int fpos[2]; switch (mapper->GetJustification()) { case VTK_TEXT_LEFT: fpos[0] = point1[0]; break; case VTK_TEXT_CENTERED: fpos[0] = point1[0] + size[0]/2; break; case VTK_TEXT_RIGHT: fpos[0] = point1[0]+size[0]; break; } switch (mapper->GetVerticalJustification()) { case VTK_TEXT_TOP: fpos[1] = point1[1] + size[1]; break; case VTK_TEXT_CENTERED: fpos[1] = point1[1] + size[1]/2; break; case VTK_TEXT_BOTTOM: fpos[1] = point1[1]; break; } float u = fpos[0], v = fpos[1]; viewport->ViewportToNormalizedViewport(u, v); this->AdjustedPositionCoordinate->SetValue(u,v); this->BuildTime.Modified(); } // Everything is built, just have to render this->vtkActor2D::RenderOpaqueGeometry(viewport); return 1; } // ---------------------------------------------------------------------------- void vtkTextActor::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "MaximumLineHeight: " << this->MaximumLineHeight << endl; os << indent << "MinimumSize: " << this->MinimumSize[0] << " " << this->MinimumSize[1] << endl; os << indent << "ScaledText: " << this->ScaledText << endl; os << indent << "AlignmentPoint: " << this->AlignmentPoint << endl; } // ---------------------------------------------------------------------------- #define SetStuffMacro(function,param) \ vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); \ if (!mapper) { return; } \ unsigned long mtime1 = mapper->GetMTime(); \ mapper->Set##function(param); \ unsigned long mtime2 = mapper->GetMTime(); \ if (mtime1 != mtime2) \ { \ this->Modified(); \ } #define GetStuffMacro(function,default) \ vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); \ if (!mapper) { return default; } \ return mapper->Get##function(); \ void vtkTextActor::SetInput(const char *inputString) { SetStuffMacro(Input,inputString); } // ---------------------------------------------------------------------------- char *vtkTextActor::GetInput(void) { GetStuffMacro(Input,NULL); } // ---------------------------------------------------------------------------- void vtkTextActor::SetFontSize(int size) { SetStuffMacro(FontSize,size); } // ---------------------------------------------------------------------------- int vtkTextActor::GetFontSize(void) { GetStuffMacro(FontSize,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetBold(int val) { SetStuffMacro(Bold,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetBold(void) { GetStuffMacro(Bold,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetItalic(int val) { SetStuffMacro(Italic,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetItalic(void) { GetStuffMacro(Italic,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetShadow(int val) { SetStuffMacro(Shadow,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetShadow(void) { GetStuffMacro(Shadow,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetFontFamily(int val) { SetStuffMacro(FontFamily,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetFontFamily(void) { GetStuffMacro(FontFamily,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetJustification(int val) { SetStuffMacro(Justification,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetJustification(void) { GetStuffMacro(Justification,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetVerticalJustification(int val) { SetStuffMacro(VerticalJustification,val); } // ---------------------------------------------------------------------------- int vtkTextActor::GetVerticalJustification(void) { GetStuffMacro(VerticalJustification,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetLineOffset(float val) { SetStuffMacro(LineOffset,val); } // ---------------------------------------------------------------------------- float vtkTextActor::GetLineOffset(void) { GetStuffMacro(LineOffset,0); } // ---------------------------------------------------------------------------- void vtkTextActor::SetLineSpacing(float val) { SetStuffMacro(LineSpacing,val); } // ---------------------------------------------------------------------------- float vtkTextActor::GetLineSpacing(void) { GetStuffMacro(LineSpacing,0); } // ---------------------------------------------------------------------------- int vtkTextActor::GetNumberOfLines(const char *input) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetNumberOfLines(input); } else { return 0; } } // ---------------------------------------------------------------------------- int vtkTextActor::GetNumberOfLines(void) { GetStuffMacro(NumberOfLines,0); } // ---------------------------------------------------------------------------- void vtkTextActor::GetSize(vtkViewport *v, int size[2]) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { mapper->GetSize(v, size); } } // ---------------------------------------------------------------------------- int vtkTextActor::GetWidth(vtkViewport*v) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetWidth(v); } else { return 0; } } // ---------------------------------------------------------------------------- int vtkTextActor::GetHeight(vtkViewport*v) { vtkTextMapper *mapper = (vtkTextMapper *)this->GetMapper(); if (mapper) { return mapper->GetHeight(v); } else { return 0; } } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "abstractmediaplayer.h" #include "defs.h" #include "utils.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- const int NullMaxVolume = -1; //----------------------------------------------------------------------------- // Constructor / destructor //----------------------------------------------------------------------------- MMF::AbstractMediaPlayer::AbstractMediaPlayer() : m_state(GroundState) , m_error(NoError) , m_playPending(false) , m_tickTimer(new QTimer(this)) , m_volume(InitialVolume) , m_mmfMaxVolume(NullMaxVolume) { connect(m_tickTimer.data(), SIGNAL(timeout()), this, SLOT(tick())); } MMF::AbstractMediaPlayer::AbstractMediaPlayer(const AbstractPlayer& player) : AbstractPlayer(player) , m_state(GroundState) , m_error(NoError) , m_playPending(false) , m_tickTimer(new QTimer(this)) , m_volume(InitialVolume) , m_mmfMaxVolume(NullMaxVolume) { connect(m_tickTimer.data(), SIGNAL(timeout()), this, SLOT(tick())); } MMF::AbstractMediaPlayer::~AbstractMediaPlayer() { } //----------------------------------------------------------------------------- // MediaObjectInterface //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::play() { TRACE_CONTEXT(AbstractMediaPlayer::play, EAudioApi); TRACE_ENTRY("state %d", m_state); switch (m_state) { case GroundState: // Is this the correct error? Really we want 'NotReadyError' m_error = NormalError; changeState(ErrorState); break; case LoadingState: m_playPending = true; break; case StoppedState: case PausedState: doPlay(); startTickTimer(); changeState(PlayingState); break; case PlayingState: case BufferingState: case ErrorState: // Do nothing break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::pause() { TRACE_CONTEXT(AbstractMediaPlayer::pause, EAudioApi); TRACE_ENTRY("state %d", m_state); m_playPending = false; switch (m_state) { case GroundState: case LoadingState: case StoppedState: case PausedState: case ErrorState: // Do nothing break; case PlayingState: case BufferingState: doPause(); stopTickTimer(); changeState(PausedState); break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::stop() { TRACE_CONTEXT(AbstractMediaPlayer::stop, EAudioApi); TRACE_ENTRY("state %d", m_state); m_playPending = false; switch (m_state) { case GroundState: case LoadingState: case StoppedState: case ErrorState: // Do nothing break; case PlayingState: case BufferingState: case PausedState: doStop(); stopTickTimer(); changeState(StoppedState); break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::seek(qint64 ms) { TRACE_CONTEXT(AbstractMediaPlayer::seek, EAudioApi); TRACE_ENTRY("state %d pos %Ld", state(), ms); // TODO: put a state guard in here const bool tickTimerWasRunning = m_tickTimer->isActive(); stopTickTimer(); doSeek(ms); if (tickTimerWasRunning) { startTickTimer(); } TRACE_EXIT_0(); } bool MMF::AbstractMediaPlayer::isSeekable() const { return true; } void MMF::AbstractMediaPlayer::doSetTickInterval(qint32 interval) { TRACE_CONTEXT(AbstractMediaPlayer::doSetTickInterval, EAudioApi); TRACE_ENTRY("state %d m_interval %d interval %d", m_state, tickInterval(), interval); m_tickTimer->setInterval(interval); TRACE_EXIT_0(); } Phonon::ErrorType MMF::AbstractMediaPlayer::errorType() const { const Phonon::ErrorType result = (ErrorState == m_state) ? m_error : NoError; return result; } QString MMF::AbstractMediaPlayer::errorString() const { // TODO: put in proper error strings QString result; return result; } Phonon::State MMF::AbstractMediaPlayer::state() const { return phononState(m_state); } MediaSource MMF::AbstractMediaPlayer::source() const { return m_source; } void MMF::AbstractMediaPlayer::setFileSource(const MediaSource &source, RFile& file) { TRACE_CONTEXT(AbstractMediaPlayer::setFileSource, EAudioApi); TRACE_ENTRY("state %d source.type %d", m_state, source.type()); close(); changeState(GroundState); // TODO: is it correct to assign even if the media type is not supported in // the switch statement below? m_source = source; TInt symbianErr = KErrNone; switch (m_source.type()) { case MediaSource::LocalFile: { // TODO: work out whose responsibility it is to ensure that paths // are Symbian-style, i.e. have backslashes for path delimiters. // Until then, use this utility function... //const QHBufC filename = Utils::symbianFilename(m_source.fileName()); //TRAP(symbianErr, m_player->OpenFileL(*filename)); // Open using shared filehandle // This is a temporary hack to work around KErrInUse from MMF // client utility OpenFileL calls //TRAP(symbianErr, m_player->OpenFileL(file)); symbianErr = openFile(file); break; } case MediaSource::Url: { TRACE_0("Source type not supported"); // TODO: support opening URLs symbianErr = KErrNotSupported; break; } case MediaSource::Invalid: case MediaSource::Disc: case MediaSource::Stream: TRACE_0("Source type not supported"); symbianErr = KErrNotSupported; break; case MediaSource::Empty: TRACE_0("Empty source - doing nothing"); TRACE_EXIT_0(); return; // Protection against adding new media types and forgetting to update this switch default: TRACE_PANIC(InvalidMediaTypePanic); } if (KErrNone == symbianErr) { changeState(LoadingState); } else { TRACE("error %d", symbianErr) // TODO: do something with the value of symbianErr? m_error = NormalError; changeState(ErrorState); } TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::setNextSource(const MediaSource &source) { TRACE_CONTEXT(AbstractMediaPlayer::setNextSource, EAudioApi); TRACE_ENTRY("state %d", m_state); // TODO: handle 'next source' m_nextSource = source; Q_UNUSED(source); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // VolumeObserver //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::volumeChanged(qreal volume) { TRACE_CONTEXT(AbstractMediaPlayer::volumeChanged, EAudioInternal); TRACE_ENTRY("state %d", m_state); m_volume = volume; doVolumeChanged(); TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::doVolumeChanged() { switch (m_state) { case GroundState: case LoadingState: case ErrorState: // Do nothing break; case StoppedState: case PausedState: case PlayingState: case BufferingState: { const int err = setDeviceVolume(m_volume * m_mmfMaxVolume); if (KErrNone != err) { m_error = NormalError; changeState(ErrorState); } break; } // Protection against adding new states and forgetting to update this // switch default: Utils::panic(InvalidStatePanic); } } //----------------------------------------------------------------------------- // Protected functions //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::startTickTimer() { m_tickTimer->start(tickInterval()); } void MMF::AbstractMediaPlayer::stopTickTimer() { m_tickTimer->stop(); } void MMF::AbstractMediaPlayer::maxVolumeChanged(int mmfMaxVolume) { m_mmfMaxVolume = mmfMaxVolume; doVolumeChanged(); } Phonon::State MMF::AbstractMediaPlayer::phononState() const { return phononState(m_state); } Phonon::State MMF::AbstractMediaPlayer::phononState(PrivateState state) { const Phonon::State phononState = GroundState == state ? Phonon::LoadingState : static_cast<Phonon::State>(state); return phononState; } void MMF::AbstractMediaPlayer::changeState(PrivateState newState) { TRACE_CONTEXT(AbstractMediaPlayer::changeState, EAudioInternal); TRACE_ENTRY("state %d newState %d", m_state, newState); // TODO: add some invariants to check that the transition is valid const Phonon::State oldPhononState = phononState(m_state); const Phonon::State newPhononState = phononState(newState); if (oldPhononState != newPhononState) { TRACE("emit stateChanged(%d, %d)", newPhononState, oldPhononState); emit stateChanged(newPhononState, oldPhononState); } m_state = newState; // Check whether play() was called while clip was being loaded. If so, // playback should be started now if ( LoadingState == oldPhononState and StoppedState == newPhononState and m_playPending ) { TRACE_0("play was called while loading; starting playback now"); m_playPending = false; play(); } TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::setError(Phonon::ErrorType error) { TRACE_CONTEXT(AbstractMediaPlayer::setError, EAudioInternal); TRACE_ENTRY("state %d error %d", m_state, error); m_error = error; changeState(ErrorState); TRACE_EXIT_0(); } qint64 MMF::AbstractMediaPlayer::toMilliSeconds(const TTimeIntervalMicroSeconds &in) { return in.Int64() / 1000; } //----------------------------------------------------------------------------- // Slots //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::tick() { // For the MWC compiler, we need to qualify the base class. emit MMF::AbstractPlayer::tick(currentTime()); } QT_END_NAMESPACE <commit_msg>Invoke on appropriate states in seek().<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include "abstractmediaplayer.h" #include "defs.h" #include "utils.h" QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- const int NullMaxVolume = -1; //----------------------------------------------------------------------------- // Constructor / destructor //----------------------------------------------------------------------------- MMF::AbstractMediaPlayer::AbstractMediaPlayer() : m_state(GroundState) , m_error(NoError) , m_playPending(false) , m_tickTimer(new QTimer(this)) , m_volume(InitialVolume) , m_mmfMaxVolume(NullMaxVolume) { connect(m_tickTimer.data(), SIGNAL(timeout()), this, SLOT(tick())); } MMF::AbstractMediaPlayer::AbstractMediaPlayer(const AbstractPlayer& player) : AbstractPlayer(player) , m_state(GroundState) , m_error(NoError) , m_playPending(false) , m_tickTimer(new QTimer(this)) , m_volume(InitialVolume) , m_mmfMaxVolume(NullMaxVolume) { connect(m_tickTimer.data(), SIGNAL(timeout()), this, SLOT(tick())); } MMF::AbstractMediaPlayer::~AbstractMediaPlayer() { } //----------------------------------------------------------------------------- // MediaObjectInterface //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::play() { TRACE_CONTEXT(AbstractMediaPlayer::play, EAudioApi); TRACE_ENTRY("state %d", m_state); switch (m_state) { case GroundState: // Is this the correct error? Really we want 'NotReadyError' m_error = NormalError; changeState(ErrorState); break; case LoadingState: m_playPending = true; break; case StoppedState: case PausedState: doPlay(); startTickTimer(); changeState(PlayingState); break; case PlayingState: case BufferingState: case ErrorState: // Do nothing break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::pause() { TRACE_CONTEXT(AbstractMediaPlayer::pause, EAudioApi); TRACE_ENTRY("state %d", m_state); m_playPending = false; switch (m_state) { case GroundState: case LoadingState: case StoppedState: case PausedState: case ErrorState: // Do nothing break; case PlayingState: case BufferingState: doPause(); stopTickTimer(); changeState(PausedState); break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::stop() { TRACE_CONTEXT(AbstractMediaPlayer::stop, EAudioApi); TRACE_ENTRY("state %d", m_state); m_playPending = false; switch (m_state) { case GroundState: case LoadingState: case StoppedState: case ErrorState: // Do nothing break; case PlayingState: case BufferingState: case PausedState: doStop(); stopTickTimer(); changeState(StoppedState); break; // Protection against adding new states and forgetting to update this switch default: TRACE_PANIC(InvalidStatePanic); } TRACE_EXIT("state %d", m_state); } void MMF::AbstractMediaPlayer::seek(qint64 ms) { TRACE_CONTEXT(AbstractMediaPlayer::seek, EAudioApi); TRACE_ENTRY("state %d pos %Ld", state(), ms); switch (m_state) { // Fallthrough all these case GroundState: case StoppedState: case PausedState: case PlayingState: case LoadingState: { const bool tickTimerWasRunning = m_tickTimer->isActive(); stopTickTimer(); doSeek(ms); if (tickTimerWasRunning) { startTickTimer(); } break; } case BufferingState: // Fallthrough case ErrorState: // Do nothing break; } TRACE_EXIT_0(); } bool MMF::AbstractMediaPlayer::isSeekable() const { return true; } void MMF::AbstractMediaPlayer::doSetTickInterval(qint32 interval) { TRACE_CONTEXT(AbstractMediaPlayer::doSetTickInterval, EAudioApi); TRACE_ENTRY("state %d m_interval %d interval %d", m_state, tickInterval(), interval); m_tickTimer->setInterval(interval); TRACE_EXIT_0(); } Phonon::ErrorType MMF::AbstractMediaPlayer::errorType() const { const Phonon::ErrorType result = (ErrorState == m_state) ? m_error : NoError; return result; } QString MMF::AbstractMediaPlayer::errorString() const { // TODO: put in proper error strings QString result; return result; } Phonon::State MMF::AbstractMediaPlayer::state() const { return phononState(m_state); } MediaSource MMF::AbstractMediaPlayer::source() const { return m_source; } void MMF::AbstractMediaPlayer::setFileSource(const MediaSource &source, RFile& file) { TRACE_CONTEXT(AbstractMediaPlayer::setFileSource, EAudioApi); TRACE_ENTRY("state %d source.type %d", m_state, source.type()); close(); changeState(GroundState); // TODO: is it correct to assign even if the media type is not supported in // the switch statement below? m_source = source; TInt symbianErr = KErrNone; switch (m_source.type()) { case MediaSource::LocalFile: { // TODO: work out whose responsibility it is to ensure that paths // are Symbian-style, i.e. have backslashes for path delimiters. // Until then, use this utility function... //const QHBufC filename = Utils::symbianFilename(m_source.fileName()); //TRAP(symbianErr, m_player->OpenFileL(*filename)); // Open using shared filehandle // This is a temporary hack to work around KErrInUse from MMF // client utility OpenFileL calls //TRAP(symbianErr, m_player->OpenFileL(file)); symbianErr = openFile(file); break; } case MediaSource::Url: { TRACE_0("Source type not supported"); // TODO: support opening URLs symbianErr = KErrNotSupported; break; } case MediaSource::Invalid: case MediaSource::Disc: case MediaSource::Stream: TRACE_0("Source type not supported"); symbianErr = KErrNotSupported; break; case MediaSource::Empty: TRACE_0("Empty source - doing nothing"); TRACE_EXIT_0(); return; // Protection against adding new media types and forgetting to update this switch default: TRACE_PANIC(InvalidMediaTypePanic); } if (KErrNone == symbianErr) { changeState(LoadingState); } else { TRACE("error %d", symbianErr) // TODO: do something with the value of symbianErr? m_error = NormalError; changeState(ErrorState); } TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::setNextSource(const MediaSource &source) { TRACE_CONTEXT(AbstractMediaPlayer::setNextSource, EAudioApi); TRACE_ENTRY("state %d", m_state); // TODO: handle 'next source' m_nextSource = source; Q_UNUSED(source); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // VolumeObserver //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::volumeChanged(qreal volume) { TRACE_CONTEXT(AbstractMediaPlayer::volumeChanged, EAudioInternal); TRACE_ENTRY("state %d", m_state); m_volume = volume; doVolumeChanged(); TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::doVolumeChanged() { switch (m_state) { case GroundState: case LoadingState: case ErrorState: // Do nothing break; case StoppedState: case PausedState: case PlayingState: case BufferingState: { const int err = setDeviceVolume(m_volume * m_mmfMaxVolume); if (KErrNone != err) { m_error = NormalError; changeState(ErrorState); } break; } // Protection against adding new states and forgetting to update this // switch default: Utils::panic(InvalidStatePanic); } } //----------------------------------------------------------------------------- // Protected functions //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::startTickTimer() { m_tickTimer->start(tickInterval()); } void MMF::AbstractMediaPlayer::stopTickTimer() { m_tickTimer->stop(); } void MMF::AbstractMediaPlayer::maxVolumeChanged(int mmfMaxVolume) { m_mmfMaxVolume = mmfMaxVolume; doVolumeChanged(); } Phonon::State MMF::AbstractMediaPlayer::phononState() const { return phononState(m_state); } Phonon::State MMF::AbstractMediaPlayer::phononState(PrivateState state) { const Phonon::State phononState = GroundState == state ? Phonon::LoadingState : static_cast<Phonon::State>(state); return phononState; } void MMF::AbstractMediaPlayer::changeState(PrivateState newState) { TRACE_CONTEXT(AbstractMediaPlayer::changeState, EAudioInternal); TRACE_ENTRY("state %d newState %d", m_state, newState); // TODO: add some invariants to check that the transition is valid const Phonon::State oldPhononState = phononState(m_state); const Phonon::State newPhononState = phononState(newState); if (oldPhononState != newPhononState) { TRACE("emit stateChanged(%d, %d)", newPhononState, oldPhononState); emit stateChanged(newPhononState, oldPhononState); } m_state = newState; // Check whether play() was called while clip was being loaded. If so, // playback should be started now if ( LoadingState == oldPhononState and StoppedState == newPhononState and m_playPending ) { TRACE_0("play was called while loading; starting playback now"); m_playPending = false; play(); } TRACE_EXIT_0(); } void MMF::AbstractMediaPlayer::setError(Phonon::ErrorType error) { TRACE_CONTEXT(AbstractMediaPlayer::setError, EAudioInternal); TRACE_ENTRY("state %d error %d", m_state, error); m_error = error; changeState(ErrorState); TRACE_EXIT_0(); } qint64 MMF::AbstractMediaPlayer::toMilliSeconds(const TTimeIntervalMicroSeconds &in) { return in.Int64() / 1000; } //----------------------------------------------------------------------------- // Slots //----------------------------------------------------------------------------- void MMF::AbstractMediaPlayer::tick() { // For the MWC compiler, we need to qualify the base class. emit MMF::AbstractPlayer::tick(currentTime()); } QT_END_NAMESPACE <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP #define STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <vector> namespace stan { namespace math { // real[] to_array_1d(matrix) // real[] to_array_1d(row_vector) // real[] to_array_1d(vector) template <typename T, int R, int C> inline std::vector<T> to_array_1d(const Eigen::Matrix<T, R, C>& matrix) { const T* datap = matrix.data(); int size = matrix.size(); std::vector<T> result(size); for (int i = 0; i < size; i++) result[i] = datap[i]; return result; } // real[] to_array_1d(...) template <typename T> inline std::vector<T> to_array_1d(const std::vector<T>& x) { return x; } // real[] to_array_1d(...) template <typename T> inline std::vector<typename scalar_type<T>::type> to_array_1d( const std::vector<std::vector<T> >& x) { size_t size1 = x.size(); size_t size2 = 0; if (size1 != 0) size2 = x[0].size(); std::vector<T> y(size1 * size2); for (size_t i = 0, ij = 0; i < size1; i++) for (size_t j = 0; j < size2; j++, ij++) y[ij] = x[i][j]; return to_array_1d(y); } } // namespace math } // namespace stan #endif <commit_msg>meta include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP #define STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <vector> namespace stan { namespace math { // real[] to_array_1d(matrix) // real[] to_array_1d(row_vector) // real[] to_array_1d(vector) template <typename T, int R, int C> inline std::vector<T> to_array_1d(const Eigen::Matrix<T, R, C>& matrix) { const T* datap = matrix.data(); int size = matrix.size(); std::vector<T> result(size); for (int i = 0; i < size; i++) result[i] = datap[i]; return result; } // real[] to_array_1d(...) template <typename T> inline std::vector<T> to_array_1d(const std::vector<T>& x) { return x; } // real[] to_array_1d(...) template <typename T> inline std::vector<typename scalar_type<T>::type> to_array_1d( const std::vector<std::vector<T> >& x) { size_t size1 = x.size(); size_t size2 = 0; if (size1 != 0) size2 = x[0].size(); std::vector<T> y(size1 * size2); for (size_t i = 0, ij = 0; i < size1; i++) for (size_t j = 0; j < size2; j++, ij++) y[ij] = x[i][j]; return to_array_1d(y); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/*****************************************************************************/ /** * @file MarchingPrismTable.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id$ */ /*****************************************************************************/ #include "MarchingPrismTable.h" namespace kvs { namespace MarchingPrismTable { const int TriangleID[64][10] = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, // 0 { 0, 6, 2,-1,-1,-1,-1,-1,-1,-1}, // 1 { 0, 1, 7,-1,-1,-1,-1,-1,-1,-1}, // 2 { 1, 6, 2, 1, 7, 6,-1,-1,-1,-1}, // 3 { 1, 2, 8,-1,-1,-1,-1,-1,-1,-1}, // 4 { 0, 1, 6, 1, 8, 6,-1,-1,-1,-1}, // 5 { 0, 2, 7, 2, 8, 7,-1,-1,-1,-1}, // 6 { 6, 8, 7,-1,-1,-1,-1,-1,-1,-1}, // 7 { 3, 5, 6,-1,-1,-1,-1,-1,-1,-1}, // 8 { 0, 3, 5, 0, 5, 2,-1,-1,-1,-1}, // 9 { 0, 1, 7, 3, 5, 6,-1,-1,-1,-1}, // 10 { 1, 5, 2, 1, 7, 5, 3, 5, 7,-1}, // 11 { 1, 2, 8, 3, 5, 6,-1,-1,-1,-1}, // 12 { 0, 3, 5, 0, 5, 1, 1, 5, 8,-1}, // 13 { 0, 2, 7, 2, 8, 7, 3, 5, 6,-1}, // 14 { 3, 5, 7, 5, 8, 7,-1,-1,-1,-1}, // 15 { 3, 7, 4,-1,-1,-1,-1,-1,-1,-1}, // 16 { 0, 6, 2, 3, 7, 4,-1,-1,-1,-1}, // 17 { 0, 1, 3, 1, 4, 3,-1,-1,-1,-1}, // 18 { 2, 3, 6, 2, 4, 3, 1, 4, 2,-1}, // 19 { 3, 7, 4, 2, 8, 1,-1,-1,-1,-1}, // 20 { 0, 6, 1, 1, 6, 8, 3, 7, 4,-1}, // 21 { 0, 2, 3, 2, 8, 3, 3, 8, 4,-1}, // 22 { 3, 6, 8, 3, 8, 4,-1,-1,-1,-1}, // 23 { 5, 6, 7, 4, 5, 7,-1,-1,-1,-1}, // 24 { 0, 7, 2, 2, 7, 5, 4, 5, 7,-1}, // 25 { 0, 5, 6, 0, 1, 5, 1, 4, 5,-1}, // 26 { 1, 5, 2, 1, 4, 5,-1,-1,-1,-1}, // 27 { 5, 6, 7, 4, 5, 7, 1, 2, 8,-1}, // 28 { 0, 7, 1, 4, 5, 8,-1,-1,-1,-1}, // 29 { 0, 2, 6, 4, 5, 8,-1,-1,-1,-1}, // 30 { 4, 5, 8,-1,-1,-1,-1,-1,-1,-1}, // 31 { 4, 8, 5,-1,-1,-1,-1,-1,-1,-1}, // 32 { 0, 6, 2, 4, 8, 5,-1,-1,-1,-1}, // 33 { 0, 1, 7, 4, 8, 5,-1,-1,-1,-1}, // 34 { 1, 6, 2, 1, 7, 6, 4, 8, 5,-1}, // 35 { 1, 2, 5, 1, 5, 4,-1,-1,-1,-1}, // 36 { 0, 5, 1, 1, 5, 4, 0, 6, 5,-1}, // 37 { 0, 2, 7, 2, 5, 7, 4, 7, 5,-1}, // 38 { 5, 7, 6, 4, 7, 5,-1,-1,-1,-1}, // 39 { 3, 8, 6, 3, 4, 8,-1,-1,-1,-1}, // 40 { 0, 3, 2, 2, 3, 8, 3, 4, 8,-1}, // 41 { 0, 1, 6, 1, 8, 6, 3, 4, 7,-1}, // 42 { 1, 8, 2, 3, 4, 7,-1,-1,-1,-1}, // 43 { 1, 2, 3, 1, 3, 4,-1,-1,-1,-1}, // 44 { 0, 3, 1, 1, 3, 4,-1,-1,-1,-1}, // 45 { 0, 2, 6, 3, 4, 7,-1,-1,-1,-1}, // 46 { 3, 4, 7,-1,-1,-1,-1,-1,-1,-1}, // 47 { 3, 7, 5, 5, 7, 8,-1,-1,-1,-1}, // 48 { 0, 6, 2, 3, 7, 5, 5, 7, 8,-1}, // 49 { 0, 5, 3, 0, 8, 5, 0, 8, 1,-1}, // 50 { 1, 8, 2, 3, 6, 5,-1,-1,-1,-1}, // 51 { 2, 3, 7, 1, 2, 7,-1,-1,-1,-1}, // 52 { 0, 7, 1, 3, 6, 5,-1,-1,-1,-1}, // 53 { 0, 5, 3, 0, 2, 5,-1,-1,-1,-1}, // 54 { 3, 6, 5,-1,-1,-1,-1,-1,-1,-1}, // 55 { 6, 7, 8,-1,-1,-1,-1,-1,-1,-1}, // 56 { 0, 7, 2, 2, 7, 8,-1,-1,-1,-1}, // 57 { 0, 8, 6, 0, 1, 8,-1,-1,-1,-1}, // 58 { 1, 8, 2,-1,-1,-1,-1,-1,-1,-1}, // 59 { 2, 6, 7, 1, 2, 7,-1,-1,-1,-1}, // 60 { 0, 7, 1,-1,-1,-1,-1,-1,-1,-1}, // 61 { 0, 2, 6,-1,-1,-1,-1,-1,-1,-1}, // 62 {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} // 63 }; const int VertexID[9][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 3, 4 }, { 4, 5 }, { 5, 3 }, { 0, 3 }, { 1, 4 }, { 2, 5 } }; } // end of namespace MarchingPrismTable } // end of namespace kvs <commit_msg>Fixed a problem<commit_after>/*****************************************************************************/ /** * @file MarchingPrismTable.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id$ */ /*****************************************************************************/ #include "MarchingPrismTable.h" namespace kvs { namespace MarchingPrismTable { const int TriangleID[64][10] = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, // 0 { 0, 6, 2,-1,-1,-1,-1,-1,-1,-1}, // 1 { 0, 1, 7,-1,-1,-1,-1,-1,-1,-1}, // 2 { 1, 6, 2, 1, 7, 6,-1,-1,-1,-1}, // 3 { 1, 2, 8,-1,-1,-1,-1,-1,-1,-1}, // 4 { 0, 6, 1, 1, 6, 8,-1,-1,-1,-1}, // 5 { 0, 2, 7, 2, 8, 7,-1,-1,-1,-1}, // 6 { 6, 8, 7,-1,-1,-1,-1,-1,-1,-1}, // 7 { 3, 5, 6,-1,-1,-1,-1,-1,-1,-1}, // 8 { 0, 3, 5, 0, 5, 2,-1,-1,-1,-1}, // 9 { 0, 1, 7, 3, 5, 6,-1,-1,-1,-1}, // 10 { 1, 5, 2, 1, 7, 5, 3, 5, 7,-1}, // 11 { 1, 2, 8, 3, 5, 6,-1,-1,-1,-1}, // 12 { 0, 3, 5, 0, 5, 1, 1, 5, 8,-1}, // 13 { 0, 2, 7, 2, 8, 7, 3, 5, 6,-1}, // 14 { 3, 5, 7, 5, 8, 7,-1,-1,-1,-1}, // 15 { 3, 7, 4,-1,-1,-1,-1,-1,-1,-1}, // 16 { 0, 6, 2, 3, 7, 4,-1,-1,-1,-1}, // 17 { 0, 1, 3, 1, 4, 3,-1,-1,-1,-1}, // 18 { 2, 3, 6, 2, 4, 3, 1, 4, 2,-1}, // 19 { 3, 7, 4, 2, 8, 1,-1,-1,-1,-1}, // 20 { 0, 6, 1, 1, 6, 8, 3, 7, 4,-1}, // 21 { 0, 2, 3, 2, 8, 3, 3, 8, 4,-1}, // 22 { 3, 6, 8, 3, 8, 4,-1,-1,-1,-1}, // 23 { 5, 6, 7, 4, 5, 7,-1,-1,-1,-1}, // 24 { 0, 7, 2, 2, 7, 5, 4, 5, 7,-1}, // 25 { 0, 5, 6, 0, 1, 5, 1, 4, 5,-1}, // 26 { 1, 5, 2, 1, 4, 5,-1,-1,-1,-1}, // 27 { 5, 6, 7, 4, 5, 7, 1, 2, 8,-1}, // 28 { 0, 7, 1, 4, 5, 8,-1,-1,-1,-1}, // 29 { 0, 2, 6, 4, 5, 8,-1,-1,-1,-1}, // 30 { 4, 5, 8,-1,-1,-1,-1,-1,-1,-1}, // 31 { 4, 8, 5,-1,-1,-1,-1,-1,-1,-1}, // 32 { 0, 6, 2, 4, 8, 5,-1,-1,-1,-1}, // 33 { 0, 1, 7, 4, 8, 5,-1,-1,-1,-1}, // 34 { 1, 6, 2, 1, 7, 6, 4, 8, 5,-1}, // 35 { 1, 2, 5, 1, 5, 4,-1,-1,-1,-1}, // 36 { 0, 5, 1, 1, 5, 4, 0, 6, 5,-1}, // 37 { 0, 2, 7, 2, 5, 7, 4, 7, 5,-1}, // 38 { 5, 7, 6, 4, 7, 5,-1,-1,-1,-1}, // 39 { 3, 8, 6, 3, 4, 8,-1,-1,-1,-1}, // 40 { 0, 3, 2, 2, 3, 8, 3, 4, 8,-1}, // 41 { 0, 1, 6, 1, 8, 6, 3, 4, 7,-1}, // 42 { 1, 8, 2, 3, 4, 7,-1,-1,-1,-1}, // 43 { 1, 2, 3, 1, 3, 4,-1,-1,-1,-1}, // 44 { 0, 3, 1, 1, 3, 4,-1,-1,-1,-1}, // 45 { 0, 2, 6, 3, 4, 7,-1,-1,-1,-1}, // 46 { 3, 4, 7,-1,-1,-1,-1,-1,-1,-1}, // 47 { 3, 7, 5, 5, 7, 8,-1,-1,-1,-1}, // 48 { 0, 6, 2, 3, 7, 5, 5, 7, 8,-1}, // 49 { 0, 5, 3, 0, 8, 5, 0, 1, 8,-1}, // 50 { 1, 8, 2, 3, 6, 5,-1,-1,-1,-1}, // 51 { 2, 3, 7, 1, 2, 7,-1,-1,-1,-1}, // 52 { 0, 7, 1, 3, 6, 5,-1,-1,-1,-1}, // 53 { 0, 5, 3, 0, 2, 5,-1,-1,-1,-1}, // 54 { 3, 6, 5,-1,-1,-1,-1,-1,-1,-1}, // 55 { 6, 7, 8,-1,-1,-1,-1,-1,-1,-1}, // 56 { 0, 7, 2, 2, 7, 8,-1,-1,-1,-1}, // 57 { 0, 8, 6, 0, 1, 8,-1,-1,-1,-1}, // 58 { 1, 8, 2,-1,-1,-1,-1,-1,-1,-1}, // 59 { 2, 6, 7, 1, 2, 7,-1,-1,-1,-1}, // 60 { 0, 7, 1,-1,-1,-1,-1,-1,-1,-1}, // 61 { 0, 2, 6,-1,-1,-1,-1,-1,-1,-1}, // 62 {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} // 63 }; const int VertexID[9][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 }, { 3, 4 }, { 4, 5 }, { 5, 3 }, { 0, 3 }, { 1, 4 }, { 2, 5 } }; } // end of namespace MarchingPrismTable } // end of namespace kvs <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/menu_scroll_view_container.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/gfx/canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/views/border.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/menu/menu_config.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/submenu_view.h" #include "ui/views/round_rect_painter.h" using ui::NativeTheme; // Height of the scroll arrow. // This goes up to 4 with large fonts, but this is close enough for now. static const int scroll_arrow_height = 3; namespace views { namespace { static const int kBorderPaddingDueToRoundedCorners = 1; // MenuScrollButton ------------------------------------------------------------ // MenuScrollButton is used for the scroll buttons when not all menu items fit // on screen. MenuScrollButton forwards appropriate events to the // MenuController. class MenuScrollButton : public View { public: MenuScrollButton(SubmenuView* host, bool is_up) : host_(host), is_up_(is_up), // Make our height the same as that of other MenuItemViews. pref_height_(MenuItemView::pref_menu_height()) { } virtual gfx::Size GetPreferredSize() OVERRIDE { return gfx::Size( host_->GetMenuItem()->GetMenuConfig().scroll_arrow_height * 2 - 1, pref_height_); } virtual bool CanDrop(const OSExchangeData& data) OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); return true; // Always return true so that drop events are targeted to us. } virtual void OnDragEntered(const ui::DropTargetEvent& event) OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); host_->GetMenuItem()->GetMenuController()->OnDragEnteredScrollButton( host_, is_up_); } virtual int OnDragUpdated(const ui::DropTargetEvent& event) OVERRIDE { return ui::DragDropTypes::DRAG_NONE; } virtual void OnDragExited() OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); host_->GetMenuItem()->GetMenuController()->OnDragExitedScrollButton(host_); } virtual int OnPerformDrop(const ui::DropTargetEvent& event) OVERRIDE { return ui::DragDropTypes::DRAG_NONE; } virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { const MenuConfig& config = host_->GetMenuItem()->GetMenuConfig(); // The background. gfx::Rect item_bounds(0, 0, width(), height()); NativeTheme::ExtraParams extra; extra.menu_item.is_selected = false; GetNativeTheme()->Paint(canvas->sk_canvas(), NativeTheme::kMenuItemBackground, NativeTheme::kNormal, item_bounds, extra); // Then the arrow. int x = width() / 2; int y = (height() - config.scroll_arrow_height) / 2; int x_left = x - config.scroll_arrow_height; int x_right = x + config.scroll_arrow_height; int y_bottom; if (!is_up_) { y_bottom = y; y = y_bottom + config.scroll_arrow_height; } else { y_bottom = y + config.scroll_arrow_height; } SkPath path; path.setFillType(SkPath::kWinding_FillType); path.moveTo(SkIntToScalar(x), SkIntToScalar(y)); path.lineTo(SkIntToScalar(x_left), SkIntToScalar(y_bottom)); path.lineTo(SkIntToScalar(x_right), SkIntToScalar(y_bottom)); path.lineTo(SkIntToScalar(x), SkIntToScalar(y)); SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setAntiAlias(true); paint.setColor(config.arrow_color); canvas->DrawPath(path, paint); } private: // SubmenuView we were created for. SubmenuView* host_; // Direction of the button. bool is_up_; // Preferred height. int pref_height_; DISALLOW_COPY_AND_ASSIGN(MenuScrollButton); }; } // namespace // MenuScrollView -------------------------------------------------------------- // MenuScrollView is a viewport for the SubmenuView. It's reason to exist is so // that ScrollRectToVisible works. // // NOTE: It is possible to use ScrollView directly (after making it deal with // null scrollbars), but clicking on a child of ScrollView forces the window to // become active, which we don't want. As we really only need a fraction of // what ScrollView does, so we use a one off variant. class MenuScrollViewContainer::MenuScrollView : public View { public: explicit MenuScrollView(View* child) { AddChildView(child); } virtual void ScrollRectToVisible(const gfx::Rect& rect) OVERRIDE { // NOTE: this assumes we only want to scroll in the y direction. // Convert rect.y() to view's coordinates and make sure we don't show past // the bottom of the view. View* child = GetContents(); child->SetY(-std::max(0, std::min( child->GetPreferredSize().height() - this->height(), rect.y() - child->y()))); } // Returns the contents, which is the SubmenuView. View* GetContents() { return child_at(0); } private: DISALLOW_COPY_AND_ASSIGN(MenuScrollView); }; // MenuScrollViewContainer ---------------------------------------------------- MenuScrollViewContainer::MenuScrollViewContainer(SubmenuView* content_view) : content_view_(content_view), arrow_location_(BubbleBorder::NONE), bubble_border_(NULL) { scroll_up_button_ = new MenuScrollButton(content_view, true); scroll_down_button_ = new MenuScrollButton(content_view, false); AddChildView(scroll_up_button_); AddChildView(scroll_down_button_); scroll_view_ = new MenuScrollView(content_view); AddChildView(scroll_view_); arrow_location_ = BubbleBorderTypeFromAnchor( content_view_->GetMenuItem()->GetMenuController()->GetAnchorPosition()); if (arrow_location_ != BubbleBorder::NONE) CreateBubbleBorder(); else CreateDefaultBorder(); } bool MenuScrollViewContainer::HasBubbleBorder() { return arrow_location_ != BubbleBorder::NONE; } void MenuScrollViewContainer::SetBubbleArrowOffset(int offset) { DCHECK(HasBubbleBorder()); bubble_border_->set_arrow_offset(offset); } void MenuScrollViewContainer::OnPaintBackground(gfx::Canvas* canvas) { if (background()) { View::OnPaintBackground(canvas); return; } gfx::Rect bounds(0, 0, width(), height()); NativeTheme::ExtraParams extra; const MenuConfig& menu_config = content_view_->GetMenuItem()->GetMenuConfig(); extra.menu_background.corner_radius = menu_config.corner_radius; GetNativeTheme()->Paint(canvas->sk_canvas(), NativeTheme::kMenuPopupBackground, NativeTheme::kNormal, bounds, extra); } void MenuScrollViewContainer::Layout() { gfx::Insets insets = GetInsets(); int x = insets.left(); int y = insets.top(); int width = View::width() - insets.width(); int content_height = height() - insets.height(); if (!scroll_up_button_->visible()) { scroll_view_->SetBounds(x, y, width, content_height); scroll_view_->Layout(); return; } gfx::Size pref = scroll_up_button_->GetPreferredSize(); scroll_up_button_->SetBounds(x, y, width, pref.height()); content_height -= pref.height(); const int scroll_view_y = y + pref.height(); pref = scroll_down_button_->GetPreferredSize(); scroll_down_button_->SetBounds(x, height() - pref.height() - insets.top(), width, pref.height()); content_height -= pref.height(); scroll_view_->SetBounds(x, scroll_view_y, width, content_height); scroll_view_->Layout(); } gfx::Size MenuScrollViewContainer::GetPreferredSize() { gfx::Size prefsize = scroll_view_->GetContents()->GetPreferredSize(); gfx::Insets insets = GetInsets(); prefsize.Enlarge(insets.width(), insets.height()); return prefsize; } void MenuScrollViewContainer::GetAccessibleState( ui::AccessibleViewState* state) { // Get the name from the submenu view. content_view_->GetAccessibleState(state); // Now change the role. state->role = ui::AccessibilityTypes::ROLE_MENUBAR; // Some AT (like NVDA) will not process focus events on menu item children // unless a parent claims to be focused. state->state = ui::AccessibilityTypes::STATE_FOCUSED; } void MenuScrollViewContainer::OnBoundsChanged( const gfx::Rect& previous_bounds) { gfx::Size content_pref = scroll_view_->GetContents()->GetPreferredSize(); scroll_up_button_->SetVisible(content_pref.height() > height()); scroll_down_button_->SetVisible(content_pref.height() > height()); Layout(); } void MenuScrollViewContainer::CreateDefaultBorder() { arrow_location_ = BubbleBorder::NONE; bubble_border_ = NULL; const MenuConfig& menu_config = content_view_->GetMenuItem()->GetMenuConfig(); int padding = menu_config.corner_radius > 0 ? kBorderPaddingDueToRoundedCorners : 0; int top = menu_config.menu_vertical_border_size + padding; int left = menu_config.menu_horizontal_border_size + padding; int bottom = menu_config.menu_vertical_border_size + padding; int right = menu_config.menu_horizontal_border_size + padding; if (NativeTheme::IsNewMenuStyleEnabled()) { set_border(views::Border::CreateBorderPainter( new views::RoundRectPainter(menu_config.native_theme->GetSystemColor( ui::NativeTheme::kColorId_MenuBorderColor), menu_config.corner_radius), gfx::Insets(top, left, bottom, right))); } else { set_border(Border::CreateEmptyBorder(top, left, bottom, right)); } } void MenuScrollViewContainer::CreateBubbleBorder() { bubble_border_ = new BubbleBorder(arrow_location_, BubbleBorder::NO_SHADOW, SK_ColorWHITE); set_border(bubble_border_); set_background(new BubbleBackground(bubble_border_)); } BubbleBorder::ArrowLocation MenuScrollViewContainer::BubbleBorderTypeFromAnchor( MenuItemView::AnchorPosition anchor) { switch (anchor) { case views::MenuItemView::BUBBLE_LEFT: return BubbleBorder::RIGHT_CENTER; case views::MenuItemView::BUBBLE_RIGHT: return BubbleBorder::LEFT_CENTER; case views::MenuItemView::BUBBLE_ABOVE: return BubbleBorder::BOTTOM_CENTER; case views::MenuItemView::BUBBLE_BELOW: return BubbleBorder::TOP_CENTER; default: return BubbleBorder::NONE; } } } // namespace views <commit_msg>Fixing the double border around rounded menus.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/menu_scroll_view_container.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/gfx/canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/views/border.h" #include "ui/views/bubble/bubble_border.h" #include "ui/views/controls/menu/menu_config.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/submenu_view.h" #include "ui/views/round_rect_painter.h" #if defined(USE_AURA) #include "ui/native_theme/native_theme_aura.h" #endif using ui::NativeTheme; // Height of the scroll arrow. // This goes up to 4 with large fonts, but this is close enough for now. static const int scroll_arrow_height = 3; namespace views { namespace { static const int kBorderPaddingDueToRoundedCorners = 1; // MenuScrollButton ------------------------------------------------------------ // MenuScrollButton is used for the scroll buttons when not all menu items fit // on screen. MenuScrollButton forwards appropriate events to the // MenuController. class MenuScrollButton : public View { public: MenuScrollButton(SubmenuView* host, bool is_up) : host_(host), is_up_(is_up), // Make our height the same as that of other MenuItemViews. pref_height_(MenuItemView::pref_menu_height()) { } virtual gfx::Size GetPreferredSize() OVERRIDE { return gfx::Size( host_->GetMenuItem()->GetMenuConfig().scroll_arrow_height * 2 - 1, pref_height_); } virtual bool CanDrop(const OSExchangeData& data) OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); return true; // Always return true so that drop events are targeted to us. } virtual void OnDragEntered(const ui::DropTargetEvent& event) OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); host_->GetMenuItem()->GetMenuController()->OnDragEnteredScrollButton( host_, is_up_); } virtual int OnDragUpdated(const ui::DropTargetEvent& event) OVERRIDE { return ui::DragDropTypes::DRAG_NONE; } virtual void OnDragExited() OVERRIDE { DCHECK(host_->GetMenuItem()->GetMenuController()); host_->GetMenuItem()->GetMenuController()->OnDragExitedScrollButton(host_); } virtual int OnPerformDrop(const ui::DropTargetEvent& event) OVERRIDE { return ui::DragDropTypes::DRAG_NONE; } virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { const MenuConfig& config = host_->GetMenuItem()->GetMenuConfig(); // The background. gfx::Rect item_bounds(0, 0, width(), height()); NativeTheme::ExtraParams extra; extra.menu_item.is_selected = false; GetNativeTheme()->Paint(canvas->sk_canvas(), NativeTheme::kMenuItemBackground, NativeTheme::kNormal, item_bounds, extra); // Then the arrow. int x = width() / 2; int y = (height() - config.scroll_arrow_height) / 2; int x_left = x - config.scroll_arrow_height; int x_right = x + config.scroll_arrow_height; int y_bottom; if (!is_up_) { y_bottom = y; y = y_bottom + config.scroll_arrow_height; } else { y_bottom = y + config.scroll_arrow_height; } SkPath path; path.setFillType(SkPath::kWinding_FillType); path.moveTo(SkIntToScalar(x), SkIntToScalar(y)); path.lineTo(SkIntToScalar(x_left), SkIntToScalar(y_bottom)); path.lineTo(SkIntToScalar(x_right), SkIntToScalar(y_bottom)); path.lineTo(SkIntToScalar(x), SkIntToScalar(y)); SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setAntiAlias(true); paint.setColor(config.arrow_color); canvas->DrawPath(path, paint); } private: // SubmenuView we were created for. SubmenuView* host_; // Direction of the button. bool is_up_; // Preferred height. int pref_height_; DISALLOW_COPY_AND_ASSIGN(MenuScrollButton); }; } // namespace // MenuScrollView -------------------------------------------------------------- // MenuScrollView is a viewport for the SubmenuView. It's reason to exist is so // that ScrollRectToVisible works. // // NOTE: It is possible to use ScrollView directly (after making it deal with // null scrollbars), but clicking on a child of ScrollView forces the window to // become active, which we don't want. As we really only need a fraction of // what ScrollView does, so we use a one off variant. class MenuScrollViewContainer::MenuScrollView : public View { public: explicit MenuScrollView(View* child) { AddChildView(child); } virtual void ScrollRectToVisible(const gfx::Rect& rect) OVERRIDE { // NOTE: this assumes we only want to scroll in the y direction. // Convert rect.y() to view's coordinates and make sure we don't show past // the bottom of the view. View* child = GetContents(); child->SetY(-std::max(0, std::min( child->GetPreferredSize().height() - this->height(), rect.y() - child->y()))); } // Returns the contents, which is the SubmenuView. View* GetContents() { return child_at(0); } private: DISALLOW_COPY_AND_ASSIGN(MenuScrollView); }; // MenuScrollViewContainer ---------------------------------------------------- MenuScrollViewContainer::MenuScrollViewContainer(SubmenuView* content_view) : content_view_(content_view), arrow_location_(BubbleBorder::NONE), bubble_border_(NULL) { scroll_up_button_ = new MenuScrollButton(content_view, true); scroll_down_button_ = new MenuScrollButton(content_view, false); AddChildView(scroll_up_button_); AddChildView(scroll_down_button_); scroll_view_ = new MenuScrollView(content_view); AddChildView(scroll_view_); arrow_location_ = BubbleBorderTypeFromAnchor( content_view_->GetMenuItem()->GetMenuController()->GetAnchorPosition()); if (arrow_location_ != BubbleBorder::NONE) CreateBubbleBorder(); else CreateDefaultBorder(); } bool MenuScrollViewContainer::HasBubbleBorder() { return arrow_location_ != BubbleBorder::NONE; } void MenuScrollViewContainer::SetBubbleArrowOffset(int offset) { DCHECK(HasBubbleBorder()); bubble_border_->set_arrow_offset(offset); } void MenuScrollViewContainer::OnPaintBackground(gfx::Canvas* canvas) { if (background()) { View::OnPaintBackground(canvas); return; } gfx::Rect bounds(0, 0, width(), height()); NativeTheme::ExtraParams extra; const MenuConfig& menu_config = content_view_->GetMenuItem()->GetMenuConfig(); extra.menu_background.corner_radius = menu_config.corner_radius; GetNativeTheme()->Paint(canvas->sk_canvas(), NativeTheme::kMenuPopupBackground, NativeTheme::kNormal, bounds, extra); } void MenuScrollViewContainer::Layout() { gfx::Insets insets = GetInsets(); int x = insets.left(); int y = insets.top(); int width = View::width() - insets.width(); int content_height = height() - insets.height(); if (!scroll_up_button_->visible()) { scroll_view_->SetBounds(x, y, width, content_height); scroll_view_->Layout(); return; } gfx::Size pref = scroll_up_button_->GetPreferredSize(); scroll_up_button_->SetBounds(x, y, width, pref.height()); content_height -= pref.height(); const int scroll_view_y = y + pref.height(); pref = scroll_down_button_->GetPreferredSize(); scroll_down_button_->SetBounds(x, height() - pref.height() - insets.top(), width, pref.height()); content_height -= pref.height(); scroll_view_->SetBounds(x, scroll_view_y, width, content_height); scroll_view_->Layout(); } gfx::Size MenuScrollViewContainer::GetPreferredSize() { gfx::Size prefsize = scroll_view_->GetContents()->GetPreferredSize(); gfx::Insets insets = GetInsets(); prefsize.Enlarge(insets.width(), insets.height()); return prefsize; } void MenuScrollViewContainer::GetAccessibleState( ui::AccessibleViewState* state) { // Get the name from the submenu view. content_view_->GetAccessibleState(state); // Now change the role. state->role = ui::AccessibilityTypes::ROLE_MENUBAR; // Some AT (like NVDA) will not process focus events on menu item children // unless a parent claims to be focused. state->state = ui::AccessibilityTypes::STATE_FOCUSED; } void MenuScrollViewContainer::OnBoundsChanged( const gfx::Rect& previous_bounds) { gfx::Size content_pref = scroll_view_->GetContents()->GetPreferredSize(); scroll_up_button_->SetVisible(content_pref.height() > height()); scroll_down_button_->SetVisible(content_pref.height() > height()); Layout(); } void MenuScrollViewContainer::CreateDefaultBorder() { arrow_location_ = BubbleBorder::NONE; bubble_border_ = NULL; const MenuConfig& menu_config = content_view_->GetMenuItem()->GetMenuConfig(); bool use_border = true; int padding = menu_config.corner_radius > 0 ? kBorderPaddingDueToRoundedCorners : 0; #if defined(USE_AURA) if (menu_config.native_theme == ui::NativeThemeAura::instance()) { // In case of NativeThemeAura the border gets drawn with the shadow. // Furthermore no additional padding is wanted. use_border = false; padding = 0; } #endif int top = menu_config.menu_vertical_border_size + padding; int left = menu_config.menu_horizontal_border_size + padding; int bottom = menu_config.menu_vertical_border_size + padding; int right = menu_config.menu_horizontal_border_size + padding; if (use_border && NativeTheme::IsNewMenuStyleEnabled()) { set_border(views::Border::CreateBorderPainter( new views::RoundRectPainter(menu_config.native_theme->GetSystemColor( ui::NativeTheme::kColorId_MenuBorderColor), menu_config.corner_radius), gfx::Insets(top, left, bottom, right))); } else { set_border(Border::CreateEmptyBorder(top, left, bottom, right)); } } void MenuScrollViewContainer::CreateBubbleBorder() { bubble_border_ = new BubbleBorder(arrow_location_, BubbleBorder::NO_SHADOW, SK_ColorWHITE); set_border(bubble_border_); set_background(new BubbleBackground(bubble_border_)); } BubbleBorder::ArrowLocation MenuScrollViewContainer::BubbleBorderTypeFromAnchor( MenuItemView::AnchorPosition anchor) { switch (anchor) { case views::MenuItemView::BUBBLE_LEFT: return BubbleBorder::RIGHT_CENTER; case views::MenuItemView::BUBBLE_RIGHT: return BubbleBorder::LEFT_CENTER; case views::MenuItemView::BUBBLE_ABOVE: return BubbleBorder::BOTTOM_CENTER; case views::MenuItemView::BUBBLE_BELOW: return BubbleBorder::TOP_CENTER; default: return BubbleBorder::NONE; } } } // namespace views <|endoftext|>
<commit_before>/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv2.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl <peter.knafl@gmail.com> * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolserverv2.h" #include <jsonrpccpp/common/errors.h> #include <iostream> using namespace std; using namespace jsonrpc; RpcProtocolServerV2::RpcProtocolServerV2(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) { } void RpcProtocolServerV2::HandleJsonRequest (const Json::Value &req, Json::Value &response) { //It could be a Batch Request if (req.isArray()) { this->HandleBatchRequest(req, response); } //It could be a simple Request else if (req.isObject()) { this->HandleSingleRequest(req, response); } else { this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); } } void RpcProtocolServerV2::HandleSingleRequest (const Json::Value &req, Json::Value& response) { int error = this->ValidateRequest(req); if (error == 0) { try { this->ProcessRequest(req, response); } catch (const JsonRpcException & exc) { this->WrapException(req, exc, response); } } else { this->WrapError(req, error, Errors::GetErrorMessage(error),response); } } void RpcProtocolServerV2::HandleBatchRequest (const Json::Value &req, Json::Value& response) { if (req.size() == 0) this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); else { for (unsigned int i = 0; i < req.size(); i++) { Json::Value result; this->HandleSingleRequest(req[i], result); if (result != Json::nullValue) response.append(result); } } } bool RpcProtocolServerV2::ValidateRequestFields(const Json::Value &request) { if (!request.isObject()) return false; if (!(request.isMember(KEY_REQUEST_METHODNAME) && request[KEY_REQUEST_METHODNAME].isString())) return false; if (!(request.isMember(KEY_REQUEST_VERSION) && request[KEY_REQUEST_VERSION].isString() && request[KEY_REQUEST_VERSION].asString() == JSON_RPC_VERSION2)) return false; if (request.isMember(KEY_REQUEST_ID) && !(request[KEY_REQUEST_ID].isIntegral() || request[KEY_REQUEST_ID].isString() || request[KEY_REQUEST_ID].isNull())) return false; if (request.isMember(KEY_REQUEST_PARAMETERS) && !(request[KEY_REQUEST_PARAMETERS].isObject() || request[KEY_REQUEST_PARAMETERS].isArray() || request[KEY_REQUEST_ID].isNull())) return false; return true; } void RpcProtocolServerV2::WrapResult(const Json::Value &request, Json::Value &response, Json::Value &result) { response[KEY_REQUEST_VERSION] = JSON_RPC_VERSION2; response[KEY_RESPONSE_RESULT] = result; response[KEY_REQUEST_ID] = request[KEY_REQUEST_ID]; } void RpcProtocolServerV2::WrapError(const Json::Value &request, int code, const string &message, Json::Value &result) { result["jsonrpc"] = "2.0"; result["error"]["code"] = code; result["error"]["message"] = message; if(request.isObject() && request.isMember("id") && (request["id"].isNull() || request["id"].isIntegral() || request["id"].isString())) { result["id"] = request["id"]; } else { result["id"] = Json::nullValue; } } void RpcProtocolServerV2::WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result) { this->WrapError(request, exception.GetCode(), exception.GetMessage(), result); result["error"]["data"] = exception.GetData(); } procedure_t RpcProtocolServerV2::GetRequestType(const Json::Value &request) { if (request.isMember(KEY_REQUEST_ID)) return RPC_METHOD; return RPC_NOTIFICATION; } <commit_msg>Fix typo in param structure checking (Closes #164)<commit_after>/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv2.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl <peter.knafl@gmail.com> * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolserverv2.h" #include <jsonrpccpp/common/errors.h> #include <iostream> using namespace std; using namespace jsonrpc; RpcProtocolServerV2::RpcProtocolServerV2(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) { } void RpcProtocolServerV2::HandleJsonRequest (const Json::Value &req, Json::Value &response) { //It could be a Batch Request if (req.isArray()) { this->HandleBatchRequest(req, response); } //It could be a simple Request else if (req.isObject()) { this->HandleSingleRequest(req, response); } else { this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); } } void RpcProtocolServerV2::HandleSingleRequest (const Json::Value &req, Json::Value& response) { int error = this->ValidateRequest(req); if (error == 0) { try { this->ProcessRequest(req, response); } catch (const JsonRpcException & exc) { this->WrapException(req, exc, response); } } else { this->WrapError(req, error, Errors::GetErrorMessage(error),response); } } void RpcProtocolServerV2::HandleBatchRequest (const Json::Value &req, Json::Value& response) { if (req.size() == 0) this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); else { for (unsigned int i = 0; i < req.size(); i++) { Json::Value result; this->HandleSingleRequest(req[i], result); if (result != Json::nullValue) response.append(result); } } } bool RpcProtocolServerV2::ValidateRequestFields(const Json::Value &request) { if (!request.isObject()) return false; if (!(request.isMember(KEY_REQUEST_METHODNAME) && request[KEY_REQUEST_METHODNAME].isString())) return false; if (!(request.isMember(KEY_REQUEST_VERSION) && request[KEY_REQUEST_VERSION].isString() && request[KEY_REQUEST_VERSION].asString() == JSON_RPC_VERSION2)) return false; if (request.isMember(KEY_REQUEST_ID) && !(request[KEY_REQUEST_ID].isIntegral() || request[KEY_REQUEST_ID].isString() || request[KEY_REQUEST_ID].isNull())) return false; if (request.isMember(KEY_REQUEST_PARAMETERS) && !(request[KEY_REQUEST_PARAMETERS].isObject() || request[KEY_REQUEST_PARAMETERS].isArray() || request[KEY_REQUEST_PARAMETERS].isNull())) return false; return true; } void RpcProtocolServerV2::WrapResult(const Json::Value &request, Json::Value &response, Json::Value &result) { response[KEY_REQUEST_VERSION] = JSON_RPC_VERSION2; response[KEY_RESPONSE_RESULT] = result; response[KEY_REQUEST_ID] = request[KEY_REQUEST_ID]; } void RpcProtocolServerV2::WrapError(const Json::Value &request, int code, const string &message, Json::Value &result) { result["jsonrpc"] = "2.0"; result["error"]["code"] = code; result["error"]["message"] = message; if(request.isObject() && request.isMember("id") && (request["id"].isNull() || request["id"].isIntegral() || request["id"].isString())) { result["id"] = request["id"]; } else { result["id"] = Json::nullValue; } } void RpcProtocolServerV2::WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result) { this->WrapError(request, exception.GetCode(), exception.GetMessage(), result); result["error"]["data"] = exception.GetData(); } procedure_t RpcProtocolServerV2::GetRequestType(const Json::Value &request) { if (request.isMember(KEY_REQUEST_ID)) return RPC_METHOD; return RPC_NOTIFICATION; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // stringAtomBuffer.cc //------------------------------------------------------------------------------ #include "Pre.h" #include <cstring> #include "stringAtomBuffer.h" #include "Core/Memory/Memory.h" #include "Core/Assertion.h" #if ORYOL_USE_VLD #include "vld.h" #endif namespace Oryol { //------------------------------------------------------------------------------ stringAtomBuffer::~stringAtomBuffer() { // release all our allocated chunks for (const int8_t* p : this->chunks) { Memory::Free((void*)p); } this->chunks.Clear(); this->curPointer = 0; } //------------------------------------------------------------------------------ void stringAtomBuffer::allocChunk() { // need to turn off leak detection for the string atom system, since // string atom buffer are never released int8_t* newChunk = (int8_t*) Memory::Alloc(this->chunkSize); this->chunks.Add(newChunk); this->curPointer = newChunk; } //------------------------------------------------------------------------------ const stringAtomBuffer::Header* stringAtomBuffer::AddString(stringAtomTable* table, int32_t hash, const char* str) { o_assert(nullptr != table); o_assert(nullptr != str); // no chunks allocated yet? if (0 == this->curPointer) { this->allocChunk(); } // compute length of new entry (header + string len + 0 terminator byte) const size_t strLen = std::strlen(str); size_t requiredSize = strLen + sizeof(Header) + 1; o_assert(requiredSize < this->chunkSize); // check if there's enough room in the current chunk if ((this->curPointer + requiredSize) >= (this->chunks.Back() + this->chunkSize)) { this->allocChunk(); } // copy over data Header* head = (Header*) this->curPointer; head->table = table; head->hash = hash; head->length = strLen; head->str = (char*) this->curPointer + sizeof(Header); #if ORYOL_WINDOWS errno_t res = strcpy_s((char*)head->str, strLen + 1, str); o_assert(0 == res); #else std::strcpy((char*)head->str, str); #endif // set curPointer to the next aligned position this->curPointer = (int8_t*) Memory::Align(this->curPointer + requiredSize, sizeof(Header)); return head; } } // namespace Oryol <commit_msg>Blind compile fix for VS<commit_after>//------------------------------------------------------------------------------ // stringAtomBuffer.cc //------------------------------------------------------------------------------ #include "Pre.h" #include <cstring> #include "stringAtomBuffer.h" #include "Core/Memory/Memory.h" #include "Core/Assertion.h" #if ORYOL_USE_VLD #include "vld.h" #endif namespace Oryol { //------------------------------------------------------------------------------ stringAtomBuffer::~stringAtomBuffer() { // release all our allocated chunks for (const int8_t* p : this->chunks) { Memory::Free((void*)p); } this->chunks.Clear(); this->curPointer = 0; } //------------------------------------------------------------------------------ void stringAtomBuffer::allocChunk() { // need to turn off leak detection for the string atom system, since // string atom buffer are never released int8_t* newChunk = (int8_t*) Memory::Alloc(this->chunkSize); this->chunks.Add(newChunk); this->curPointer = newChunk; } //------------------------------------------------------------------------------ const stringAtomBuffer::Header* stringAtomBuffer::AddString(stringAtomTable* table, int32_t hash, const char* str) { o_assert(nullptr != table); o_assert(nullptr != str); // no chunks allocated yet? if (0 == this->curPointer) { this->allocChunk(); } // compute length of new entry (header + string len + 0 terminator byte) const int strLen = int(std::strlen(str)); size_t requiredSize = strLen + sizeof(Header) + 1; o_assert(requiredSize < this->chunkSize); // check if there's enough room in the current chunk if ((this->curPointer + requiredSize) >= (this->chunks.Back() + this->chunkSize)) { this->allocChunk(); } // copy over data Header* head = (Header*) this->curPointer; head->table = table; head->hash = hash; head->length = strLen; head->str = (char*) this->curPointer + sizeof(Header); #if ORYOL_WINDOWS errno_t res = strcpy_s((char*)head->str, strLen + 1, str); o_assert(0 == res); #else std::strcpy((char*)head->str, str); #endif // set curPointer to the next aligned position this->curPointer = (int8_t*) Memory::Align(this->curPointer + requiredSize, sizeof(Header)); return head; } } // namespace Oryol <|endoftext|>
<commit_before>/* Copyright (C) 2015-2016 INRA * * 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 <algorithm> #include <string> #include "options.hpp" #include "private.hpp" #include "utils.hpp" #include <cassert> #include <cstdio> namespace efyj { static std::vector<const attribute*> get_basic_attribute(const Model& model) { std::vector<const attribute*> ret; ret.reserve(model.attributes.size()); for (const auto& att : model.attributes) if (att.is_basic()) ret.emplace_back(&att); return ret; } static std::optional<int> get_basic_attribute_id(const std::vector<const attribute*>& att, const std::string& name) { for (size_t i = 0, e = att.size(); i != e; ++i) if (att[i]->name == name) return std::make_optional(static_cast<int>(i)); return std::nullopt; } struct line_reader { line_reader(FILE* is_) : is(is_) {} bool is_end() const { return feof(is) || ferror(is); } std::optional<std::string> getline() { // If the next line is already available in the m_buffer, we return a // substring of the m_buffer and update the m_buffer. auto newline_pos = m_buffer.find_first_of('\n'); if (newline_pos != std::string::npos) { auto ret = m_buffer.substr(0, newline_pos); if (newline_pos >= m_buffer.size()) m_buffer.clear(); else m_buffer = m_buffer.substr(newline_pos + 1, std::string::npos); return std::make_optional(ret); } // We need to append data to the buffer. char buffer[BUFSIZ]; do { if (is_end()) { m_buffer.clear(); return {}; } auto len = fread(buffer, 1, BUFSIZ - 1, is); buffer[len] = '\0'; if (len == 0) { auto ret = std::move(m_buffer); ret += '\n'; return std::make_optional(ret); } else { auto* newline = strchr(buffer, '\n'); if (newline == nullptr) { m_buffer.append(buffer); } else { m_buffer.append(buffer, newline); auto ret = std::move(m_buffer); m_buffer.assign(newline + 1); return std::make_optional(ret); } } } while (!is_end()); auto ret = std::move(m_buffer); ret += '\n'; return std::make_optional(ret); } FILE* is; std::string m_buffer; }; void Options::read(std::shared_ptr<context> context, FILE* is, const Model& model) { clear(); std::vector<const attribute*> atts = get_basic_attribute(model); std::vector<int> convertheader(atts.size(), 0); std::vector<std::string> columns; std::string line; int id = -1; line_reader ls(is); { auto opt_line = ls.getline(); if (!opt_line) { info(context, "Fail to read header\n"); throw csv_parser_status( csv_parser_status::tag::file_error, size_t(0), columns.size()); } line = *opt_line; tokenize(line, columns, ";", false); if (columns.size() == atts.size() + 4) id = 3; else if (columns.size() == atts.size() + 5) id = 4; else throw csv_parser_status( csv_parser_status::tag::column_number_incorrect, size_t(0), columns.size()); } for (size_t i = 0, e = atts.size(); i != e; ++i) info(context, "column {} {}\n", i, columns[i].c_str()); for (size_t i = id, e = id + atts.size(); i != e; ++i) { info(context, "try to get_basic_atribute_id {} : {}\n", i, columns[i].c_str()); auto opt_att_id = get_basic_attribute_id(atts, columns[i]); if (!opt_att_id) { error(context, "Fail to found attribute for `{}'\n", columns[i]); throw csv_parser_status( csv_parser_status::tag::basic_attribute_unknown, size_t(0), columns.size()); } convertheader[i - id] = *opt_att_id; } info(context, "Starts to read data (atts.size() = {}\n", atts.size()); options.init(atts.size()); options.push_line(); int line_number = -1; while (true) { auto opt_line = ls.getline(); if (!opt_line) break; line = *opt_line; line_number++; tokenize(line, columns, ";", false); if (columns.size() != atts.size() + id + 1) { error(context, "Options: error in csv file line {}:" " not correct number of column {}" " (expected: {})\n", line_number, columns.size(), atts.size() + id + 1); continue; } auto opt_obs = model.attributes[0].scale.find_scale_value(columns.back()); if (!opt_obs) throw csv_parser_status( csv_parser_status::tag::scale_value_unknown, static_cast<size_t>(line_number), static_cast<size_t>(columns.size())); int obs = *opt_obs; int department, year; { auto len1 = sscanf(columns[id - 1].c_str(), "%d", &year); auto len2 = sscanf(columns[id - 1].c_str(), "%d", &department); if (len1 != 1 || len2 != 1) { error(context, "Options: error in csv file line {}." " Malformed year or department\n", line_number); continue; } } simulations.push_back(columns[0]); if (id == 4) places.push_back(columns[1]); departments.push_back(department); years.push_back(year); observed.push_back(obs); for (size_t i = id, e = id + atts.size(); i != e; ++i) { size_t attid = convertheader[i - id]; auto opt_option = atts[attid]->scale.find_scale_value(columns[i]); if (!opt_option) { error(context, "Options: error in csv file line {}: " "unknown scale value `{}' for attribute `{}'\n", line_number, columns[i].c_str(), atts[attid]->name.c_str()); throw csv_parser_status{ csv_parser_status::tag::scale_value_unknown, static_cast<size_t>(line_number), static_cast<size_t>(columns.size()) }; } options(options.rows() - 1, attid) = *opt_option; } options.push_line(); } options.pop_line(); init_dataset(); check(); } void Options::init_dataset() { const size_t size = simulations.size(); assert(!simulations.empty()); subdataset.resize(size); if (places.empty()) { for (size_t i = 0; i != size; ++i) { for (size_t j = 0; j != size; ++j) { if (i != j && departments[i] != departments[j] && years[i] != years[j]) { subdataset[i].emplace_back(static_cast<int>(j)); } } } } else { for (size_t i = 0; i != size; ++i) { for (size_t j = 0; j != size; ++j) { if (i != j && departments[i] != departments[j] && places[i] != places[j] && years[i] != years[j]) { subdataset[i].emplace_back(static_cast<int>(j)); } } } } // printf("init_dataset\n"); // for (size_t i = 0, e = subdataset.size(); i != e; ++i) { // printf("%ld [", i); // for (auto elem : subdataset[i]) // printf("%d ", elem); // printf("]\n"); // } { std::vector<std::vector<int>> reduced; id_subdataset_reduced.resize(subdataset.size()); for (size_t i = 0, e = subdataset.size(); i != e; ++i) { auto it = std::find(reduced.cbegin(), reduced.cend(), subdataset[i]); if (it == reduced.cend()) { id_subdataset_reduced[i] = (int)reduced.size(); reduced.push_back(subdataset[i]); } else { id_subdataset_reduced[i] = numeric_cast<int>(std::distance(reduced.cbegin(), it)); } } } // printf("id_subdataset: ["); // for (size_t i = 0, e = subdataset.size(); i != e; ++i) // printf("%d ", id_subdataset_reduced[i]); // printf("]\n"); } void Options::check() { if (static_cast<size_t>(options.rows()) != simulations.size() || options.cols() == 0 || simulations.size() != departments.size() || simulations.size() != years.size() || simulations.size() != observed.size() || !(simulations.size() == places.size() || places.empty()) || simulations.size() != id_subdataset_reduced.size() || subdataset.size() != simulations.size()) throw solver_error("Options are inconsistent"); } void Options::set(const options_data& opts) { simulations = opts.simulations; places = opts.places; departments = opts.departments; years = opts.years; observed = opts.observed; const auto rows = opts.options.rows(); const auto columns = opts.options.columns(); options.init(rows, columns); for (size_t r = 0; r != rows; ++r) for (size_t c = 0; c != columns; ++c) options(r, c) = opts.options(c, r); init_dataset(); check(); } void Options::clear() noexcept { std::vector<std::string>().swap(simulations); std::vector<std::string>().swap(places); std::vector<int>().swap(departments); std::vector<int>().swap(years); std::vector<int>().swap(observed); DynArray().swap(options); std::vector<std::vector<int>>().swap(subdataset); std::vector<int>().swap(id_subdataset_reduced); } } // namespace efyj <commit_msg>efyj: show error when reading bad scale value<commit_after>/* Copyright (C) 2015-2016 INRA * * 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 <algorithm> #include <string> #include "options.hpp" #include "private.hpp" #include "utils.hpp" #include <cassert> #include <cstdio> namespace efyj { static std::vector<const attribute*> get_basic_attribute(const Model& model) { std::vector<const attribute*> ret; ret.reserve(model.attributes.size()); for (const auto& att : model.attributes) if (att.is_basic()) ret.emplace_back(&att); return ret; } static std::optional<int> get_basic_attribute_id(const std::vector<const attribute*>& att, const std::string& name) { for (size_t i = 0, e = att.size(); i != e; ++i) if (att[i]->name == name) return std::make_optional(static_cast<int>(i)); return std::nullopt; } struct line_reader { line_reader(FILE* is_) : is(is_) {} bool is_end() const { return feof(is) || ferror(is); } std::optional<std::string> getline() { // If the next line is already available in the m_buffer, we return a // substring of the m_buffer and update the m_buffer. auto newline_pos = m_buffer.find_first_of('\n'); if (newline_pos != std::string::npos) { auto ret = m_buffer.substr(0, newline_pos); if (newline_pos >= m_buffer.size()) m_buffer.clear(); else m_buffer = m_buffer.substr(newline_pos + 1, std::string::npos); return std::make_optional(ret); } // We need to append data to the buffer. char buffer[BUFSIZ]; do { if (is_end()) { m_buffer.clear(); return {}; } auto len = fread(buffer, 1, BUFSIZ - 1, is); buffer[len] = '\0'; if (len == 0) { auto ret = std::move(m_buffer); ret += '\n'; return std::make_optional(ret); } else { auto* newline = strchr(buffer, '\n'); if (newline == nullptr) { m_buffer.append(buffer); } else { m_buffer.append(buffer, newline); auto ret = std::move(m_buffer); m_buffer.assign(newline + 1); return std::make_optional(ret); } } } while (!is_end()); auto ret = std::move(m_buffer); ret += '\n'; return std::make_optional(ret); } FILE* is; std::string m_buffer; }; void Options::read(std::shared_ptr<context> context, FILE* is, const Model& model) { clear(); std::vector<const attribute*> atts = get_basic_attribute(model); std::vector<int> convertheader(atts.size(), 0); std::vector<std::string> columns; std::string line; int id = -1; line_reader ls(is); { auto opt_line = ls.getline(); if (!opt_line) { info(context, "Fail to read header\n"); throw csv_parser_status( csv_parser_status::tag::file_error, size_t(0), columns.size()); } line = *opt_line; tokenize(line, columns, ";", false); if (columns.size() == atts.size() + 4) id = 3; else if (columns.size() == atts.size() + 5) id = 4; else throw csv_parser_status( csv_parser_status::tag::column_number_incorrect, size_t(0), columns.size()); } for (size_t i = 0, e = atts.size(); i != e; ++i) info(context, "column {} {}\n", i, columns[i].c_str()); for (size_t i = id, e = id + atts.size(); i != e; ++i) { info(context, "try to get_basic_atribute_id {} : {}\n", i, columns[i].c_str()); auto opt_att_id = get_basic_attribute_id(atts, columns[i]); if (!opt_att_id) { error(context, "Fail to found attribute for `{}'\n", columns[i]); throw csv_parser_status( csv_parser_status::tag::basic_attribute_unknown, size_t(0), columns.size()); } convertheader[i - id] = *opt_att_id; } info(context, "Starts to read data (atts.size() = {}\n", atts.size()); options.init(atts.size()); options.push_line(); int line_number = -1; while (true) { auto opt_line = ls.getline(); if (!opt_line) break; line = *opt_line; line_number++; tokenize(line, columns, ";", false); if (columns.size() != atts.size() + id + 1) { error(context, "Options: error in csv file line {}:" " not correct number of column {}" " (expected: {})\n", line_number, columns.size(), atts.size() + id + 1); continue; } auto opt_obs = model.attributes[0].scale.find_scale_value(columns.back()); if (!opt_obs) { error(context, "Options: error in csv file line {}: unknown scale value `{}'\n", line_number, columns.back()); throw csv_parser_status( csv_parser_status::tag::scale_value_unknown, static_cast<size_t>(line_number), static_cast<size_t>(columns.size())); } int obs = *opt_obs; int department, year; { auto len1 = sscanf(columns[id - 1].c_str(), "%d", &year); auto len2 = sscanf(columns[id - 1].c_str(), "%d", &department); if (len1 != 1 || len2 != 1) { error(context, "Options: error in csv file line {}." " Malformed year or department\n", line_number); continue; } } simulations.push_back(columns[0]); if (id == 4) places.push_back(columns[1]); departments.push_back(department); years.push_back(year); observed.push_back(obs); for (size_t i = id, e = id + atts.size(); i != e; ++i) { size_t attid = convertheader[i - id]; auto opt_option = atts[attid]->scale.find_scale_value(columns[i]); if (!opt_option) { error(context, "Options: error in csv file line {}: " "unknown scale value `{}' for attribute `{}'\n", line_number, columns[i].c_str(), atts[attid]->name.c_str()); throw csv_parser_status{ csv_parser_status::tag::scale_value_unknown, static_cast<size_t>(line_number), static_cast<size_t>(columns.size()) }; } options(options.rows() - 1, attid) = *opt_option; } options.push_line(); } options.pop_line(); init_dataset(); check(); } void Options::init_dataset() { const size_t size = simulations.size(); assert(!simulations.empty()); subdataset.resize(size); if (places.empty()) { for (size_t i = 0; i != size; ++i) { for (size_t j = 0; j != size; ++j) { if (i != j && departments[i] != departments[j] && years[i] != years[j]) { subdataset[i].emplace_back(static_cast<int>(j)); } } } } else { for (size_t i = 0; i != size; ++i) { for (size_t j = 0; j != size; ++j) { if (i != j && departments[i] != departments[j] && places[i] != places[j] && years[i] != years[j]) { subdataset[i].emplace_back(static_cast<int>(j)); } } } } // printf("init_dataset\n"); // for (size_t i = 0, e = subdataset.size(); i != e; ++i) { // printf("%ld [", i); // for (auto elem : subdataset[i]) // printf("%d ", elem); // printf("]\n"); // } { std::vector<std::vector<int>> reduced; id_subdataset_reduced.resize(subdataset.size()); for (size_t i = 0, e = subdataset.size(); i != e; ++i) { auto it = std::find(reduced.cbegin(), reduced.cend(), subdataset[i]); if (it == reduced.cend()) { id_subdataset_reduced[i] = (int)reduced.size(); reduced.push_back(subdataset[i]); } else { id_subdataset_reduced[i] = numeric_cast<int>(std::distance(reduced.cbegin(), it)); } } } // printf("id_subdataset: ["); // for (size_t i = 0, e = subdataset.size(); i != e; ++i) // printf("%d ", id_subdataset_reduced[i]); // printf("]\n"); } void Options::check() { if (static_cast<size_t>(options.rows()) != simulations.size() || options.cols() == 0 || simulations.size() != departments.size() || simulations.size() != years.size() || simulations.size() != observed.size() || !(simulations.size() == places.size() || places.empty()) || simulations.size() != id_subdataset_reduced.size() || subdataset.size() != simulations.size()) throw solver_error("Options are inconsistent"); } void Options::set(const options_data& opts) { simulations = opts.simulations; places = opts.places; departments = opts.departments; years = opts.years; observed = opts.observed; const auto rows = opts.options.rows(); const auto columns = opts.options.columns(); options.init(rows, columns); for (size_t r = 0; r != rows; ++r) for (size_t c = 0; c != columns; ++c) options(r, c) = opts.options(c, r); init_dataset(); check(); } void Options::clear() noexcept { std::vector<std::string>().swap(simulations); std::vector<std::string>().swap(places); std::vector<int>().swap(departments); std::vector<int>().swap(years); std::vector<int>().swap(observed); DynArray().swap(options); std::vector<std::vector<int>>().swap(subdataset); std::vector<int>().swap(id_subdataset_reduced); } } // namespace efyj <|endoftext|>
<commit_before>#include "nuFATE.h" double nuFACE::readDoubleAttribute(hid_t object, std::string name){ double target; hid_t attribute_id = H5Aopen(object,name.c_str(),H5P_DEFAULT); herr_t status = H5Aread(attribute_id, H5T_NATIVE_DOUBLE, &target); if(status<0) throw std::runtime_error("Failed to read attribute '"+name+"'"); H5Aclose(attribute_id); return target; } double* nuFACE::logspace(double Emin,double Emax,unsigned int div){ if(div==0) throw std::length_error("number of samples requested from logspace must be nonzero"); double logpoints[div]; double Emin_log,Emax_log; Emin_log = log(Emin); Emax_log = log(Emax); double step_log = (Emax_log - Emin_log)/double(div-1); logpoints[0]=Emin; double EE = Emin_log+step_log; for(unsigned int i=1; i<div-1; i++, EE+=step_log) logpoints[i] = exp(EE); logpoints[div-1]=Emax; double* logpoints_ = &logpoints[0]; return logpoints_; } double* nuFACE::get_glashow_total(double NumNodes, double* energy_nodes){ double GF = 1.16e-5 double hbarc = 1.97e-14 double GW = 2.085 double MW = 80.385e0 double mmu = 0.106e0 double me = 511.e-6 double pi = 3.14159265358979323846 glashow_total_ = (double *)malloc(NumNodes*sizeof(double)); for(int i=0; i<NumNodes; i++){ double x = *(glashow_total_+i); *(glashow_total_ +i) = 2.*me*(*(energy_nodes+i)); *(glashow_total_ +i) = 1. /3.*std::pow(GF,2)*x/pi*std::pow((1.-(std::pow(mmu,2)-std::pow(me,2))/x),2)/(std::pow((1.-x/std::pow(MW,2)),2)+std::pow(GW,2)/std::pow(MW,2))*0.676/0.1057*std::pow(hbarc,2); } return glashow_total_; } double* nuFACE::get_RHS_matrices(double NumNodes, double* energy_nodes, std::shared_ptr<double> sigma_array_, double* dxs_array_){ DeltaE_ = (double *)malloc(NumNodes*sizeof(double)); for(int i = 0; i < NumNodes-1;i++){ *(DeltaE_ + i) = log10(*(energy_nodes+i+1)) - log10(*(energy_nodes+i)); } double RHSMatrix[NumNodes][NumNodes] = {}; for(int i = 0; i < NumNodes; i++) { for(int j= i+1; j < NumNodes ) { double e1 = 1./ *(energy_nodes+j); double e2 = *(energy_nodes+i) * *(energy_nodes+i); RHSMatrix[i][j] = *(DeltaE_ + j - 1) * *(dxs_array_+j * dxsdim[1]+i) * e1 * e2; } } double* RHSMatrix_ = &RHSMatrix[0][0]; return RHSMatrix_; } nuFACE::get_eigs(int flavor, double gamma, string h5_filename) { newflavor = flavor; newgamma = gamma; newh5_filename = h5_filename; //open h5file containing cross sections hid_t file_id,group_id,root_id; file_id = H5Fopen(h5_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); root_id = H5Gopen(file_id, "/", H5P_DEFAULT); std::string grptot = "/total_cross_sections"; std::string grpdiff = "/differential_cross_sections"; group_id = H5Gopen(root_id, grptot.c_str(), H5P_DEFAULT); //Get energy information double Emin = readDoubleAttribute(group_id, 'max_energy') double Emax = readDoubleAttribute(group_id, 'min_energy') double NumNodes = readDoubleAttribute(group_id, 'number_energy_nodes') energy_nodes = logspace(Emin, Emax, Numnodes) //Get sigma_array if (flavor == -1) { hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nuebarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nuebarxs", sigma_array_); } else if (flavor == -2){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"numubarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "numubarxs", sigma_array_); } else if (flavor == -3){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nutaubarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nutaubarxs", sigma_array_); } else if (flavor == 1){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nuexs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nuexs", sigma_array_); } else if (flavor == 2){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"numuxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "numuxs", sigma_array_); } else if (flavor == 3){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nutauxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nutauxs", sigma_array_); } //Get differential cross sections hsize_t dxarraysize[2]; group_id = H5Gopen(root_id, grpdiff.c_str(), H5P_DEFAULT); if (flavor > 0){ H5LTget_dataset_info(group_id,"dxsnu", dxarraysize,NULL,NULL); size_t dim1 = dxarraysize[0]; size_t dim2 = dxarraysize[1]; dxsdim[0] = dxarraysize[0]; dxsdim[1] = dxarraysize[1]; dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "dxsnu", dxs_array_); } else { H5LTget_dataset_info(group_id,"dxsnubar", dxarraysize,NULL,NULL); size_t dim1 = dxarraysize[0]; size_t dim2 = dxarraysize[1]; dxsdim[0] = dxarraysize[0]; dxsdim[1] = dxarraysize[1]; dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "dxsnu", dxs_array_); } //Find RHS matrix RHSMatrix_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, dxs_array_); //Account for tau regeneration/Glashow resonance if (flavor == -3){ std:string grptau = "/tau_decay_spectrum"; group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT); hsize_t tauarraysize[2]; H5LTget_dataset_info(group_id,"tbarfull", tauarraysize,NULL,NULL); size_t dim1 = tauarraysize[0]; size_t dim2 = taurraysize[1]; tau_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "tbarfull", tau_array_); RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_); for (int i = 0; i<NumNodes; i++){ for(int j=0; j<NumNodes;j++) *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j); } } else if(flavor == 3){ std:string grptau = "/tau_decay_spectrum"; group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT); hsize_t tauarraysize[2]; H5LTget_dataset_info(group_id,"tfull", tauarraysize,NULL,NULL); size_t dim1 = tauarraysize[0]; size_t dim2 = taurraysize[1]; tau_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "tbarfull", tau_array_); RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_); for (int i = 0; i<NumNodes; i++){ for(int j=0; j<NumNodes;j++) *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j); } } else if(flavor == -1){ double* glashow_total_ = get_glashow_total(energy_nodes); for (int i = 0; i < sarraysize[0]; i++){ *(sigma_array_+i) = *(sigma_array_+i) + *(glashow_total_ + i)/2.; *(RHSMatrix_ +i) = *(RHSMatrix_ +i) + *(glashow_partial_ + i)/2.; } } phi_0_ = (double *)malloc(NumNodes*sizeof(double)); for (int i = 0; i < NumNodes; i++){ *(phi_0_ + i) = std::pow(*(energy_nodes +i),(2-gamma)); } for (int i = 0; i < sarraysize[0]; i++){ *(RHSMatrix_+i*sarraysize[0]+i) = *(RHSMatrix_+i*sarraysize[0]+i) + *(sigma_array_+i); } //compute eigenvalues and eigenvectors gsl_matrix_view m = gsl_matrix_view_array(RHSMatrix_, NumNodes, NumNodes); gsl_vector *eval = gsl_vector_alloc (NumNodes); gsl_matrix *evec = gsl_matrix_alloc (NumNodes, NumNodes); gsl_eigen_nonsymmv_workspace * w = gsl_eigen_nonsymmv_alloc (NumNodes); gsl_eigen_nonsymmv (&m.matrix, eval, evec, w); int s; gsl_vector *ci = gsl_vector_alloc(NumNodes); gsl_permutation *p = gsl_permutation_alloc(NumNodes); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, phi_0_, ci); //free unneeded memory gsl_permutation_free (p); gsl_eigen_nonsymmv_free (w); return eval, evec, ci, energy_nodes, phi_0_; } int nuFACE::getFlavor() const { return newflavor; } double nuFACE::getGamma() const { return newgamma; } string nuFACE::getFilename() const { return newh5_filename; } <commit_msg>Update nuFACE.cpp<commit_after>#include "nuFATE.h" double nuFACE::readDoubleAttribute(hid_t object, std::string name){ double target; hid_t attribute_id = H5Aopen(object,name.c_str(),H5P_DEFAULT); herr_t status = H5Aread(attribute_id, H5T_NATIVE_DOUBLE, &target); if(status<0) throw std::runtime_error("Failed to read attribute '"+name+"'"); H5Aclose(attribute_id); return target; } double* nuFACE::logspace(double Emin,double Emax,unsigned int div){ if(div==0) throw std::length_error("number of samples requested from logspace must be nonzero"); double logpoints[div]; double Emin_log,Emax_log; Emin_log = log(Emin); Emax_log = log(Emax); double step_log = (Emax_log - Emin_log)/double(div-1); logpoints[0]=Emin; double EE = Emin_log+step_log; for(unsigned int i=1; i<div-1; i++, EE+=step_log) logpoints[i] = exp(EE); logpoints[div-1]=Emax; double* logpoints_ = &logpoints[0]; return logpoints_; } double* nuFACE::get_glashow_total(double NumNodes, double* energy_nodes){ double GF = 1.16e-5 double hbarc = 1.97e-14 double GW = 2.085 double MW = 80.385e0 double mmu = 0.106e0 double me = 511.e-6 double pi = 3.14159265358979323846 glashow_total_ = (double *)malloc(NumNodes*sizeof(double)); for(int i=0; i<NumNodes; i++){ double x = *(glashow_total_+i); *(glashow_total_ +i) = 2.*me*(*(energy_nodes+i)); *(glashow_total_ +i) = 1. /3.*std::pow(GF,2)*x/pi*std::pow((1.-(std::pow(mmu,2)-std::pow(me,2))/x),2)/(std::pow((1.-x/std::pow(MW,2)),2)+std::pow(GW,2)/std::pow(MW,2))*0.676/0.1057*std::pow(hbarc,2); } return glashow_total_; } double* nuFACE::get_RHS_matrices(double NumNodes, double* energy_nodes, std::shared_ptr<double> sigma_array_, double* dxs_array_){ DeltaE_ = (double *)malloc(NumNodes*sizeof(double)); for(int i = 0; i < NumNodes-1;i++){ *(DeltaE_ + i) = log10(*(energy_nodes+i+1)) - log10(*(energy_nodes+i)); } double RHSMatrix[NumNodes][NumNodes] = {}; for(int i = 0; i < NumNodes; i++) { for(int j= i+1; j < NumNodes ) { double e1 = 1./ *(energy_nodes+j); double e2 = *(energy_nodes+i) * *(energy_nodes+i); RHSMatrix[i][j] = *(DeltaE_ + j - 1) * *(dxs_array_+j * dxsdim[1]+i) * e1 * e2; } } double* RHSMatrix_ = &RHSMatrix[0][0]; return RHSMatrix_; } nuFACE::get_eigs(int flavor, double gamma, string h5_filename) { newflavor = flavor; newgamma = gamma; newh5_filename = h5_filename; //open h5file containing cross sections hid_t file_id,group_id,root_id; file_id = H5Fopen(h5_filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); root_id = H5Gopen(file_id, "/", H5P_DEFAULT); std::string grptot = "/total_cross_sections"; std::string grpdiff = "/differential_cross_sections"; group_id = H5Gopen(root_id, grptot.c_str(), H5P_DEFAULT); //Get energy information double Emin = readDoubleAttribute(group_id, "max_energy") double Emax = readDoubleAttribute(group_id, "min_energy") double NumNodes = readDoubleAttribute(group_id, "number_energy_nodes") energy_nodes = logspace(Emin, Emax, Numnodes) //Get sigma_array if (flavor == -1) { hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nuebarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nuebarxs", sigma_array_); } else if (flavor == -2){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"numubarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "numubarxs", sigma_array_); } else if (flavor == -3){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nutaubarxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nutaubarxs", sigma_array_); } else if (flavor == 1){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nuexs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nuexs", sigma_array_); } else if (flavor == 2){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"numuxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "numuxs", sigma_array_); } else if (flavor == 3){ hsize_t sarraysize[1]; H5LTget_dataset_info(group_id,"nutauxs", sarraysize,NULL,NULL); sigma_array_ = std::make_shared<double>(sarraysize[0]); H5LTread_dataset_double(group_id, "nutauxs", sigma_array_); } //Get differential cross sections hsize_t dxarraysize[2]; group_id = H5Gopen(root_id, grpdiff.c_str(), H5P_DEFAULT); if (flavor > 0){ H5LTget_dataset_info(group_id,"dxsnu", dxarraysize,NULL,NULL); size_t dim1 = dxarraysize[0]; size_t dim2 = dxarraysize[1]; dxsdim[0] = dxarraysize[0]; dxsdim[1] = dxarraysize[1]; dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "dxsnu", dxs_array_); } else { H5LTget_dataset_info(group_id,"dxsnubar", dxarraysize,NULL,NULL); size_t dim1 = dxarraysize[0]; size_t dim2 = dxarraysize[1]; dxsdim[0] = dxarraysize[0]; dxsdim[1] = dxarraysize[1]; dxs_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "dxsnu", dxs_array_); } //Find RHS matrix RHSMatrix_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, dxs_array_); //Account for tau regeneration/Glashow resonance if (flavor == -3){ std:string grptau = "/tau_decay_spectrum"; group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT); hsize_t tauarraysize[2]; H5LTget_dataset_info(group_id,"tbarfull", tauarraysize,NULL,NULL); size_t dim1 = tauarraysize[0]; size_t dim2 = taurraysize[1]; tau_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "tbarfull", tau_array_); RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_); for (int i = 0; i<NumNodes; i++){ for(int j=0; j<NumNodes;j++) *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j); } } else if(flavor == 3){ std:string grptau = "/tau_decay_spectrum"; group_id = H5Gopen(root_id, grptau.c_str(), H5P_DEFAULT); hsize_t tauarraysize[2]; H5LTget_dataset_info(group_id,"tfull", tauarraysize,NULL,NULL); size_t dim1 = tauarraysize[0]; size_t dim2 = taurraysize[1]; tau_array_ = (double *)malloc(dim1*dim2*sizeof(double)); H5LTread_dataset(group_id, "tbarfull", tau_array_); RHregen_ = get_RHS_matrices(NumNodes, energy_nodes, sigma_array_, tau_array_); for (int i = 0; i<NumNodes; i++){ for(int j=0; j<NumNodes;j++) *(RHSMatrix_+i*NumNodes+j) = *(RHSMatrix_+i*NumNodes+j) + *(RHregen_+i*NumNodes+j); } } else if(flavor == -1){ double* glashow_total_ = get_glashow_total(energy_nodes); for (int i = 0; i < sarraysize[0]; i++){ *(sigma_array_+i) = *(sigma_array_+i) + *(glashow_total_ + i)/2.; *(RHSMatrix_ +i) = *(RHSMatrix_ +i) + *(glashow_partial_ + i)/2.; } } phi_0_ = (double *)malloc(NumNodes*sizeof(double)); for (int i = 0; i < NumNodes; i++){ *(phi_0_ + i) = std::pow(*(energy_nodes +i),(2-gamma)); } for (int i = 0; i < sarraysize[0]; i++){ *(RHSMatrix_+i*sarraysize[0]+i) = *(RHSMatrix_+i*sarraysize[0]+i) + *(sigma_array_+i); } //compute eigenvalues and eigenvectors gsl_matrix_view m = gsl_matrix_view_array(RHSMatrix_, NumNodes, NumNodes); gsl_vector *eval = gsl_vector_alloc (NumNodes); gsl_matrix *evec = gsl_matrix_alloc (NumNodes, NumNodes); gsl_eigen_nonsymmv_workspace * w = gsl_eigen_nonsymmv_alloc (NumNodes); gsl_eigen_nonsymmv (&m.matrix, eval, evec, w); int s; gsl_vector *ci = gsl_vector_alloc(NumNodes); gsl_permutation *p = gsl_permutation_alloc(NumNodes); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, phi_0_, ci); //free unneeded memory gsl_permutation_free (p); gsl_eigen_nonsymmv_free (w); return eval, evec, ci, energy_nodes, phi_0_; } int nuFACE::getFlavor() const { return newflavor; } double nuFACE::getGamma() const { return newgamma; } string nuFACE::getFilename() const { return newh5_filename; } <|endoftext|>
<commit_before> #ifndef WIN32_WINDOW_NAMESPACE #error WIN32_WINDOW_NAMESPACE must be defined #endif namespace WIN32_WINDOW_NAMESPACE { namespace detail { template<typename T> struct raw_ptr { explicit raw_ptr(T* raw) : raw(raw) {} operator typename cmn::unspecified_bool<raw_ptr>::type () { return cmn::unspecified_bool<raw_ptr>::get(!!raw); } T* operator ->() { return raw; } T* raw; }; } template<typename WindowClassTag> //static ATOM window_class<WindowClassTag>::Register() { WNDCLASSEX wcex = {}; wcex.cbSize = sizeof(WNDCLASSEX); // defaults that can be overriden wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = GetCurrentInstance(); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); window_class_register(&wcex, tag()); // not overridable wcex.lpfnWndProc = WindowCallback<WindowClassTag>; return RegisterClassEx(&wcex); } template<typename WindowClassTag> template<typename T> //static ATOM window_class<WindowClassTag>::Register(T&& t) { WNDCLASSEX wcex = {}; wcex.cbSize = sizeof(WNDCLASSEX); // defaults that can be overriden wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = cmn::GetCurrentInstance(); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); window_class_register(std::forward<T>(t), &wcex, tag()); // not overridable wcex.lpfnWndProc = WindowCallback<WindowClassTag>; return RegisterClassEx(&wcex); } template<typename WindowClassTag> struct Context { HWND window; UINT message; WPARAM wParam; LPARAM lParam; }; template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_constructor(LPCREATESTRUCT createStruct, decltype(new (std::nothrow) window_class<WindowClassTag>::traits::type(cmn::instance_of<CREATESTRUCT>::value))) { typedef typename window_class<WindowClassTag>::traits::type Type; std::unique_ptr<Type> type(new (std::nothrow) Type(*createStruct)); return std::move(type); } template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_constructor(LPCREATESTRUCT , ...) { typedef typename window_class<WindowClassTag>::traits::type Type; std::unique_ptr<Type> type(new (std::nothrow) Type); return std::move(type); } template<typename WindowClassTag> decltype( window_class_construct( cmn::instance_of<HWND>::value, cmn::instance_of<LPCREATESTRUCT>::value, WindowClassTag())) optional_window_class_construct(HWND hwnd, LPCREATESTRUCT createStruct, WindowClassTag&&, int) { return window_class_construct(hwnd, createStruct, WindowClassTag()); } template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_construct(HWND , LPCREATESTRUCT createStruct, WindowClassTag&&, ...) { return optional_window_class_constructor<WindowClassTag>(createStruct, 0); } template<typename WindowClassTag, typename T> decltype( window_class_insert( cmn::instance_of<HWND>::value, WindowClassTag())) optional_window_class_insert(HWND hwnd, T t, WindowClassTag&&, int) { return window_class_insert(hwnd, std::move(t), WindowClassTag()); } template<typename WindowClassTag> bool optional_window_class_insert( HWND hwnd, std::unique_ptr<typename window_class<WindowClassTag>::traits::type> type, WindowClassTag&&, ...) { if (!type) { return false; } SetLastError(0); auto result = SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(type.get())); unique_winerror winerror = make_winerror_if(!result); ON_UNWIND(UserDataUnwind, [&]{SetWindowLongPtr(hwnd, GWLP_USERDATA, 0);}); if (!winerror) { return false; } if (!!result) { return false; } type.release(); UserDataUnwind.dismiss(); return true; } template<typename WindowClassTag> decltype( window_class_find( cmn::instance_of<HWND>::value, WindowClassTag())) optional_window_class_find(HWND hwnd, WindowClassTag&&, int) { return window_class_find(hwnd, WindowClassTag()); } template<typename WindowClassTag> detail::raw_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_find(HWND hwnd, WindowClassTag&&, ...) { typedef typename window_class<WindowClassTag>::traits::type type; return detail::raw_ptr<type>(reinterpret_cast<type*>(GetWindowLongPtr(hwnd, GWLP_USERDATA))); } template<typename Type, typename WindowClassTag> decltype( window_class_erase( cmn::instance_of<HWND>::value, cmn::instance_of<Type>::value, WindowClassTag())) optional_window_class_erase(HWND hwnd, Type type, WindowClassTag&&, int) { return window_class_erase(hwnd, type, WindowClassTag()); } template<typename Type, typename WindowClassTag> void optional_window_class_erase(HWND hwnd, detail::raw_ptr<Type> , WindowClassTag&&, ...) { SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); } template<typename Type, typename WindowClassTag> decltype( window_class_destroy( cmn::instance_of<HWND>::value, cmn::instance_of<Type>::value, WindowClassTag())) optional_window_class_destroy(HWND hwnd, Type type, WindowClassTag&&, int) { return window_class_destroy(hwnd, type, WindowClassTag()); } template<typename Type, typename WindowClassTag> void optional_window_class_destroy(HWND , detail::raw_ptr<Type> type, WindowClassTag&&, ...) { delete type.raw; } template<typename Type, typename WindowClassTag> decltype( window_class_dispatch( cmn::instance_of<Type>::value, cmn::instance_of<Context<WindowClassTag>>::value, WindowClassTag())) optional_window_class_dispatch(Type type, const Context<WindowClassTag>& context, WindowClassTag&&, int) { return window_message_error_contract( [type] (const Context<WindowClassTag>& context) { return window_class_dispatch(type, context, WindowClassTag()); }, context, WindowClassTag() ); } typedef std::pair<bool, LRESULT> dispatch_result; template<typename Type, typename WindowClassTag> dispatch_result optional_window_class_dispatch(detail::raw_ptr<Type> type, const Context<WindowClassTag>& context, WindowClassTag&&, ...) { return window_message_error_contract( [type] (const Context<WindowClassTag>& context) { return type->window_proc(context.window, context.message, context.wParam, context.LParam); }, context, WindowClassTag() ); } namespace detail { template<typename WindowClassTag> LRESULT CALLBACK WindowCallbackSafe(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { bool handled = false; LRESULT result = 0; if (message == WM_NCCREATE) { auto existingType = optional_window_class_find(hWnd, WindowClassTag(), 0); if (!existingType) { if (!optional_window_class_insert( hWnd, optional_window_class_construct( hWnd, reinterpret_cast<LPCREATESTRUCT>(lParam), WindowClassTag(), 0 ), WindowClassTag(), 0 ) ) { return FALSE; } } } auto type = optional_window_class_find(hWnd, WindowClassTag(), 0); ON_UNWIND_AUTO( [&] { if (type && message == WM_NCDESTROY) { optional_window_class_erase(hWnd, type, WindowClassTag(), 0); optional_window_class_destroy(hWnd, type, WindowClassTag(), 0); } } ); if (type) { Context<WindowClassTag> context = {hWnd, message, wParam, lParam}; std::tie(handled, result) = optional_window_class_dispatch(type, context, WindowClassTag(), 0); if (handled) { return result; } } return DefWindowProc(hWnd, message, wParam, lParam); } } template<typename WindowClassTag> LRESULT CALLBACK WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { __try { return detail::WindowCallbackSafe<WindowClassTag>(hWnd, message, wParam, lParam); } __except(cmn::FailFastFilter(GetExceptionInformation())) { } return 0; } } <commit_msg>add hwnd to the constructor call<commit_after> #ifndef WIN32_WINDOW_NAMESPACE #error WIN32_WINDOW_NAMESPACE must be defined #endif namespace WIN32_WINDOW_NAMESPACE { namespace detail { template<typename T> struct raw_ptr { explicit raw_ptr(T* raw) : raw(raw) {} operator typename cmn::unspecified_bool<raw_ptr>::type () { return cmn::unspecified_bool<raw_ptr>::get(!!raw); } T* operator ->() { return raw; } T* raw; }; } template<typename WindowClassTag> //static ATOM window_class<WindowClassTag>::Register() { WNDCLASSEX wcex = {}; wcex.cbSize = sizeof(WNDCLASSEX); // defaults that can be overriden wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = GetCurrentInstance(); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); window_class_register(&wcex, tag()); // not overridable wcex.lpfnWndProc = WindowCallback<WindowClassTag>; return RegisterClassEx(&wcex); } template<typename WindowClassTag> template<typename T> //static ATOM window_class<WindowClassTag>::Register(T&& t) { WNDCLASSEX wcex = {}; wcex.cbSize = sizeof(WNDCLASSEX); // defaults that can be overriden wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.hInstance = cmn::GetCurrentInstance(); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); window_class_register(std::forward<T>(t), &wcex, tag()); // not overridable wcex.lpfnWndProc = WindowCallback<WindowClassTag>; return RegisterClassEx(&wcex); } template<typename WindowClassTag> struct Context { HWND window; UINT message; WPARAM wParam; LPARAM lParam; }; template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_constructor(HWND hwnd, LPCREATESTRUCT createStruct, decltype(new (std::nothrow) window_class<WindowClassTag>::traits::type(cmn::instance_of<HWND>::value, cmn::instance_of<CREATESTRUCT>::value))) { typedef typename window_class<WindowClassTag>::traits::type Type; std::unique_ptr<Type> type(new (std::nothrow) Type(hwnd, *createStruct)); return std::move(type); } template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_constructor(HWND , LPCREATESTRUCT , ...) { typedef typename window_class<WindowClassTag>::traits::type Type; std::unique_ptr<Type> type(new (std::nothrow) Type); return std::move(type); } template<typename WindowClassTag> decltype( window_class_construct( cmn::instance_of<HWND>::value, cmn::instance_of<LPCREATESTRUCT>::value, WindowClassTag())) optional_window_class_construct(HWND hwnd, LPCREATESTRUCT createStruct, WindowClassTag&&, int) { return window_class_construct(hwnd, createStruct, WindowClassTag()); } template<typename WindowClassTag> std::unique_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_construct(HWND hwnd, LPCREATESTRUCT createStruct, WindowClassTag&&, ...) { return optional_window_class_constructor<WindowClassTag>(hwnd, createStruct, 0); } template<typename WindowClassTag, typename T> decltype( window_class_insert( cmn::instance_of<HWND>::value, WindowClassTag())) optional_window_class_insert(HWND hwnd, T t, WindowClassTag&&, int) { return window_class_insert(hwnd, std::move(t), WindowClassTag()); } template<typename WindowClassTag> bool optional_window_class_insert( HWND hwnd, std::unique_ptr<typename window_class<WindowClassTag>::traits::type> type, WindowClassTag&&, ...) { if (!type) { return false; } SetLastError(0); auto result = SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(type.get())); unique_winerror winerror = make_winerror_if(!result); ON_UNWIND(UserDataUnwind, [&]{SetWindowLongPtr(hwnd, GWLP_USERDATA, 0);}); if (!winerror) { return false; } if (!!result) { return false; } type.release(); UserDataUnwind.dismiss(); return true; } template<typename WindowClassTag> decltype( window_class_find( cmn::instance_of<HWND>::value, WindowClassTag())) optional_window_class_find(HWND hwnd, WindowClassTag&&, int) { return window_class_find(hwnd, WindowClassTag()); } template<typename WindowClassTag> detail::raw_ptr<typename window_class<WindowClassTag>::traits::type> optional_window_class_find(HWND hwnd, WindowClassTag&&, ...) { typedef typename window_class<WindowClassTag>::traits::type type; return detail::raw_ptr<type>(reinterpret_cast<type*>(GetWindowLongPtr(hwnd, GWLP_USERDATA))); } template<typename Type, typename WindowClassTag> decltype( window_class_erase( cmn::instance_of<HWND>::value, cmn::instance_of<Type>::value, WindowClassTag())) optional_window_class_erase(HWND hwnd, Type type, WindowClassTag&&, int) { return window_class_erase(hwnd, type, WindowClassTag()); } template<typename Type, typename WindowClassTag> void optional_window_class_erase(HWND hwnd, detail::raw_ptr<Type> , WindowClassTag&&, ...) { SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); } template<typename Type, typename WindowClassTag> decltype( window_class_destroy( cmn::instance_of<HWND>::value, cmn::instance_of<Type>::value, WindowClassTag())) optional_window_class_destroy(HWND hwnd, Type type, WindowClassTag&&, int) { return window_class_destroy(hwnd, type, WindowClassTag()); } template<typename Type, typename WindowClassTag> void optional_window_class_destroy(HWND , detail::raw_ptr<Type> type, WindowClassTag&&, ...) { delete type.raw; } template<typename Type, typename WindowClassTag> decltype( window_class_dispatch( cmn::instance_of<Type>::value, cmn::instance_of<Context<WindowClassTag>>::value, WindowClassTag())) optional_window_class_dispatch(Type type, const Context<WindowClassTag>& context, WindowClassTag&&, int) { return window_message_error_contract( [type] (const Context<WindowClassTag>& context) { return window_class_dispatch(type, context, WindowClassTag()); }, context, WindowClassTag() ); } typedef std::pair<bool, LRESULT> dispatch_result; template<typename Type, typename WindowClassTag> dispatch_result optional_window_class_dispatch(detail::raw_ptr<Type> type, const Context<WindowClassTag>& context, WindowClassTag&&, ...) { return window_message_error_contract( [type] (const Context<WindowClassTag>& context) { return type->window_proc(context.window, context.message, context.wParam, context.LParam); }, context, WindowClassTag() ); } namespace detail { template<typename WindowClassTag> LRESULT CALLBACK WindowCallbackSafe(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { bool handled = false; LRESULT result = 0; if (message == WM_NCCREATE) { auto existingType = optional_window_class_find(hWnd, WindowClassTag(), 0); if (!existingType) { if (!optional_window_class_insert( hWnd, optional_window_class_construct( hWnd, reinterpret_cast<LPCREATESTRUCT>(lParam), WindowClassTag(), 0 ), WindowClassTag(), 0 ) ) { return FALSE; } } } auto type = optional_window_class_find(hWnd, WindowClassTag(), 0); ON_UNWIND_AUTO( [&] { if (type && message == WM_NCDESTROY) { optional_window_class_erase(hWnd, type, WindowClassTag(), 0); optional_window_class_destroy(hWnd, type, WindowClassTag(), 0); } } ); if (type) { Context<WindowClassTag> context = {hWnd, message, wParam, lParam}; std::tie(handled, result) = optional_window_class_dispatch(type, context, WindowClassTag(), 0); if (handled) { return result; } } return DefWindowProc(hWnd, message, wParam, lParam); } } template<typename WindowClassTag> LRESULT CALLBACK WindowCallback(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { __try { return detail::WindowCallbackSafe<WindowClassTag>(hWnd, message, wParam, lParam); } __except(cmn::FailFastFilter(GetExceptionInformation())) { } return 0; } } <|endoftext|>
<commit_before>#define BOOST_ASIO_DYN_LINK #include "session.h" #include "state.h" #include "utils/json.h" #include <utility> #include <boost/cstdint.hpp> #include <libtorrent/ptime.hpp> namespace torrent { std::unique_ptr < Session > Session::instance; Session::Session () : session ( libtorrent::fingerprint ( "LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0 ), std::make_pair ( 6881, 6889 ) ) {} void Session::initialize () { instance.reset ( new Session ); } std::vector < libtorrent::torrent_handle > Session::get_torrents () { return instance->session.get_torrents (); } libtorrent::torrent_handle Session::add_torrent ( libtorrent::add_torrent_params const& params ) { return instance->session.add_torrent ( params ); } std::shared_ptr < libtorrent::alert > Session::pop_alert () { // Wait for a new alert ( 30 is realy just an arbitrary value ) while ( !instance->session.wait_for_alert ( libtorrent::time_duration ( boost::int64_t ( 30 ) ) ) ); return std::shared_ptr < libtorrent::alert > ( instance->session.pop_alert ().release () ); } void Session::load_torrent_states () { std::vector < std::shared_ptr < utils::Json_element > > torrent_states = State::get_torrent_states (); for ( auto torrent_state : torrent_states ) { libtorrent::add_torrent_params p; if ( torrent_state->get_string ( "method" ) == "url" ) p.url = torrent_state->get_string ( "url" ); p.save_path = torrent_state->get_string ( "save_path" ); libtorrent::torrent_handle torrent = instance->session.add_torrent ( p ); torrent.set_download_limit ( 300000 ); } } } <commit_msg>Implement resuming from torrent files<commit_after>#define BOOST_ASIO_DYN_LINK #include "session.h" #include "state.h" #include "utils/json.h" #include <utility> #include <boost/cstdint.hpp> #include <libtorrent/ptime.hpp> namespace torrent { std::unique_ptr < Session > Session::instance; Session::Session () : session ( libtorrent::fingerprint ( "LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0 ), std::make_pair ( 6881, 6889 ) ) {} void Session::initialize () { instance.reset ( new Session ); } std::vector < libtorrent::torrent_handle > Session::get_torrents () { return instance->session.get_torrents (); } libtorrent::torrent_handle Session::add_torrent ( libtorrent::add_torrent_params const& params ) { return instance->session.add_torrent ( params ); } std::shared_ptr < libtorrent::alert > Session::pop_alert () { // Wait for a new alert ( 30 is realy just an arbitrary value ) while ( !instance->session.wait_for_alert ( libtorrent::time_duration ( boost::int64_t ( 30 ) ) ) ); return std::shared_ptr < libtorrent::alert > ( instance->session.pop_alert ().release () ); } void Session::load_torrent_states () { std::vector < std::shared_ptr < utils::Json_element > > torrent_states = State::get_torrent_states (); for ( auto torrent_state : torrent_states ) { libtorrent::add_torrent_params p; if ( torrent_state->get_string ( "method" ) == "url" ) p.url = torrent_state->get_string ( "url" ); else if ( torrent_state->get_string ( "method" ) == "torrent_file" ) p.ti = new libtorrent::torrent_info ( torrent_state->get_string ( "file_name" ).c_str () ); else continue; p.save_path = torrent_state->get_string ( "save_path" ); libtorrent::torrent_handle torrent = instance->session.add_torrent ( p ); torrent.set_download_limit ( 300000 ); } } } <|endoftext|>
<commit_before>/* * SegmentInformation.hpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN Authors * * 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. *****************************************************************************/ #ifndef SEGMENTINFORMATION_HPP #define SEGMENTINFORMATION_HPP #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "ICanonicalUrl.hpp" #include "Properties.hpp" #include <vlc_common.h> #include <vector> namespace dash { namespace mpd { class ISegment; class SegmentBase; class SegmentList; class SegmentTemplate; /* common segment elements for period/adaptset/rep 5.3.9.1, * with properties inheritance */ class SegmentInformation : public ICanonicalUrl { friend class IsoffMainParser; public: SegmentInformation( SegmentInformation * = 0 ); explicit SegmentInformation( ICanonicalUrl * ); virtual ~SegmentInformation(); bool canBitswitch() const; uint64_t getTimescale() const; virtual mtime_t getPeriodStart() const; class SplitPoint { public: size_t offset; mtime_t time; }; void SplitUsingIndex(std::vector<SplitPoint>&); enum SegmentInfoType { INFOTYPE_INIT = 0, INFOTYPE_MEDIA, INFOTYPE_INDEX }; static const int InfoTypeCount = INFOTYPE_INDEX + 1; ISegment * getSegment(SegmentInfoType, uint64_t = 0) const; bool getSegmentNumberByTime(mtime_t, uint64_t *) const; protected: std::vector<ISegment *> getSegments() const; std::vector<ISegment *> getSegments(SegmentInfoType) const; private: void setSegmentList(SegmentList *); void setSegmentBase(SegmentBase *); void setSegmentTemplate(SegmentTemplate *, SegmentInfoType); void setBitstreamSwitching(bool); SegmentBase * inheritSegmentBase() const; SegmentList * inheritSegmentList() const; SegmentTemplate * inheritSegmentTemplate(SegmentInfoType) const; SegmentInformation *parent; SegmentBase *segmentBase; SegmentList *segmentList; SegmentTemplate *segmentTemplate[InfoTypeCount]; enum BitswitchPolicy { BITSWITCH_INHERIT, BITSWITCH_YES, BITSWITCH_NO } bitswitch_policy; Property<uint64_t> timescale; }; } } #endif // SEGMENTINFORMATION_HPP <commit_msg>Dash: fix compilation for Windows<commit_after>/* * SegmentInformation.hpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN Authors * * 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. *****************************************************************************/ #ifndef SEGMENTINFORMATION_HPP #define SEGMENTINFORMATION_HPP #define __STDC_CONSTANT_MACROS #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "ICanonicalUrl.hpp" #include "Properties.hpp" #include <vlc_common.h> #include <vector> namespace dash { namespace mpd { class ISegment; class SegmentBase; class SegmentList; class SegmentTemplate; /* common segment elements for period/adaptset/rep 5.3.9.1, * with properties inheritance */ class SegmentInformation : public ICanonicalUrl { friend class IsoffMainParser; public: SegmentInformation( SegmentInformation * = 0 ); explicit SegmentInformation( ICanonicalUrl * ); virtual ~SegmentInformation(); bool canBitswitch() const; uint64_t getTimescale() const; virtual mtime_t getPeriodStart() const; class SplitPoint { public: size_t offset; mtime_t time; }; void SplitUsingIndex(std::vector<SplitPoint>&); enum SegmentInfoType { INFOTYPE_INIT = 0, INFOTYPE_MEDIA, INFOTYPE_INDEX }; static const int InfoTypeCount = INFOTYPE_INDEX + 1; ISegment * getSegment(SegmentInfoType, uint64_t = 0) const; bool getSegmentNumberByTime(mtime_t, uint64_t *) const; protected: std::vector<ISegment *> getSegments() const; std::vector<ISegment *> getSegments(SegmentInfoType) const; private: void setSegmentList(SegmentList *); void setSegmentBase(SegmentBase *); void setSegmentTemplate(SegmentTemplate *, SegmentInfoType); void setBitstreamSwitching(bool); SegmentBase * inheritSegmentBase() const; SegmentList * inheritSegmentList() const; SegmentTemplate * inheritSegmentTemplate(SegmentInfoType) const; SegmentInformation *parent; SegmentBase *segmentBase; SegmentList *segmentList; SegmentTemplate *segmentTemplate[InfoTypeCount]; enum BitswitchPolicy { BITSWITCH_INHERIT, BITSWITCH_YES, BITSWITCH_NO } bitswitch_policy; Property<uint64_t> timescale; }; } } #endif // SEGMENTINFORMATION_HPP <|endoftext|>
<commit_before>template <class T> BST<T> * search(const T &value){ } BST<T> * insert(const T &value){ if(this.value > value) *right.insert(value); else if(this.value < value) *left->instert(value); else this.value = value; } BST<T> * delete(const T &value){ } <commit_msg>working bst insert and search, broken bst remove<commit_after>using namespace std; template <class T> BST<T>* BST<T>::insert(const T &value){ if(this->getValue() < value){ if(this->getRight() == NULL){ this->setRight(new BST<T>(value, NULL, NULL, this)); } else{ BST<T>* right = dynamic_cast<BST<T>*>(this->getRight()); this->setRight(right->insert(value)); } } else if(this->getValue() > value){ if(this->getLeft() == NULL){ this->setLeft( new BST<T>(value, NULL, NULL, this)); } else{ BST<T>* left = dynamic_cast<BST<T>*>(this->getLeft()); this->setLeft(left->insert(value)); } } return this; } template <class T> BST<T>* BST<T>::search(const T &value){ if(this->getValue() == value) return this; else if(this->getValue() > value && this->getLeft() != NULL){ BST<T>* left = dynamic_cast<BST<T>*>(this->getLeft()); return left->search(value); } else if(this->getValue() < value && this->getRight() != NULL){ BST<T>* right = dynamic_cast<BST<T>*>(this->getRight()); return right->search(value); } else return NULL; } template <class T> BST<T>* BST<T>::remove(const T &value){ if(this->getValue() == value){ if(this->getRight() == NULL && this->getLeft() == NULL){ BST<T>* parent = dynamic_cast<BST<T>*>(this->getParent()); if(parent != NULL){ if( parent->getLeft() == this) parent->setLeft(NULL); else if(parent->getRight() == this) parent->setRight(NULL); return parent; } else return NULL; } else if( this->getRight() != NULL){ BST<T>* parent = dynamic_cast<BST<T>*>(this->getParent()); BST<T>* right = dynamic_cast<BST<T>*>(this->getRight()); right->setParent(parent); return right; } else if( this->getLeft() != NULL){ BST<T>* parent = dynamic_cast<BST<T>*>(this->getParent()); BST<T>* left = dynamic_cast<BST<T>*>(this->getLeft()); left->setParent(parent); return left; } else{ BST<T>* next = dynamic_cast<BST<T>*>(this->successor()); BST<T>* right = dynamic_cast<BST<T>*>(this->getRight()); T val = next->getValue(); right = right->remove(next->getValue()); return this; } } else if(this->getValue() > value && this->getLeft() != NULL){ BST<T>* next = dynamic_cast<BST<T>*>(this->getLeft()); return next->remove(value); } else if(this->getValue() < value && this->getRight() != NULL){ BST<T>* next = dynamic_cast<BST<T>*>(this->getRight()); return next->remove(value); } else return NULL; } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __PROCESS_SSL_TEST_HPP__ #define __PROCESS_SSL_TEST_HPP__ #ifdef USE_SSL_SOCKET #include <openssl/rsa.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <process/io.hpp> #include <process/socket.hpp> #include <process/ssl/utilities.hpp> namespace process { namespace network { namespace openssl { // Forward declare the `reinitialize()` function since we want to // programatically change SSL flags during tests. void reinitialize(); } // namespace openssl { } // namespace network { } // namespace process { /** * A Test fixture that sets up SSL keys and certificates. * * This class sets up a private key and certificate pair at * SSLTest::key_path and SSLTest::certificate_path. * It also sets up an independent 'scrap' pair that can be used to * test an invalid certificate authority chain. These can be found at * SSLTest::scrap_key_path and SSLTest::scrap_certificate_path. * * There are some helper functions like SSLTest::setup_server and * SSLTest::launch_client that factor out common behavior used in * tests. */ class SSLTest : public ::testing::Test { protected: SSLTest() : data("Hello World!") {} /** * @return The path to the authorized private key. */ static const Path& key_path() { static Path path(path::join(os::getcwd(), "key.pem")); return path; } /** * @return The path to the authorized certificate. */ static const Path& certificate_path() { static Path path(path::join(os::getcwd(), "cert.pem")); return path; } /** * @return The path to the unauthorized private key. */ static const Path& scrap_key_path() { static Path path(path::join(os::getcwd(), "scrap_key.pem")); return path; } /** * @return The path to the unauthorized certificate. */ static const Path& scrap_certificate_path() { static Path path(path::join(os::getcwd(), "scrap_cert.pem")); return path; } static void cleanup_directories() { os::rm(key_path().value); os::rm(certificate_path().value); os::rm(scrap_key_path().value); os::rm(scrap_certificate_path().value); } static void SetUpTestCase() { // We store the allocated objects in these results so that we can // have a consolidated 'cleanup()' function. This makes all the // 'EXIT()' calls more readable and less error prone. Result<EVP_PKEY*> private_key = None(); Result<X509*> certificate = None(); Result<EVP_PKEY*> scrap_key = None(); Result<X509*> scrap_certificate = None(); auto cleanup = [&private_key, &certificate, &scrap_key, &scrap_certificate]( bool failure = true) { if (private_key.isSome()) { EVP_PKEY_free(private_key.get()); } if (certificate.isSome()) { X509_free(certificate.get()); } if (scrap_key.isSome()) { EVP_PKEY_free(scrap_key.get()); } if (scrap_certificate.isSome()) { X509_free(scrap_certificate.get()); } // If we are under a failure condition, clean up any files we // already generated. The expected behavior is that they will be // cleaned up in 'TearDownTestCase()'; however, we call ABORT // during 'SetUpTestCase()' failures. if (failure) { cleanup_directories(); } }; // Generate the authority key. private_key = process::network::openssl::generate_private_rsa_key(); if (private_key.isError()) { ABORT("Could not generate private key: " + private_key.error()); } // Figure out the hostname that 'INADDR_LOOPBACK' will bind to. // Set the hostname of the certificate to this hostname so that // hostname verification of the certificate will pass. Try<std::string> hostname = net::getHostname(net::IP(INADDR_LOOPBACK)); if (hostname.isError()) { cleanup(); ABORT("Could not determine hostname of 'INADDR_LOOPBACK': " + hostname.error()); } // Generate an authorized certificate. certificate = process::network::openssl::generate_x509( private_key.get(), private_key.get(), None(), 1, 365, hostname.get()); if (certificate.isError()) { cleanup(); ABORT("Could not generate certificate: " + certificate.error()); } // Write the authority key to disk. Try<Nothing> key_write = process::network::openssl::write_key_file(private_key.get(), key_path()); if (key_write.isError()) { cleanup(); ABORT("Could not write private key to disk: " + key_write.error()); } // Write the authorized certificate to disk. Try<Nothing> certificate_write = process::network::openssl::write_certificate_file( certificate.get(), certificate_path()); if (certificate_write.isError()) { cleanup(); ABORT("Could not write certificate to disk: " + certificate_write.error()); } // Generate a scrap key. scrap_key = process::network::openssl::generate_private_rsa_key(); if (scrap_key.isError()) { cleanup(); ABORT("Could not generate a scrap private key: " + scrap_key.error()); } // Write the scrap key to disk. key_write = process::network::openssl::write_key_file( scrap_key.get(), scrap_key_path()); if (key_write.isError()) { cleanup(); ABORT("Could not write scrap key to disk: " + key_write.error()); } // Generate a scrap certificate. scrap_certificate = process::network::openssl::generate_x509( scrap_key.get(), scrap_key.get()); if (scrap_certificate.isError()) { cleanup(); ABORT("Could not generate a scrap certificate: " + scrap_certificate.error()); } // Write the scrap certificate to disk. certificate_write = process::network::openssl::write_certificate_file( scrap_certificate.get(), scrap_certificate_path()); if (certificate_write.isError()) { cleanup(); ABORT("Could not write scrap certificate to disk: " + certificate_write.error()); } // Since we successfully set up all our state, we call cleanup // with failure set to 'false'. cleanup(false); } static void TearDownTestCase() { // Clean up all the pem files we generated. cleanup_directories(); } virtual void SetUp() { // This unsets all the SSL environment variables. Necessary for // ensuring a clean starting slate between tests. os::unsetenv("SSL_ENABLED"); os::unsetenv("SSL_SUPPORT_DOWNGRADE"); os::unsetenv("SSL_CERT_FILE"); os::unsetenv("SSL_KEY_FILE"); os::unsetenv("SSL_VERIFY_CERT"); os::unsetenv("SSL_REQUIRE_CERT"); os::unsetenv("SSL_VERIFY_DEPTH"); os::unsetenv("SSL_CA_DIR"); os::unsetenv("SSL_CA_FILE"); os::unsetenv("SSL_CIPHERS"); os::unsetenv("SSL_ENABLE_SSL_V3"); os::unsetenv("SSL_ENABLE_TLS_V1_0"); os::unsetenv("SSL_ENABLE_TLS_V1_1"); os::unsetenv("SSL_ENABLE_TLS_V1_2"); } /** * Initializes a listening server. * * @param environment The SSL environment variables to launch the * server socket with. * * @return Socket if successful otherwise an Error. */ Try<process::network::Socket> setup_server( const std::map<std::string, std::string>& environment) { foreachpair ( const std::string& name, const std::string& value, environment) { os::setenv(name, value); } process::network::openssl::reinitialize(); const Try<process::network::Socket> create = process::network::Socket::create(process::network::Socket::SSL); if (create.isError()) { return Error(create.error()); } process::network::Socket server = create.get(); // We need to explicitly bind to INADDR_LOOPBACK so the // certificate we create in this test fixture can be verified. Try<process::network::Address> bind = server.bind(process::network::Address(net::IP(INADDR_LOOPBACK), 0)); if (bind.isError()) { return Error(bind.error()); } const Try<Nothing> listen = server.listen(BACKLOG); if (listen.isError()) { return Error(listen.error()); } return server; } /** * Launches a test SSL client as a subprocess connecting to the * server. * * The subprocess calls the 'ssl-client' binary with the provided * environment. * * @param environment The SSL environment variables to launch the * SSL client subprocess with. * @param use_ssl_socket Whether the SSL client will try to connect * using an SSL socket or a POLL socket. * * @return Subprocess if successful otherwise an Error. */ Try<process::Subprocess> launch_client( const std::map<std::string, std::string>& environment, const process::network::Socket& server, bool use_ssl_socket) { const Try<process::network::Address> address = server.address(); if (address.isError()) { return Error(address.error()); } // Set up arguments to be passed to the 'client-ssl' binary. const std::vector<std::string> argv = { "ssl-client", "--use_ssl=" + stringify(use_ssl_socket), "--server=127.0.0.1", "--port=" + stringify(address.get().port), "--data=" + data}; Result<std::string> path = os::realpath(BUILD_DIR); if (!path.isSome()) { return Error("Could not establish build directory path"); } return process::subprocess( path::join(path.get(), "ssl-client"), argv, process::Subprocess::PIPE(), process::Subprocess::PIPE(), process::Subprocess::FD(STDERR_FILENO), None(), environment); } static constexpr size_t BACKLOG = 5; const std::string data; }; #endif // USE_SSL_SOCKET #endif // __PROCESS_SSL_TEST_HPP__ <commit_msg>SSLTest refactor: Made SSLTest inherit from TemporaryDirectoryTest.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __PROCESS_SSL_TEST_HPP__ #define __PROCESS_SSL_TEST_HPP__ #ifdef USE_SSL_SOCKET #include <string> #include <openssl/rsa.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <process/io.hpp> #include <process/socket.hpp> #include <process/ssl/utilities.hpp> #include <stout/none.hpp> #include <stout/option.hpp> #include <stout/try.hpp> #include <stout/result.hpp> #include <stout/tests/utils.hpp> namespace process { namespace network { namespace openssl { // Forward declare the `reinitialize()` function since we want to // programatically change SSL flags during tests. void reinitialize(); } // namespace openssl { } // namespace network { } // namespace process { /** * A Test fixture that sets up SSL keys and certificates. * * This class sets up a private key and certificate pair at * SSLTest::key_path and SSLTest::certificate_path. * It also sets up an independent 'scrap' pair that can be used to * test an invalid certificate authority chain. These can be found at * SSLTest::scrap_key_path and SSLTest::scrap_certificate_path. * * There are some helper functions like SSLTest::setup_server and * SSLTest::launch_client that factor out common behavior used in * tests. */ class SSLTest : public TemporaryDirectoryTest { protected: SSLTest() : data("Hello World!") {} /** * @return The path to the authorized private key. */ Path key_path() { return Path(path::join(os::getcwd(), "key.pem")); } /** * @return The path to the authorized certificate. */ Path certificate_path() { return Path(path::join(os::getcwd(), "cert.pem")); } /** * @return The path to the unauthorized private key. */ Path scrap_key_path() { return Path(path::join(os::getcwd(), "scrap_key.pem")); } /** * @return The path to the unauthorized certificate. */ Path scrap_certificate_path() { return Path(path::join(os::getcwd(), "scrap_cert.pem")); } virtual void SetUp() { TemporaryDirectoryTest::SetUp(); // This unsets all the SSL environment variables. Necessary for // ensuring a clean starting slate between tests. os::unsetenv("SSL_ENABLED"); os::unsetenv("SSL_SUPPORT_DOWNGRADE"); os::unsetenv("SSL_CERT_FILE"); os::unsetenv("SSL_KEY_FILE"); os::unsetenv("SSL_VERIFY_CERT"); os::unsetenv("SSL_REQUIRE_CERT"); os::unsetenv("SSL_VERIFY_DEPTH"); os::unsetenv("SSL_CA_DIR"); os::unsetenv("SSL_CA_FILE"); os::unsetenv("SSL_CIPHERS"); os::unsetenv("SSL_ENABLE_SSL_V3"); os::unsetenv("SSL_ENABLE_TLS_V1_0"); os::unsetenv("SSL_ENABLE_TLS_V1_1"); os::unsetenv("SSL_ENABLE_TLS_V1_2"); // We store the allocated objects in these results so that we can // have a consolidated 'cleanup()' function. This makes all the // 'EXIT()' calls more readable and less error prone. Result<EVP_PKEY*> private_key = None(); Result<X509*> certificate = None(); Result<EVP_PKEY*> scrap_key = None(); Result<X509*> scrap_certificate = None(); auto cleanup = [&private_key, &certificate, &scrap_key, &scrap_certificate]( const Option<std::string> abort_message = None()) { if (private_key.isSome()) { EVP_PKEY_free(private_key.get()); } if (certificate.isSome()) { X509_free(certificate.get()); } if (scrap_key.isSome()) { EVP_PKEY_free(scrap_key.get()); } if (scrap_certificate.isSome()) { X509_free(scrap_certificate.get()); } // We abort here because failure during setup indicates that something // is horribly and irrecoverably wrong. if (abort_message.isSome()) { ABORT(abort_message.get()); } }; // Generate the authority key. private_key = process::network::openssl::generate_private_rsa_key(); if (private_key.isError()) { cleanup("Could not generate private key: " + private_key.error()); } // Figure out the hostname that 'INADDR_LOOPBACK' will bind to. // Set the hostname of the certificate to this hostname so that // hostname verification of the certificate will pass. Try<std::string> hostname = net::getHostname(net::IP(INADDR_LOOPBACK)); if (hostname.isError()) { cleanup("Could not determine hostname of 'INADDR_LOOPBACK': " + hostname.error()); } // Generate an authorized certificate. certificate = process::network::openssl::generate_x509( private_key.get(), private_key.get(), None(), 1, 365, hostname.get()); if (certificate.isError()) { cleanup("Could not generate certificate: " + certificate.error()); } // Write the authority key to disk. Try<Nothing> key_write = process::network::openssl::write_key_file(private_key.get(), key_path()); if (key_write.isError()) { cleanup("Could not write private key to disk: " + key_write.error()); } // Write the authorized certificate to disk. Try<Nothing> certificate_write = process::network::openssl::write_certificate_file( certificate.get(), certificate_path()); if (certificate_write.isError()) { cleanup("Could not write certificate to disk: " + certificate_write.error()); } // Generate a scrap key. scrap_key = process::network::openssl::generate_private_rsa_key(); if (scrap_key.isError()) { cleanup("Could not generate a scrap private key: " + scrap_key.error()); } // Write the scrap key to disk. key_write = process::network::openssl::write_key_file( scrap_key.get(), scrap_key_path()); if (key_write.isError()) { cleanup("Could not write scrap key to disk: " + key_write.error()); } // Generate a scrap certificate. scrap_certificate = process::network::openssl::generate_x509( scrap_key.get(), scrap_key.get()); if (scrap_certificate.isError()) { cleanup("Could not generate a scrap certificate: " + scrap_certificate.error()); } // Write the scrap certificate to disk. certificate_write = process::network::openssl::write_certificate_file( scrap_certificate.get(), scrap_certificate_path()); if (certificate_write.isError()) { cleanup("Could not write scrap certificate to disk: " + certificate_write.error()); } // Since we successfully set up all our state, we call cleanup // without an abort message (so as not to abort). cleanup(); } /** * Initializes a listening server. * * @param environment The SSL environment variables to launch the * server socket with. * * @return Socket if successful otherwise an Error. */ Try<process::network::Socket> setup_server( const std::map<std::string, std::string>& environment) { foreachpair ( const std::string& name, const std::string& value, environment) { os::setenv(name, value); } process::network::openssl::reinitialize(); const Try<process::network::Socket> create = process::network::Socket::create(process::network::Socket::SSL); if (create.isError()) { return Error(create.error()); } process::network::Socket server = create.get(); // We need to explicitly bind to INADDR_LOOPBACK so the // certificate we create in this test fixture can be verified. Try<process::network::Address> bind = server.bind(process::network::Address(net::IP(INADDR_LOOPBACK), 0)); if (bind.isError()) { return Error(bind.error()); } const Try<Nothing> listen = server.listen(BACKLOG); if (listen.isError()) { return Error(listen.error()); } return server; } /** * Launches a test SSL client as a subprocess connecting to the * server. * * The subprocess calls the 'ssl-client' binary with the provided * environment. * * @param environment The SSL environment variables to launch the * SSL client subprocess with. * @param use_ssl_socket Whether the SSL client will try to connect * using an SSL socket or a POLL socket. * * @return Subprocess if successful otherwise an Error. */ Try<process::Subprocess> launch_client( const std::map<std::string, std::string>& environment, const process::network::Socket& server, bool use_ssl_socket) { const Try<process::network::Address> address = server.address(); if (address.isError()) { return Error(address.error()); } // Set up arguments to be passed to the 'client-ssl' binary. const std::vector<std::string> argv = { "ssl-client", "--use_ssl=" + stringify(use_ssl_socket), "--server=127.0.0.1", "--port=" + stringify(address.get().port), "--data=" + data}; Result<std::string> path = os::realpath(BUILD_DIR); if (!path.isSome()) { return Error("Could not establish build directory path"); } return process::subprocess( path::join(path.get(), "ssl-client"), argv, process::Subprocess::PIPE(), process::Subprocess::PIPE(), process::Subprocess::FD(STDERR_FILENO), None(), environment); } static constexpr size_t BACKLOG = 5; const std::string data; }; #endif // USE_SSL_SOCKET #endif // __PROCESS_SSL_TEST_HPP__ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of 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. * * $Id: test_common.cpp 36632 2010-05-12 19:17:08Z rusu $ * */ #include <gtest/gtest.h> #include <pcl/common/common.h> #include <pcl/common/distances.h> #include <pcl/common/eigen.h> #include <pcl/point_types.h> #include <sys/time.h> using pcl::PointXYZ; TEST (PCL, Common) { PointXYZ p1, p2, p3; p1.x = 1; p1.y = p1.z = 0; p2.y = 1; p2.x = p2.z = 0; p3.z = 1; p3.x = p3.y = 0; double radius = getCircumcircleRadius (p1, p2, p3); EXPECT_NEAR (radius, 0.816497, 1e-4); Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0); double point2line_disance = sqrt (pcl::sqrPointToLineDistance (pt, line_pt, line_dir)); EXPECT_NEAR (point2line_disance, sqrt(2)/2, 1e-4); } TEST (PCL, Eigen) { Eigen::Matrix3f mat, vec; mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05; Eigen::Vector3f val; pcl::eigen33 (mat, vec, val); EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4); EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4); EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4); EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4); Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat); EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4); EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4); Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues (); EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4); } /* ---[ */ int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <commit_msg>Fix: bug 57<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of 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. * * $Id: test_common.cpp 36632 2010-05-12 19:17:08Z rusu $ * */ #include <gtest/gtest.h> #include <pcl/common/common.h> #include <pcl/common/distances.h> #include <pcl/common/eigen.h> #include <pcl/point_types.h> #include <sys/time.h> using pcl::PointXYZ; TEST (PCL, Common) { PointXYZ p1, p2, p3; p1.x = 1; p1.y = p1.z = 0; p2.y = 1; p2.x = p2.z = 0; p3.z = 1; p3.x = p3.y = 0; double radius = getCircumcircleRadius (p1, p2, p3); EXPECT_NEAR (radius, 0.816497, 1e-4); Eigen::Vector4f pt (1,0,0,0), line_pt (0,0,0,0), line_dir (1,1,0,0); double point2line_disance = sqrt (pcl::sqrPointToLineDistance (pt, line_pt, line_dir)); EXPECT_NEAR (point2line_disance, sqrt(2.0)/2, 1e-4); } TEST (PCL, Eigen) { Eigen::Matrix3f mat, vec; mat << 0.000536227, -1.56178e-05, -9.47391e-05, -1.56178e-05, 0.000297322, -0.000148785, -9.47391e-05, -0.000148785, 9.7827e-05; Eigen::Vector3f val; pcl::eigen33 (mat, vec, val); EXPECT_NEAR (fabs (vec (0, 0)), 0.168841, 1e-4); EXPECT_NEAR (fabs (vec (0, 1)), 0.161623, 1e-4); EXPECT_NEAR (fabs (vec (0, 2)), 0.972302, 1e-4); EXPECT_NEAR (fabs (vec (1, 0)), 0.451632, 1e-4); EXPECT_NEAR (fabs (vec (1, 1)), 0.889498, 1e-4); EXPECT_NEAR (fabs (vec (1, 2)), 0.0694328, 1e-4); EXPECT_NEAR (fabs (vec (2, 0)), 0.876082, 1e-4); EXPECT_NEAR (fabs (vec (2, 1)), 0.4274, 1e-4); EXPECT_NEAR (fabs (vec (2, 2)), 0.223178, 1e-4); EXPECT_NEAR (val (0), 2.86806e-06, 1e-4); EXPECT_NEAR (val (1), 0.00037165, 1e-4); EXPECT_NEAR (val (2), 0.000556858, 1e-4); Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eig (mat); EXPECT_NEAR (eig.eigenvectors () (0, 0), -0.168841, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 1), 0.161623, 1e-4); EXPECT_NEAR (eig.eigenvectors () (0, 2), 0.972302, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 0), -0.451632, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 1), -0.889498, 1e-4); EXPECT_NEAR (eig.eigenvectors () (1, 2), 0.0694328, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 0), -0.876083, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 1), 0.4274, 1e-4); EXPECT_NEAR (eig.eigenvectors () (2, 2), -0.223178, 1e-4); EXPECT_NEAR (eig.eigenvalues () (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eig.eigenvalues () (1), 0.00037165, 1e-4); EXPECT_NEAR (eig.eigenvalues () (2), 0.000556858, 1e-4); Eigen::Vector3f eivals = mat.selfadjointView<Eigen::Lower>().eigenvalues (); EXPECT_NEAR (eivals (0), 2.86806e-06, 1e-4); EXPECT_NEAR (eivals (1), 0.00037165, 1e-4); EXPECT_NEAR (eivals (2), 0.000556858, 1e-4); } /* ---[ */ int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxesTransformWidget.h" #include "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkHandleWidget.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkWidgetEventTranslator.h" #include "vtkWidgetCallbackMapper.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include "vtkRenderWindow.h" vtkStandardNewMacro(vtkAxesTransformWidget); //---------------------------------------------------------------------------- vtkAxesTransformWidget::vtkAxesTransformWidget() { this->WidgetState = vtkAxesTransformWidget::Start; this->ManagesCursor = 1; this->CurrentHandle = 0; // The widgets for moving the end points. They observe this widget (i.e., // this widget is the parent to the handles). this->OriginWidget = vtkHandleWidget::New(); this->OriginWidget->SetPriority(this->Priority-0.01); this->OriginWidget->SetParent(this); this->OriginWidget->ManagesCursorOff(); this->SelectionWidget = vtkHandleWidget::New(); this->SelectionWidget->SetPriority(this->Priority-0.01); this->SelectionWidget->SetParent(this); this->SelectionWidget->ManagesCursorOff(); // Define widget events this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkWidgetEvent::Select, this, vtkAxesTransformWidget::SelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkWidgetEvent::EndSelect, this, vtkAxesTransformWidget::EndSelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkAxesTransformWidget::MoveAction); } //---------------------------------------------------------------------------- vtkAxesTransformWidget::~vtkAxesTransformWidget() { this->OriginWidget->Delete(); this->SelectionWidget->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::SetEnabled(int enabling) { // We do this step first because it sets the CurrentRenderer this->Superclass::SetEnabled(enabling); // We defer enabling the handles until the selection process begins if ( enabling ) { // Don't actually turn these on until cursor is near the end points or the line. this->CreateDefaultRepresentation(); this->OriginWidget->SetRepresentation(reinterpret_cast<vtkAxesTransformRepresentation*> (this->WidgetRep)->GetOriginRepresentation()); this->OriginWidget->SetInteractor(this->Interactor); this->OriginWidget->GetRepresentation()->SetRenderer(this->CurrentRenderer); this->SelectionWidget->SetRepresentation(reinterpret_cast<vtkAxesTransformRepresentation*> (this->WidgetRep)->GetSelectionRepresentation()); this->SelectionWidget->SetInteractor(this->Interactor); this->SelectionWidget->GetRepresentation()->SetRenderer(this->CurrentRenderer); } else { this->OriginWidget->SetEnabled(0); this->SelectionWidget->SetEnabled(0); } } //---------------------------------------------------------------------- void vtkAxesTransformWidget::SelectAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); if ( self->WidgetRep->GetInteractionState() == vtkAxesTransformRepresentation::Outside ) { return; } // Get the event position int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; // We are definitely selected self->WidgetState = vtkAxesTransformWidget::Active; self->GrabFocus(self->EventCallbackCommand); double e[2]; e[0] = static_cast<double>(X); e[1] = static_cast<double>(Y); reinterpret_cast<vtkAxesTransformRepresentation*>(self->WidgetRep)-> StartWidgetInteraction(e); self->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); //for the handles self->StartInteraction(); self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::MoveAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); // compute some info we need for all cases int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; // See whether we're active if ( self->WidgetState == vtkAxesTransformWidget::Start ) { self->Interactor->Disable(); //avoid extra renders self->OriginWidget->SetEnabled(0); self->SelectionWidget->SetEnabled(0); int oldState = self->WidgetRep->GetInteractionState(); int state = self->WidgetRep->ComputeInteractionState(X,Y); int changed; // Determine if we are near the end points or the line if ( state == vtkAxesTransformRepresentation::Outside ) { changed = self->RequestCursorShape(VTK_CURSOR_DEFAULT); } else //must be near something { changed = self->RequestCursorShape(VTK_CURSOR_HAND); if ( state == vtkAxesTransformRepresentation::OnOrigin ) { self->OriginWidget->SetEnabled(1); } else //if ( state == vtkAxesTransformRepresentation::OnXXX ) { self->SelectionWidget->SetEnabled(1); changed = 1; //movement along the line always needs render } } self->Interactor->Enable(); //avoid extra renders if ( changed || oldState != state ) { self->Render(); } } else //if ( self->WidgetState == vtkAxesTransformWidget::Active ) { // moving something double e[2]; e[0] = static_cast<double>(X); e[1] = static_cast<double>(Y); self->InvokeEvent(vtkCommand::MouseMoveEvent,NULL); //handles observe this reinterpret_cast<vtkAxesTransformRepresentation*>(self->WidgetRep)-> WidgetInteraction(e); self->InvokeEvent(vtkCommand::InteractionEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); self->Render(); } } //---------------------------------------------------------------------- void vtkAxesTransformWidget::EndSelectAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); if ( self->WidgetState == vtkAxesTransformWidget::Start ) { return; } // Return state to not active self->WidgetState = vtkAxesTransformWidget::Start; self->ReleaseFocus(); self->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); //handles observe this self->EventCallbackCommand->SetAbortFlag(1); self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); self->Superclass::EndInteraction(); self->Render(); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::CreateDefaultRepresentation() { if ( ! this->WidgetRep ) { this->WidgetRep = vtkAxesTransformRepresentation::New(); } } //---------------------------------------------------------------------------- void vtkAxesTransformWidget::SetProcessEvents(int pe) { this->Superclass::SetProcessEvents(pe); this->OriginWidget->SetProcessEvents(pe); this->SelectionWidget->SetProcessEvents(pe); } //---------------------------------------------------------------------------- void vtkAxesTransformWidget::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <commit_msg>Reorder initialization so that representations have renderers.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkAxesTransformWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxesTransformWidget.h" #include "vtkAxesTransformRepresentation.h" #include "vtkPointHandleRepresentation3D.h" #include "vtkHandleWidget.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRendererCollection.h" #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkWidgetEventTranslator.h" #include "vtkWidgetCallbackMapper.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include "vtkRenderWindow.h" vtkStandardNewMacro(vtkAxesTransformWidget); //---------------------------------------------------------------------------- vtkAxesTransformWidget::vtkAxesTransformWidget() { this->WidgetState = vtkAxesTransformWidget::Start; this->ManagesCursor = 1; this->CurrentHandle = 0; // The widgets for moving the end points. They observe this widget (i.e., // this widget is the parent to the handles). this->OriginWidget = vtkHandleWidget::New(); this->OriginWidget->SetPriority(this->Priority-0.01); this->OriginWidget->SetParent(this); this->OriginWidget->ManagesCursorOff(); this->SelectionWidget = vtkHandleWidget::New(); this->SelectionWidget->SetPriority(this->Priority-0.01); this->SelectionWidget->SetParent(this); this->SelectionWidget->ManagesCursorOff(); // Define widget events this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkWidgetEvent::Select, this, vtkAxesTransformWidget::SelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkWidgetEvent::EndSelect, this, vtkAxesTransformWidget::EndSelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkAxesTransformWidget::MoveAction); } //---------------------------------------------------------------------------- vtkAxesTransformWidget::~vtkAxesTransformWidget() { this->OriginWidget->Delete(); this->SelectionWidget->Delete(); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::SetEnabled(int enabling) { // We defer enabling the handles until the selection process begins if ( enabling ) { if ( ! this->CurrentRenderer ) { int X=this->Interactor->GetEventPosition()[0]; int Y=this->Interactor->GetEventPosition()[1]; this->SetCurrentRenderer(this->Interactor->FindPokedRenderer(X,Y)); if (this->CurrentRenderer == NULL) { return; } } // Don't actually turn these on until cursor is near the end points or the line. this->CreateDefaultRepresentation(); vtkHandleRepresentation * originRep = reinterpret_cast<vtkAxesTransformRepresentation*> (this->WidgetRep)->GetOriginRepresentation(); originRep->SetRenderer(this->CurrentRenderer); this->OriginWidget->SetRepresentation(originRep); this->OriginWidget->SetInteractor(this->Interactor); vtkHandleRepresentation * selectionRep = reinterpret_cast<vtkAxesTransformRepresentation*> (this->WidgetRep)->GetSelectionRepresentation(); selectionRep->SetRenderer(this->CurrentRenderer); this->SelectionWidget->SetRepresentation(selectionRep); this->SelectionWidget->SetInteractor(this->Interactor); // We do this step first because it sets the CurrentRenderer this->Superclass::SetEnabled(enabling); } else { this->OriginWidget->SetEnabled(0); this->SelectionWidget->SetEnabled(0); } } //---------------------------------------------------------------------- void vtkAxesTransformWidget::SelectAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); if ( self->WidgetRep->GetInteractionState() == vtkAxesTransformRepresentation::Outside ) { return; } // Get the event position int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; // We are definitely selected self->WidgetState = vtkAxesTransformWidget::Active; self->GrabFocus(self->EventCallbackCommand); double e[2]; e[0] = static_cast<double>(X); e[1] = static_cast<double>(Y); reinterpret_cast<vtkAxesTransformRepresentation*>(self->WidgetRep)-> StartWidgetInteraction(e); self->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); //for the handles self->StartInteraction(); self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::MoveAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); // compute some info we need for all cases int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; // See whether we're active if ( self->WidgetState == vtkAxesTransformWidget::Start ) { self->Interactor->Disable(); //avoid extra renders self->OriginWidget->SetEnabled(0); self->SelectionWidget->SetEnabled(0); int oldState = self->WidgetRep->GetInteractionState(); int state = self->WidgetRep->ComputeInteractionState(X,Y); int changed; // Determine if we are near the end points or the line if ( state == vtkAxesTransformRepresentation::Outside ) { changed = self->RequestCursorShape(VTK_CURSOR_DEFAULT); } else //must be near something { changed = self->RequestCursorShape(VTK_CURSOR_HAND); if ( state == vtkAxesTransformRepresentation::OnOrigin ) { self->OriginWidget->SetEnabled(1); } else //if ( state == vtkAxesTransformRepresentation::OnXXX ) { self->SelectionWidget->SetEnabled(1); changed = 1; //movement along the line always needs render } } self->Interactor->Enable(); //avoid extra renders if ( changed || oldState != state ) { self->Render(); } } else //if ( self->WidgetState == vtkAxesTransformWidget::Active ) { // moving something double e[2]; e[0] = static_cast<double>(X); e[1] = static_cast<double>(Y); self->InvokeEvent(vtkCommand::MouseMoveEvent,NULL); //handles observe this reinterpret_cast<vtkAxesTransformRepresentation*>(self->WidgetRep)-> WidgetInteraction(e); self->InvokeEvent(vtkCommand::InteractionEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); self->Render(); } } //---------------------------------------------------------------------- void vtkAxesTransformWidget::EndSelectAction(vtkAbstractWidget *w) { vtkAxesTransformWidget *self = reinterpret_cast<vtkAxesTransformWidget*>(w); if ( self->WidgetState == vtkAxesTransformWidget::Start ) { return; } // Return state to not active self->WidgetState = vtkAxesTransformWidget::Start; self->ReleaseFocus(); self->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); //handles observe this self->EventCallbackCommand->SetAbortFlag(1); self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); self->Superclass::EndInteraction(); self->Render(); } //---------------------------------------------------------------------- void vtkAxesTransformWidget::CreateDefaultRepresentation() { if ( ! this->WidgetRep ) { this->WidgetRep = vtkAxesTransformRepresentation::New(); } } //---------------------------------------------------------------------------- void vtkAxesTransformWidget::SetProcessEvents(int pe) { this->Superclass::SetProcessEvents(pe); this->OriginWidget->SetProcessEvents(pe); this->SelectionWidget->SetProcessEvents(pe); } //---------------------------------------------------------------------------- void vtkAxesTransformWidget::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/reduce.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_HEADER #define C7A_API_REDUCE_HEADER #include <c7a/api/dia.hpp> #include <c7a/api/dop_node.hpp> #include <c7a/common/functional.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_post_table.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type ValueType, which is the result type of the * reduce_function. * * \tparam ValueType Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the * last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function. * \tparam RobustKey Whether to reuse the key once extracted in during pre reduce * (false) or let the post reduce extract the key again (true). */ template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename ReduceFunction, const bool RobustKey, const bool SendPair> class ReduceNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using Value = typename common::FunctionTraits<ReduceFunction>::result_type; using ReduceArg = typename common::FunctionTraits<ReduceFunction> ::template arg<0>; typedef std::pair<Key, Value> KeyValuePair; using Super::context_; using Super::result_file_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(const ParentDIARef& parent, KeyExtractor key_extractor, ReduceFunction reduce_function, StatsNode* stats_node) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, "Reduce", stats_node), key_extractor_(key_extractor), reduce_function_(reduce_function), channel_(parent.ctx().data_manager().GetNewChannel()), emitters_(channel_->OpenWriters()), reduce_pre_table_(parent.ctx().num_workers(), key_extractor, reduce_function_, emitters_) { // Hook PreOp auto pre_op_fn = [=](const ValueType& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain); channel_->OnClose(std::bind(&DIABase::WriteChannelStats, this, channel_)); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() final { MainOp(); } void PushData() final { // TODO(ms): this is not what should happen: every thing is reduced again: using ReduceTable = core::ReducePostTable<ValueType, KeyExtractor, ReduceFunction, false, SendPair>; ReduceTable table(key_extractor_, reduce_function_, DIANode<ValueType>::callbacks()); if (RobustKey) { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<Value>()); } table.Flush(); } else { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<KeyValuePair>()); } table.Flush(); } } void Dispose() final { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { return FunctionStack<ValueType>(); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() final { return "[ReduceNode] Id: " + result_file_.ToString(); } private: //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; data::ChannelPtr channel_; std::vector<data::BlockWriter> emitters_; core::ReducePreTable<Key, Value, KeyExtractor, ReduceFunction, RobustKey> reduce_pre_table_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(const ValueType& input) { reduce_pre_table_.Insert(input); } //!Receive elements from other workers. auto MainOp() { LOG << ToString() << " running main op"; //Flush hash table before the postOp reduce_pre_table_.Flush(); reduce_pre_table_.CloseEmitter(); channel_->Close(); } }; template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceBy( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("ReduceBy", NodeType::DOP); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, true, false>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename ReduceFunction> auto DIARef<ValueType, Stack>::ReducePair( const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert(common::is_pair<ValueType>::value, "ValueType is not a pair"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, typename ValueType::second_type>::value, "ReduceFunction has the wrong output type"); using Key = typename ValueType::first_type; StatsNode* stats_node = AddChildStatsNode("ReducePair", NodeType::DOP); using ReduceResultNode = ReduceNode<ValueType, DIARef, std::function<Key(Key)>, ReduceFunction, false, true>; auto shared_node = std::make_shared<ReduceResultNode>(*this, [](Key key) { //This function should not be //called, it is only here to //give the key type to the //hashtables. assert(1 == 0); key = key; return Key(); }, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<ValueType, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceByKey( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor>:: template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("Reduce", NodeType::DOP); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, false, false>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_REDUCE_HEADER /******************************************************************************/ <commit_msg>Revert "use bind instead of lambda"<commit_after>/******************************************************************************* * c7a/api/reduce.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_HEADER #define C7A_API_REDUCE_HEADER #include <c7a/api/dia.hpp> #include <c7a/api/dop_node.hpp> #include <c7a/common/functional.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_post_table.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <functional> #include <string> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type ValueType, which is the result type of the * reduce_function. * * \tparam ValueType Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the * last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function. * \tparam RobustKey Whether to reuse the key once extracted in during pre reduce * (false) or let the post reduce extract the key again (true). */ template <typename ValueType, typename ParentDIARef, typename KeyExtractor, typename ReduceFunction, const bool RobustKey, const bool SendPair> class ReduceNode : public DOpNode<ValueType> { static const bool debug = false; using Super = DOpNode<ValueType>; using Key = typename common::FunctionTraits<KeyExtractor>::result_type; using Value = typename common::FunctionTraits<ReduceFunction>::result_type; using ReduceArg = typename common::FunctionTraits<ReduceFunction> ::template arg<0>; typedef std::pair<Key, Value> KeyValuePair; using Super::context_; using Super::result_file_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param parent Parent DIARef. * and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(const ParentDIARef& parent, KeyExtractor key_extractor, ReduceFunction reduce_function, StatsNode* stats_node) : DOpNode<ValueType>(parent.ctx(), { parent.node() }, "Reduce", stats_node), key_extractor_(key_extractor), reduce_function_(reduce_function), channel_(parent.ctx().data_manager().GetNewChannel()), emitters_(channel_->OpenWriters()), reduce_pre_table_(parent.ctx().num_workers(), key_extractor, reduce_function_, emitters_) { // Hook PreOp auto pre_op_fn = [=](const ValueType& input) { PreOp(input); }; // close the function stack with our pre op and register it at // parent node for output auto lop_chain = parent.stack().push(pre_op_fn).emit(); parent.node()->RegisterChild(lop_chain); channel_->OnClose([this]() { this->WriteChannelStats(this->channel_); }); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void Execute() final { MainOp(); } void PushData() final { // TODO(ms): this is not what should happen: every thing is reduced again: using ReduceTable = core::ReducePostTable<ValueType, KeyExtractor, ReduceFunction, false, SendPair>; ReduceTable table(key_extractor_, reduce_function_, DIANode<ValueType>::callbacks()); if (RobustKey) { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<Value>()); } table.Flush(); } else { //we actually want to wire up callbacks in the ctor and NOT use this blocking method auto reader = channel_->OpenReader(); sLOG << "reading data from" << channel_->id() << "to push into post table which flushes to" << result_file_.ToString(); while (reader.HasNext()) { table.Insert(reader.template Next<KeyValuePair>()); } table.Flush(); } } void Dispose() final { } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { return FunctionStack<ValueType>(); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() final { return "[ReduceNode] Id: " + result_file_.ToString(); } private: //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; data::ChannelPtr channel_; std::vector<data::BlockWriter> emitters_; core::ReducePreTable<Key, Value, KeyExtractor, ReduceFunction, RobustKey> reduce_pre_table_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(const ValueType& input) { reduce_pre_table_.Insert(input); } //!Receive elements from other workers. auto MainOp() { LOG << ToString() << " running main op"; //Flush hash table before the postOp reduce_pre_table_.Flush(); reduce_pre_table_.CloseEmitter(); channel_->Close(); } }; template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceBy( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor> ::template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("ReduceBy", NodeType::DOP); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, true, false>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename ReduceFunction> auto DIARef<ValueType, Stack>::ReducePair( const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert(common::is_pair<ValueType>::value, "ValueType is not a pair"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< typename ValueType::second_type, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, typename ValueType::second_type>::value, "ReduceFunction has the wrong output type"); using Key = typename ValueType::first_type; StatsNode* stats_node = AddChildStatsNode("ReducePair", NodeType::DOP); using ReduceResultNode = ReduceNode<ValueType, DIARef, std::function<Key(Key)>, ReduceFunction, false, true>; auto shared_node = std::make_shared<ReduceResultNode>(*this, [](Key key) { //This function should not be //called, it is only here to //give the key type to the //hashtables. assert(1 == 0); key = key; return Key(); }, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<ValueType, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } template <typename ValueType, typename Stack> template <typename KeyExtractor, typename ReduceFunction> auto DIARef<ValueType, Stack>::ReduceByKey( const KeyExtractor &key_extractor, const ReduceFunction &reduce_function) const { using DOpResult = typename common::FunctionTraits<ReduceFunction>::result_type; static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<0> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_convertible< ValueType, typename common::FunctionTraits<ReduceFunction>::template arg<1> >::value, "ReduceFunction has the wrong input type"); static_assert( std::is_same< DOpResult, ValueType>::value, "ReduceFunction has the wrong output type"); static_assert( std::is_same< typename std::decay<typename common::FunctionTraits<KeyExtractor>:: template arg<0> >::type, ValueType>::value, "KeyExtractor has the wrong input type"); StatsNode* stats_node = AddChildStatsNode("Reduce", NodeType::DOP); using ReduceResultNode = ReduceNode<DOpResult, DIARef, KeyExtractor, ReduceFunction, false, false>; auto shared_node = std::make_shared<ReduceResultNode>(*this, key_extractor, reduce_function, stats_node); auto reduce_stack = shared_node->ProduceStack(); return DIARef<DOpResult, decltype(reduce_stack)>( shared_node, reduce_stack, { stats_node }); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_REDUCE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>#include "Limiter.h" #include "Testing.h" #include <iostream> static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); } static constexpr auto oneSecond = std::chrono::seconds(1); std::ostream& operator<<(std::ostream& os, HttpResult::Code code) { const auto str = code == HttpResult::Code::Ok ? "Ok (200)" : code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" : "Unknown code"; os << str; return os; } template <typename Clock, typename Duration> std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint) { const static auto start = timepoint.time_since_epoch().count(); return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000); } static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) limiter.ValidateRequest(); while (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } struct TimeStamps { const std::chrono::time_point<std::chrono::high_resolution_clock> firstAcceptedRequest; const std::chrono::time_point<std::chrono::high_resolution_clock> lastAcceptedRequest; }; static auto TestWithPeakLoadInTheBeginning(Limiter& limiter) { // Accepting the requests until we hit the limit. const auto firstAcceptedRequestTime = CurrentTime(); for (int i = 0; i < limiter.maxRPS(); ++i) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } const auto lastAcceptedRequestTime = CurrentTime(); // Not accepting more requests within current second. while (CurrentTime() < firstAcceptedRequestTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } // Still not accepting requests if less than one second has elapsed after the first request. if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_until(firstAcceptedRequestTime + std::chrono::milliseconds(900)); if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); return TimeStamps{ firstAcceptedRequestTime, lastAcceptedRequestTime }; } static auto TestWithPeakLoadInTheBeginning_SingleIteration(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); // Herewith we ensure that NOT MORE than maxAllowedRps requests are allowed per second. // It is possible that the limiter will allow a bit LESS, though, hence this "delta" allowance // in the assertion below. constexpr auto delayDueToTimerIssueObtainedEmpirically = std::chrono::milliseconds(42); std::this_thread::sleep_until(timeStamps.firstAcceptedRequest + oneSecond + delayDueToTimerIssueObtainedEmpirically); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestWithPeakLoadInTheBeginning_MultipleIterations(int maxAllowedRps, int iterations) { Limiter limiter(maxAllowedRps, 100); for (int i = 0; i < iterations; ++i) { const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); std::this_thread::sleep_until(timeStamps.lastAcceptedRequest + oneSecond); } } static auto TestWithEvenLoad(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps); for (int iterations = 0; iterations < 5; ++iterations) { int requestsSent = 0; const auto startTime = CurrentTime(); while (requestsSent < maxAllowedRps && CurrentTime() < startTime + oneSecond) { ++requestsSent; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::Ok) std::cout << "iterations = " << iterations << "; requestsSent = " << requestsSent << '\n'; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); std::this_thread::sleep_for(intervalBetweenRequests); } const auto lastValidRequestTime = CurrentTime(); while (CurrentTime() < startTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_for(intervalBetweenRequests); } std::this_thread::sleep_until(lastValidRequestTime + oneSecond); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } } static auto TestWithAdjacentPeaks(int maxAllowedRps) { const auto startTime = CurrentTime(); Limiter limiter(maxAllowedRps, 100); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900)); int requestsSent = 0; while (requestsSent < maxAllowedRps * 0.8) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500)); while (requestsSent < maxAllowedRps) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::cout << "requestsSent == " << requestsSent << '\n'; while (CurrentTime() < startTime + std::chrono::milliseconds(1900)) { requestsSent++; const auto result = limiter.ValidateRequest(); if (result != HttpResult::Code::TooManyRequests) std::cout << "requestsSent == " << requestsSent << '\n'; ASSERT_EQUAL(result, HttpResult::Code::TooManyRequests); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000)); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } namespace LimiterSpecs { static constexpr int minRPS = 1; static constexpr int maxRPS = 100'000; }; int main() { // Failing tests are commented out. try { TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS); TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS); TestWithPeakLoadInTheBeginning_SingleIteration(LimiterSpecs::maxRPS); //TestWithPeakLoadInTheBeginning_MultipleIterations(LimiterSpecs::maxRPS, 10); TestWithAdjacentPeaks(LimiterSpecs::maxRPS); TestWithEvenLoad(LimiterSpecs::maxRPS); std::cout << "All Tests passed successfully\n"; } catch (AssertionException& e) { std::cout << "One or more of tests failed: " << e.what() << '\n'; } system("pause"); return 0; } <commit_msg>Tests - remove diagnostic output<commit_after>#include "Limiter.h" #include "Testing.h" #include <iostream> static auto CurrentTime() { return std::chrono::high_resolution_clock::now(); } static constexpr auto oneSecond = std::chrono::seconds(1); std::ostream& operator<<(std::ostream& os, HttpResult::Code code) { const auto str = code == HttpResult::Code::Ok ? "Ok (200)" : code == HttpResult::Code::TooManyRequests ? "Too many requests (429)" : "Unknown code"; os << str; return os; } template <typename Clock, typename Duration> std::string millisecondsSinceStart(std::chrono::time_point<Clock, Duration> timepoint) { const static auto start = timepoint.time_since_epoch().count(); return std::to_string((timepoint.time_since_epoch().count() - start) / 1'000'000); } static auto TestAllRequestsBelowMaxAreAccepted(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestAllRequestsAboveMaxAreDeclined(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto startTime = std::chrono::high_resolution_clock::now(); for (int i = 0; i < maxAllowedRps; ++i) if (CurrentTime() < startTime + oneSecond) limiter.ValidateRequest(); while (CurrentTime() < startTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } struct TimeStamps { const std::chrono::time_point<std::chrono::high_resolution_clock> firstAcceptedRequest; const std::chrono::time_point<std::chrono::high_resolution_clock> lastAcceptedRequest; }; static auto TestWithPeakLoadInTheBeginning(Limiter& limiter) { // Accepting the requests until we hit the limit. const auto firstAcceptedRequestTime = CurrentTime(); for (int i = 0; i < limiter.maxRPS(); ++i) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } const auto lastAcceptedRequestTime = CurrentTime(); // Not accepting more requests within current second. while (CurrentTime() < firstAcceptedRequestTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } // Still not accepting requests if less than one second has elapsed after the first request. if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_until(firstAcceptedRequestTime + std::chrono::milliseconds(900)); if (CurrentTime() < firstAcceptedRequestTime + oneSecond) ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); return TimeStamps{ firstAcceptedRequestTime, lastAcceptedRequestTime }; } static auto TestWithPeakLoadInTheBeginning_SingleIteration(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); // Herewith we ensure that NOT MORE than maxAllowedRps requests are allowed per second. // It is possible that the limiter will allow a bit LESS, though, hence this "delta" allowance // in the assertion below. constexpr auto delayDueToTimerIssueObtainedEmpirically = std::chrono::milliseconds(42); std::this_thread::sleep_until(timeStamps.firstAcceptedRequest + oneSecond + delayDueToTimerIssueObtainedEmpirically); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } static auto TestWithPeakLoadInTheBeginning_MultipleIterations(int maxAllowedRps, int iterations) { Limiter limiter(maxAllowedRps, 100); for (int i = 0; i < iterations; ++i) { const auto timeStamps = TestWithPeakLoadInTheBeginning(limiter); std::this_thread::sleep_until(timeStamps.lastAcceptedRequest + oneSecond); } } static auto TestWithEvenLoad(int maxAllowedRps) { Limiter limiter(maxAllowedRps, 100); const auto intervalBetweenRequests = oneSecond / (2 * maxAllowedRps); for (int iterations = 0; iterations < 5; ++iterations) { int requestsSent = 0; const auto startTime = CurrentTime(); while (requestsSent < maxAllowedRps && CurrentTime() < startTime + oneSecond) { ++requestsSent; const auto result = limiter.ValidateRequest(); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); std::this_thread::sleep_for(intervalBetweenRequests); } const auto lastValidRequestTime = CurrentTime(); while (CurrentTime() < startTime + oneSecond) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); std::this_thread::sleep_for(intervalBetweenRequests); } std::this_thread::sleep_until(lastValidRequestTime + oneSecond); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } } static auto TestWithAdjacentPeaks(int maxAllowedRps) { const auto startTime = CurrentTime(); Limiter limiter(maxAllowedRps, 100); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(900)); int requestsSent = 0; while (requestsSent < maxAllowedRps * 0.8) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500)); while (requestsSent < maxAllowedRps) { requestsSent++; ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } while (CurrentTime() < startTime + std::chrono::milliseconds(1900)) { ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(2000)); ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok); } namespace LimiterSpecs { static constexpr int minRPS = 1; static constexpr int maxRPS = 100'000; }; int main() { // Failing tests are commented out. try { TestAllRequestsBelowMaxAreAccepted(LimiterSpecs::maxRPS); TestAllRequestsAboveMaxAreDeclined(LimiterSpecs::maxRPS); TestWithPeakLoadInTheBeginning_SingleIteration(LimiterSpecs::maxRPS); //TestWithPeakLoadInTheBeginning_MultipleIterations(LimiterSpecs::maxRPS, 10); TestWithAdjacentPeaks(LimiterSpecs::maxRPS); TestWithEvenLoad(LimiterSpecs::maxRPS); std::cout << "All Tests passed successfully\n"; } catch (AssertionException& e) { std::cout << "One or more of tests failed: " << e.what() << '\n'; } system("pause"); return 0; } <|endoftext|>
<commit_before>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2011 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <MultiLibeio.h> #include <oxt/thread.hpp> #include <oxt/system_calls.hpp> #ifndef PREAD_AND_PWRITE_ARE_NOT_THREADSAFE #ifdef __APPLE__ #define PREAD_AND_PWRITE_ARE_NOT_THREADSAFE 1 #else #define PREAD_AND_PWRITE_ARE_NOT_THREADSAFE 0 #endif #endif namespace Passenger { using namespace oxt; static boost::mutex syncher; static condition_variable cond; static bool shouldPoll = false; static oxt::thread *thr = NULL; static bool quit = false; struct Data { SafeLibevPtr libev; MultiLibeio::Callback callback; Data(const SafeLibevPtr &_libev, const MultiLibeio::Callback &_callback) : libev(_libev), callback(_callback) { } }; struct CustomData: public Data { MultiLibeio::ExecuteCallback execute; CustomData(const SafeLibevPtr &_libev, const MultiLibeio::Callback &_callback, const MultiLibeio::ExecuteCallback &_execute) : Data(_libev, _callback), execute(_execute) { } }; static void threadMain() { unique_lock<boost::mutex> l(syncher); while (!quit) { while (!shouldPoll && !quit) { cond.wait(l); } if (!quit) { l.unlock(); eio_poll(); l.lock(); } } } static void wantPoll() { lock_guard<boost::mutex> l(syncher); shouldPoll = true; cond.notify_one(); } static int dispatch(eio_req *req) { auto_ptr<Data> data((Data *) req->data); data->libev->runLaterTS(boost::bind(data->callback, *req)); return 0; } static void executeWrapper(eio_req *req) { CustomData *data = (CustomData *) req->data; data->execute(req); } #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE boost::mutex preadWriteLock; static void lockedPread(int fd, void *buf, size_t length, off_t offset, eio_req *req) { lock_guard<boost::mutex> l(preadWriteLock); req->result = pread(fd, buf, length, offset); } static void lockedPwrite(int fd, void *buf, size_t length, off_t offset, eio_req *req) { lock_guard<boost::mutex> l(preadWriteLock); req->result = pwrite(fd, buf, length, offset); } #endif void MultiLibeio::init() { eio_init(wantPoll, NULL); thr = new oxt::thread(threadMain, "MultiLibeio dispatcher", 1024 * 64); } void MultiLibeio::shutdown() { unique_lock<boost::mutex> l(syncher); quit = true; cond.notify_one(); l.unlock(); thr->join(); delete thr; thr = NULL; quit = false; } #define MAKE_REQUEST(code) \ eio_req *result; \ Data *data = new Data(libev, callback); \ code \ if (result == NULL) { \ delete data; \ return NULL; \ } else { \ return result; \ } eio_req * MultiLibeio::open(const char *path, int flags, mode_t mode, int pri, const Callback &callback) { MAKE_REQUEST( result = eio_open(path, flags, mode, pri, dispatch, data); ); } eio_req * MultiLibeio::read(int fd, void *buf, size_t length, off_t offset, int pri, const Callback &callback) { #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE return custom(boost::bind(lockedPread, fd, buf, length, offset, _1), pri, callback); #else MAKE_REQUEST( result = eio_read(fd, buf, length, offset, pri, dispatch, data); ); #endif } eio_req * MultiLibeio::write(int fd, void *buf, size_t length, off_t offset, int pri, const Callback &callback) { #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE return custom(boost::bind(lockedPwrite, fd, buf, length, offset, _1), pri, callback); #else MAKE_REQUEST( result = eio_write(fd, buf, length, offset, pri, dispatch, data); ); #endif } eio_req * MultiLibeio::custom(const ExecuteCallback &execute, int pri, const Callback &callback) { CustomData *data = new CustomData(libev, callback, execute); eio_req *result = eio_custom(executeWrapper, pri, dispatch, data); if (result == NULL) { delete data; return NULL; } else { return result; } } } // namespace Passenger <commit_msg>Fix an infinite loop in MultiLibeio.<commit_after>/* * Phusion Passenger - http://www.modrails.com/ * Copyright (c) 2011 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <MultiLibeio.h> #include <oxt/thread.hpp> #include <oxt/system_calls.hpp> #ifndef PREAD_AND_PWRITE_ARE_NOT_THREADSAFE #ifdef __APPLE__ #define PREAD_AND_PWRITE_ARE_NOT_THREADSAFE 1 #else #define PREAD_AND_PWRITE_ARE_NOT_THREADSAFE 0 #endif #endif namespace Passenger { using namespace oxt; static boost::mutex syncher; static condition_variable cond; static bool shouldPoll = false; static oxt::thread *thr = NULL; static bool quit = false; struct Data { SafeLibevPtr libev; MultiLibeio::Callback callback; Data(const SafeLibevPtr &_libev, const MultiLibeio::Callback &_callback) : libev(_libev), callback(_callback) { } }; struct CustomData: public Data { MultiLibeio::ExecuteCallback execute; CustomData(const SafeLibevPtr &_libev, const MultiLibeio::Callback &_callback, const MultiLibeio::ExecuteCallback &_execute) : Data(_libev, _callback), execute(_execute) { } }; static void threadMain() { unique_lock<boost::mutex> l(syncher); while (!quit) { while (!shouldPoll && !quit) { cond.wait(l); } if (!quit) { shouldPoll = false; l.unlock(); eio_poll(); l.lock(); } } } static void wantPoll() { lock_guard<boost::mutex> l(syncher); shouldPoll = true; cond.notify_one(); } static int dispatch(eio_req *req) { auto_ptr<Data> data((Data *) req->data); data->libev->runLaterTS(boost::bind(data->callback, *req)); return 0; } static void executeWrapper(eio_req *req) { CustomData *data = (CustomData *) req->data; data->execute(req); } #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE boost::mutex preadWriteLock; static void lockedPread(int fd, void *buf, size_t length, off_t offset, eio_req *req) { lock_guard<boost::mutex> l(preadWriteLock); req->result = pread(fd, buf, length, offset); } static void lockedPwrite(int fd, void *buf, size_t length, off_t offset, eio_req *req) { lock_guard<boost::mutex> l(preadWriteLock); req->result = pwrite(fd, buf, length, offset); } #endif void MultiLibeio::init() { eio_init(wantPoll, NULL); thr = new oxt::thread(threadMain, "MultiLibeio dispatcher", 1024 * 64); } void MultiLibeio::shutdown() { unique_lock<boost::mutex> l(syncher); quit = true; cond.notify_one(); l.unlock(); thr->join(); delete thr; thr = NULL; quit = false; } #define MAKE_REQUEST(code) \ eio_req *result; \ Data *data = new Data(libev, callback); \ code \ if (result == NULL) { \ delete data; \ return NULL; \ } else { \ return result; \ } eio_req * MultiLibeio::open(const char *path, int flags, mode_t mode, int pri, const Callback &callback) { MAKE_REQUEST( result = eio_open(path, flags, mode, pri, dispatch, data); ); } eio_req * MultiLibeio::read(int fd, void *buf, size_t length, off_t offset, int pri, const Callback &callback) { #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE return custom(boost::bind(lockedPread, fd, buf, length, offset, _1), pri, callback); #else MAKE_REQUEST( result = eio_read(fd, buf, length, offset, pri, dispatch, data); ); #endif } eio_req * MultiLibeio::write(int fd, void *buf, size_t length, off_t offset, int pri, const Callback &callback) { #if PREAD_AND_PWRITE_ARE_NOT_THREADSAFE return custom(boost::bind(lockedPwrite, fd, buf, length, offset, _1), pri, callback); #else MAKE_REQUEST( result = eio_write(fd, buf, length, offset, pri, dispatch, data); ); #endif } eio_req * MultiLibeio::custom(const ExecuteCallback &execute, int pri, const Callback &callback) { CustomData *data = new CustomData(libev, callback, execute); eio_req *result = eio_custom(executeWrapper, pri, dispatch, data); if (result == NULL) { delete data; return NULL; } else { return result; } } } // namespace Passenger <|endoftext|>
<commit_before>/* * op≈ * External object for Max/MSP to perform basic mathematical operations on objects in a lydbær dsp chain. * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "maxbaer.h" // Data Structure for this object typedef struct LydOp { t_object obj; LydbaerObjectPtr lydbaer; void* lydbaerOutlet; SymbolPtr attrOperator; TTFloat32 attrOperand; }; typedef LydOp* LydOpPtr; // Prototypes for methods LydOpPtr lydOpNew(SymbolPtr msg, AtomCount argc, AtomPtr argv); void lydOpFree(LydOpPtr x); void lydOpAssist(LydOpPtr x, void* b, long msg, long arg, char* dst); TTErr lydOpReset(LydOpPtr x, long vectorSize); TTErr lydOpSetup(LydOpPtr x); TTErr lydOpObject(LydOpPtr x, LydbaerObjectPtr audioSourceObject); MaxErr lydOpSetOperator(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv); MaxErr lydOpSetOperand(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv); // Globals static ClassPtr sLydOpClass; /************************************************************************************/ // Main() Function int main(void) { t_class *c; TTBlueInit(); common_symbols_init(); c = class_new("op≈", (method)lydOpNew, (method)lydOpFree, sizeof(LydOp), (method)0L, A_GIMME, 0); class_addmethod(c, (method)lydOpReset, "lydbaerReset", A_CANT, 0); class_addmethod(c, (method)lydOpSetup, "lydbaerSetup", A_CANT, 0); class_addmethod(c, (method)lydOpObject, "lydbaerObject", A_OBJ, 0); class_addmethod(c, (method)lydOpAssist, "assist", A_CANT, 0); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); CLASS_ATTR_SYM(c, "operator", 0, LydOp, attrOperator); CLASS_ATTR_ACCESSORS(c, "operator", NULL, lydOpSetOperator); CLASS_ATTR_FLOAT(c, "operand", 0, LydOp, attrOperand); CLASS_ATTR_ACCESSORS(c, "operand", NULL, lydOpSetOperand); class_register(_sym_box, c); sLydOpClass = c; return 0; } /************************************************************************************/ // Object Creation Method LydOpPtr lydOpNew(SymbolPtr msg, AtomCount argc, AtomPtr argv) { LydOpPtr x; x = LydOpPtr(object_alloc(sLydOpClass)); if(x){ object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout x->lydbaerOutlet = outlet_new((t_pxobject *)x, 0); // TODO: we need to update objects to work with the correct number of channels when the network is configured // Either that, or when we pull we just up the number of channels if when we need to ??? x->lydbaer = new LydbaerObject(TT("operator"), 8); if(!x->lydbaer->audioObject){ object_error(ObjectPtr(x), "cannot load TTBlue object"); return NULL; } attr_args_process(x,argc,argv); } return x; } // Memory Deallocation void lydOpFree(LydOpPtr x) { delete x->lydbaer; } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void lydOpAssist(LydOpPtr x, void* b, long msg, long arg, char* dst) { if(msg==1) // Inlets strcpy(dst, "multichannel input and control messages"); else if(msg==2){ // Outlets if(arg == 0) strcpy(dst, "multichannel output"); else strcpy(dst, "dumpout"); } } // METHODS SPECIFIC TO LYDBAER EXTERNALS TTErr lydOpReset(LydOpPtr x, long vectorSize) { return x->lydbaer->resetSources(vectorSize); } TTErr lydOpSetup(LydOpPtr x) { Atom a; atom_setobj(&a, ObjectPtr(x->lydbaer)); outlet_anything(x->lydbaerOutlet, gensym("lydbaerObject"), 1, &a); return kTTErrNone; } TTErr lydOpObject(LydOpPtr x, LydbaerObjectPtr audioSourceObject) { return x->lydbaer->addSource(audioSourceObject); } // ATTRIBUTE SETTERS MaxErr lydOpSetOperator(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv) { if(argc){ x->attrOperator = atom_getsym(argv); x->lydbaer->audioObject->setAttributeValue(TT("operator"), TT(x->attrOperator->s_name)); } return MAX_ERR_NONE; } MaxErr lydOpSetOperand(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv) { if(argc){ x->attrOperand = atom_getfloat(argv); x->lydbaer->audioObject->setAttributeValue(TT("operand"), x->attrOperand); } return MAX_ERR_NONE; } <commit_msg>removed unneeded cast<commit_after>/* * op≈ * External object for Max/MSP to perform basic mathematical operations on objects in a lydbær dsp chain. * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "maxbaer.h" // Data Structure for this object typedef struct LydOp { t_object obj; LydbaerObjectPtr lydbaer; void* lydbaerOutlet; SymbolPtr attrOperator; TTFloat32 attrOperand; }; typedef LydOp* LydOpPtr; // Prototypes for methods LydOpPtr lydOpNew(SymbolPtr msg, AtomCount argc, AtomPtr argv); void lydOpFree(LydOpPtr x); void lydOpAssist(LydOpPtr x, void* b, long msg, long arg, char* dst); TTErr lydOpReset(LydOpPtr x, long vectorSize); TTErr lydOpSetup(LydOpPtr x); TTErr lydOpObject(LydOpPtr x, LydbaerObjectPtr audioSourceObject); MaxErr lydOpSetOperator(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv); MaxErr lydOpSetOperand(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv); // Globals static ClassPtr sLydOpClass; /************************************************************************************/ // Main() Function int main(void) { t_class *c; TTBlueInit(); common_symbols_init(); c = class_new("op≈", (method)lydOpNew, (method)lydOpFree, sizeof(LydOp), (method)0L, A_GIMME, 0); class_addmethod(c, (method)lydOpReset, "lydbaerReset", A_CANT, 0); class_addmethod(c, (method)lydOpSetup, "lydbaerSetup", A_CANT, 0); class_addmethod(c, (method)lydOpObject, "lydbaerObject", A_OBJ, 0); class_addmethod(c, (method)lydOpAssist, "assist", A_CANT, 0); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); CLASS_ATTR_SYM(c, "operator", 0, LydOp, attrOperator); CLASS_ATTR_ACCESSORS(c, "operator", NULL, lydOpSetOperator); CLASS_ATTR_FLOAT(c, "operand", 0, LydOp, attrOperand); CLASS_ATTR_ACCESSORS(c, "operand", NULL, lydOpSetOperand); class_register(_sym_box, c); sLydOpClass = c; return 0; } /************************************************************************************/ // Object Creation Method LydOpPtr lydOpNew(SymbolPtr msg, AtomCount argc, AtomPtr argv) { LydOpPtr x; x = LydOpPtr(object_alloc(sLydOpClass)); if(x){ object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout x->lydbaerOutlet = outlet_new(x, 0); // TODO: we need to update objects to work with the correct number of channels when the network is configured // Either that, or when we pull we just up the number of channels if when we need to ??? x->lydbaer = new LydbaerObject(TT("operator"), 8); if(!x->lydbaer->audioObject){ object_error(ObjectPtr(x), "cannot load TTBlue object"); return NULL; } attr_args_process(x,argc,argv); } return x; } // Memory Deallocation void lydOpFree(LydOpPtr x) { delete x->lydbaer; } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void lydOpAssist(LydOpPtr x, void* b, long msg, long arg, char* dst) { if(msg==1) // Inlets strcpy(dst, "multichannel input and control messages"); else if(msg==2){ // Outlets if(arg == 0) strcpy(dst, "multichannel output"); else strcpy(dst, "dumpout"); } } // METHODS SPECIFIC TO LYDBAER EXTERNALS TTErr lydOpReset(LydOpPtr x, long vectorSize) { return x->lydbaer->resetSources(vectorSize); } TTErr lydOpSetup(LydOpPtr x) { Atom a; atom_setobj(&a, ObjectPtr(x->lydbaer)); outlet_anything(x->lydbaerOutlet, gensym("lydbaerObject"), 1, &a); return kTTErrNone; } TTErr lydOpObject(LydOpPtr x, LydbaerObjectPtr audioSourceObject) { return x->lydbaer->addSource(audioSourceObject); } // ATTRIBUTE SETTERS MaxErr lydOpSetOperator(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv) { if(argc){ x->attrOperator = atom_getsym(argv); x->lydbaer->audioObject->setAttributeValue(TT("operator"), TT(x->attrOperator->s_name)); } return MAX_ERR_NONE; } MaxErr lydOpSetOperand(LydOpPtr x, void *attr, AtomCount argc, AtomPtr argv) { if(argc){ x->attrOperand = atom_getfloat(argv); x->lydbaer->audioObject->setAttributeValue(TT("operand"), x->attrOperand); } return MAX_ERR_NONE; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/tools/quic_client_base.h" #include "net/third_party/quiche/src/quic/core/crypto/quic_random.h" #include "net/third_party/quiche/src/quic/core/http/spdy_utils.h" #include "net/third_party/quiche/src/quic/core/quic_server_id.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" namespace quic { QuicClientBase::NetworkHelper::~NetworkHelper() = default; QuicClientBase::QuicClientBase( const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, std::unique_ptr<NetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : server_id_(server_id), initialized_(false), local_port_(0), config_(config), crypto_config_(std::move(proof_verifier), std::move(session_cache)), helper_(helper), alarm_factory_(alarm_factory), supported_versions_(supported_versions), initial_max_packet_length_(0), num_sent_client_hellos_(0), connection_error_(QUIC_NO_ERROR), connected_or_attempting_connect_(false), network_helper_(std::move(network_helper)), connection_debug_visitor_(nullptr) {} QuicClientBase::~QuicClientBase() = default; bool QuicClientBase::Initialize() { num_sent_client_hellos_ = 0; connection_error_ = QUIC_NO_ERROR; connected_or_attempting_connect_ = false; // If an initial flow control window has not explicitly been set, then use the // same values that Chrome uses. const uint32_t kSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB const uint32_t kStreamMaxRecvWindowSize = 6 * 1024 * 1024; // 6 MB if (config()->GetInitialStreamFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config()->SetInitialStreamFlowControlWindowToSend(kStreamMaxRecvWindowSize); } if (config()->GetInitialSessionFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config()->SetInitialSessionFlowControlWindowToSend( kSessionMaxRecvWindowSize); } if (!network_helper_->CreateUDPSocketAndBind(server_address_, bind_to_address_, local_port_)) { return false; } initialized_ = true; return true; } bool QuicClientBase::Connect() { // Attempt multiple connects until the maximum number of client hellos have // been sent. while (!connected() && GetNumSentClientHellos() <= QuicCryptoClientStream::kMaxClientHellos) { StartConnect(); while (EncryptionBeingEstablished()) { WaitForEvents(); } ParsedQuicVersion version = UnsupportedQuicVersion(); if (session() != nullptr && !CanReconnectWithDifferentVersion(&version)) { // We've successfully created a session but we're not connected, and we // cannot reconnect with a different version. Give up trying. break; } } return session()->connection()->connected(); } void QuicClientBase::StartConnect() { DCHECK(initialized_); DCHECK(!connected()); QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter(); ParsedQuicVersion mutual_version = UnsupportedQuicVersion(); const bool can_reconnect_with_different_version = CanReconnectWithDifferentVersion(&mutual_version); if (connected_or_attempting_connect()) { // Clear queued up data if client can not try to connect with a different // version. if (!can_reconnect_with_different_version) { ClearDataToResend(); } // Before we destroy the last session and create a new one, gather its stats // and update the stats for the overall connection. UpdateStats(); } session_ = CreateQuicClientSession( supported_versions(), new QuicConnection(GetNextConnectionId(), server_address(), helper(), alarm_factory(), writer, /* owns_writer= */ false, Perspective::IS_CLIENT, can_reconnect_with_different_version ? ParsedQuicVersionVector{mutual_version} : supported_versions())); if (connection_debug_visitor_ != nullptr) { session()->connection()->set_debug_visitor(connection_debug_visitor_); } session()->connection()->set_client_connection_id(GetClientConnectionId()); if (initial_max_packet_length_ != 0) { session()->connection()->SetMaxPacketLength(initial_max_packet_length_); } // Reset |writer()| after |session()| so that the old writer outlives the old // session. set_writer(writer); InitializeSession(); if (can_reconnect_with_different_version) { // This is a reconnect using server supported |mutual_version|. session()->connection()->SetVersionNegotiated(); } set_connected_or_attempting_connect(true); } void QuicClientBase::InitializeSession() { session()->Initialize(); } void QuicClientBase::Disconnect() { DCHECK(initialized_); initialized_ = false; if (connected()) { session()->connection()->CloseConnection( QUIC_PEER_GOING_AWAY, "Client disconnecting", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } ClearDataToResend(); network_helper_->CleanUpAllUDPSockets(); } ProofVerifier* QuicClientBase::proof_verifier() const { return crypto_config_.proof_verifier(); } bool QuicClientBase::EncryptionBeingEstablished() { return !session_->IsEncryptionEstablished() && session_->connection()->connected(); } bool QuicClientBase::WaitForEvents() { DCHECK(connected()); network_helper_->RunEventLoop(); DCHECK(session() != nullptr); ParsedQuicVersion version = UnsupportedQuicVersion(); if (!connected() && CanReconnectWithDifferentVersion(&version)) { QUIC_DLOG(INFO) << "Can reconnect with version: " << version << ", attempting to reconnect."; Connect(); } return HasActiveRequests(); } bool QuicClientBase::MigrateSocket(const QuicIpAddress& new_host) { return MigrateSocketWithSpecifiedPort(new_host, local_port_); } bool QuicClientBase::MigrateSocketWithSpecifiedPort( const QuicIpAddress& new_host, int port) { if (!connected()) { return false; } network_helper_->CleanUpAllUDPSockets(); set_bind_to_address(new_host); if (!network_helper_->CreateUDPSocketAndBind(server_address_, bind_to_address_, port)) { return false; } session()->connection()->SetSelfAddress( network_helper_->GetLatestClientAddress()); QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter(); set_writer(writer); session()->connection()->SetQuicPacketWriter(writer, false); return true; } bool QuicClientBase::ChangeEphemeralPort() { auto current_host = network_helper_->GetLatestClientAddress().host(); return MigrateSocketWithSpecifiedPort(current_host, 0 /*any ephemeral port*/); } QuicSession* QuicClientBase::session() { return session_.get(); } QuicClientBase::NetworkHelper* QuicClientBase::network_helper() { return network_helper_.get(); } const QuicClientBase::NetworkHelper* QuicClientBase::network_helper() const { return network_helper_.get(); } void QuicClientBase::WaitForStreamToClose(QuicStreamId id) { DCHECK(connected()); while (connected() && !session_->IsClosedStream(id)) { WaitForEvents(); } } bool QuicClientBase::WaitForCryptoHandshakeConfirmed() { DCHECK(connected()); while (connected() && !session_->OneRttKeysAvailable()) { WaitForEvents(); } // If the handshake fails due to a timeout, the connection will be closed. QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed."; return connected(); } bool QuicClientBase::connected() const { return session_.get() && session_->connection() && session_->connection()->connected(); } bool QuicClientBase::goaway_received() const { return session_ != nullptr && session_->goaway_received(); } int QuicClientBase::GetNumSentClientHellos() { // If we are not actively attempting to connect, the session object // corresponds to the previous connection and should not be used. const int current_session_hellos = !connected_or_attempting_connect_ ? 0 : GetNumSentClientHellosFromSession(); return num_sent_client_hellos_ + current_session_hellos; } void QuicClientBase::UpdateStats() { num_sent_client_hellos_ += GetNumSentClientHellosFromSession(); } int QuicClientBase::GetNumReceivedServerConfigUpdates() { // If we are not actively attempting to connect, the session object // corresponds to the previous connection and should not be used. return !connected_or_attempting_connect_ ? 0 : GetNumReceivedServerConfigUpdatesFromSession(); } QuicErrorCode QuicClientBase::connection_error() const { // Return the high-level error if there was one. Otherwise, return the // connection error from the last session. if (connection_error_ != QUIC_NO_ERROR) { return connection_error_; } if (session_ == nullptr) { return QUIC_NO_ERROR; } return session_->error(); } QuicConnectionId QuicClientBase::GetNextConnectionId() { QuicConnectionId server_designated_id = GetNextServerDesignatedConnectionId(); return !server_designated_id.IsEmpty() ? server_designated_id : GenerateNewConnectionId(); } QuicConnectionId QuicClientBase::GetNextServerDesignatedConnectionId() { QuicCryptoClientConfig::CachedState* cached = crypto_config_.LookupOrCreate(server_id_); // If the cached state indicates that we should use a server-designated // connection ID, then return that connection ID. CHECK(cached != nullptr) << "QuicClientCryptoConfig::LookupOrCreate returned " << "unexpected nullptr."; return cached->has_server_designated_connection_id() ? cached->GetNextServerDesignatedConnectionId() : EmptyQuicConnectionId(); } QuicConnectionId QuicClientBase::GenerateNewConnectionId() { return QuicUtils::CreateRandomConnectionId(); } QuicConnectionId QuicClientBase::GetClientConnectionId() { return EmptyQuicConnectionId(); } bool QuicClientBase::CanReconnectWithDifferentVersion( ParsedQuicVersion* version) const { if (session_ == nullptr || session_->connection() == nullptr || session_->error() != QUIC_INVALID_VERSION || session_->connection()->server_supported_versions().empty()) { return false; } for (const auto& client_version : supported_versions_) { if (QuicContainsValue(session_->connection()->server_supported_versions(), client_version)) { *version = client_version; return true; } } return false; } } // namespace quic <commit_msg>Change number of connection attempts in QuicClientBase::Connect<commit_after>// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/tools/quic_client_base.h" #include "net/third_party/quiche/src/quic/core/crypto/quic_random.h" #include "net/third_party/quiche/src/quic/core/http/spdy_utils.h" #include "net/third_party/quiche/src/quic/core/quic_server_id.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" namespace quic { QuicClientBase::NetworkHelper::~NetworkHelper() = default; QuicClientBase::QuicClientBase( const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, std::unique_ptr<NetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : server_id_(server_id), initialized_(false), local_port_(0), config_(config), crypto_config_(std::move(proof_verifier), std::move(session_cache)), helper_(helper), alarm_factory_(alarm_factory), supported_versions_(supported_versions), initial_max_packet_length_(0), num_sent_client_hellos_(0), connection_error_(QUIC_NO_ERROR), connected_or_attempting_connect_(false), network_helper_(std::move(network_helper)), connection_debug_visitor_(nullptr) {} QuicClientBase::~QuicClientBase() = default; bool QuicClientBase::Initialize() { num_sent_client_hellos_ = 0; connection_error_ = QUIC_NO_ERROR; connected_or_attempting_connect_ = false; // If an initial flow control window has not explicitly been set, then use the // same values that Chrome uses. const uint32_t kSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB const uint32_t kStreamMaxRecvWindowSize = 6 * 1024 * 1024; // 6 MB if (config()->GetInitialStreamFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config()->SetInitialStreamFlowControlWindowToSend(kStreamMaxRecvWindowSize); } if (config()->GetInitialSessionFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config()->SetInitialSessionFlowControlWindowToSend( kSessionMaxRecvWindowSize); } if (!network_helper_->CreateUDPSocketAndBind(server_address_, bind_to_address_, local_port_)) { return false; } initialized_ = true; return true; } bool QuicClientBase::Connect() { // Attempt multiple connects until the maximum number of client hellos have // been sent. int num_attempts = 0; while (!connected() && num_attempts <= QuicCryptoClientStream::kMaxClientHellos) { StartConnect(); while (EncryptionBeingEstablished()) { WaitForEvents(); } ParsedQuicVersion version = UnsupportedQuicVersion(); if (session() != nullptr && !CanReconnectWithDifferentVersion(&version)) { // We've successfully created a session but we're not connected, and we // cannot reconnect with a different version. Give up trying. break; } num_attempts++; } return session()->connection()->connected(); } void QuicClientBase::StartConnect() { DCHECK(initialized_); DCHECK(!connected()); QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter(); ParsedQuicVersion mutual_version = UnsupportedQuicVersion(); const bool can_reconnect_with_different_version = CanReconnectWithDifferentVersion(&mutual_version); if (connected_or_attempting_connect()) { // Clear queued up data if client can not try to connect with a different // version. if (!can_reconnect_with_different_version) { ClearDataToResend(); } // Before we destroy the last session and create a new one, gather its stats // and update the stats for the overall connection. UpdateStats(); } session_ = CreateQuicClientSession( supported_versions(), new QuicConnection(GetNextConnectionId(), server_address(), helper(), alarm_factory(), writer, /* owns_writer= */ false, Perspective::IS_CLIENT, can_reconnect_with_different_version ? ParsedQuicVersionVector{mutual_version} : supported_versions())); if (connection_debug_visitor_ != nullptr) { session()->connection()->set_debug_visitor(connection_debug_visitor_); } session()->connection()->set_client_connection_id(GetClientConnectionId()); if (initial_max_packet_length_ != 0) { session()->connection()->SetMaxPacketLength(initial_max_packet_length_); } // Reset |writer()| after |session()| so that the old writer outlives the old // session. set_writer(writer); InitializeSession(); if (can_reconnect_with_different_version) { // This is a reconnect using server supported |mutual_version|. session()->connection()->SetVersionNegotiated(); } set_connected_or_attempting_connect(true); } void QuicClientBase::InitializeSession() { session()->Initialize(); } void QuicClientBase::Disconnect() { DCHECK(initialized_); initialized_ = false; if (connected()) { session()->connection()->CloseConnection( QUIC_PEER_GOING_AWAY, "Client disconnecting", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } ClearDataToResend(); network_helper_->CleanUpAllUDPSockets(); } ProofVerifier* QuicClientBase::proof_verifier() const { return crypto_config_.proof_verifier(); } bool QuicClientBase::EncryptionBeingEstablished() { return !session_->IsEncryptionEstablished() && session_->connection()->connected(); } bool QuicClientBase::WaitForEvents() { DCHECK(connected()); network_helper_->RunEventLoop(); DCHECK(session() != nullptr); ParsedQuicVersion version = UnsupportedQuicVersion(); if (!connected() && CanReconnectWithDifferentVersion(&version)) { QUIC_DLOG(INFO) << "Can reconnect with version: " << version << ", attempting to reconnect."; Connect(); } return HasActiveRequests(); } bool QuicClientBase::MigrateSocket(const QuicIpAddress& new_host) { return MigrateSocketWithSpecifiedPort(new_host, local_port_); } bool QuicClientBase::MigrateSocketWithSpecifiedPort( const QuicIpAddress& new_host, int port) { if (!connected()) { return false; } network_helper_->CleanUpAllUDPSockets(); set_bind_to_address(new_host); if (!network_helper_->CreateUDPSocketAndBind(server_address_, bind_to_address_, port)) { return false; } session()->connection()->SetSelfAddress( network_helper_->GetLatestClientAddress()); QuicPacketWriter* writer = network_helper_->CreateQuicPacketWriter(); set_writer(writer); session()->connection()->SetQuicPacketWriter(writer, false); return true; } bool QuicClientBase::ChangeEphemeralPort() { auto current_host = network_helper_->GetLatestClientAddress().host(); return MigrateSocketWithSpecifiedPort(current_host, 0 /*any ephemeral port*/); } QuicSession* QuicClientBase::session() { return session_.get(); } QuicClientBase::NetworkHelper* QuicClientBase::network_helper() { return network_helper_.get(); } const QuicClientBase::NetworkHelper* QuicClientBase::network_helper() const { return network_helper_.get(); } void QuicClientBase::WaitForStreamToClose(QuicStreamId id) { DCHECK(connected()); while (connected() && !session_->IsClosedStream(id)) { WaitForEvents(); } } bool QuicClientBase::WaitForCryptoHandshakeConfirmed() { DCHECK(connected()); while (connected() && !session_->OneRttKeysAvailable()) { WaitForEvents(); } // If the handshake fails due to a timeout, the connection will be closed. QUIC_LOG_IF(ERROR, !connected()) << "Handshake with server failed."; return connected(); } bool QuicClientBase::connected() const { return session_.get() && session_->connection() && session_->connection()->connected(); } bool QuicClientBase::goaway_received() const { return session_ != nullptr && session_->goaway_received(); } int QuicClientBase::GetNumSentClientHellos() { // If we are not actively attempting to connect, the session object // corresponds to the previous connection and should not be used. const int current_session_hellos = !connected_or_attempting_connect_ ? 0 : GetNumSentClientHellosFromSession(); return num_sent_client_hellos_ + current_session_hellos; } void QuicClientBase::UpdateStats() { num_sent_client_hellos_ += GetNumSentClientHellosFromSession(); } int QuicClientBase::GetNumReceivedServerConfigUpdates() { // If we are not actively attempting to connect, the session object // corresponds to the previous connection and should not be used. return !connected_or_attempting_connect_ ? 0 : GetNumReceivedServerConfigUpdatesFromSession(); } QuicErrorCode QuicClientBase::connection_error() const { // Return the high-level error if there was one. Otherwise, return the // connection error from the last session. if (connection_error_ != QUIC_NO_ERROR) { return connection_error_; } if (session_ == nullptr) { return QUIC_NO_ERROR; } return session_->error(); } QuicConnectionId QuicClientBase::GetNextConnectionId() { QuicConnectionId server_designated_id = GetNextServerDesignatedConnectionId(); return !server_designated_id.IsEmpty() ? server_designated_id : GenerateNewConnectionId(); } QuicConnectionId QuicClientBase::GetNextServerDesignatedConnectionId() { QuicCryptoClientConfig::CachedState* cached = crypto_config_.LookupOrCreate(server_id_); // If the cached state indicates that we should use a server-designated // connection ID, then return that connection ID. CHECK(cached != nullptr) << "QuicClientCryptoConfig::LookupOrCreate returned " << "unexpected nullptr."; return cached->has_server_designated_connection_id() ? cached->GetNextServerDesignatedConnectionId() : EmptyQuicConnectionId(); } QuicConnectionId QuicClientBase::GenerateNewConnectionId() { return QuicUtils::CreateRandomConnectionId(); } QuicConnectionId QuicClientBase::GetClientConnectionId() { return EmptyQuicConnectionId(); } bool QuicClientBase::CanReconnectWithDifferentVersion( ParsedQuicVersion* version) const { if (session_ == nullptr || session_->connection() == nullptr || session_->error() != QUIC_INVALID_VERSION || session_->connection()->server_supported_versions().empty()) { return false; } for (const auto& client_version : supported_versions_) { if (QuicContainsValue(session_->connection()->server_supported_versions(), client_version)) { *version = client_version; return true; } } return false; } } // namespace quic <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> #include <unistd.h> int main(int argc, char** argv){ if(argc!=2){ std::cout << "Nope.\n"; return -1; } cv::VideoCapture _capture(CV_CAP_OPENNI); std::cout << "Started streaming data to main system..\n"; int c=0; while(1){ cv::Mat depthMap, rgb; usleep(500000); _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); imwrite(std::string(argv[1])+"/rgb.png", rgb); imwrite(std::string(argv[1])+"/depth.png", depthMap); std::cout << ++c << "\n"; } return 0; } <commit_msg>Make a more robust streamer<commit_after>#include <opencv2/opencv.hpp> #include <opencv/highgui.h> #include <unistd.h> int main(int argc, char** argv){ if(argc!=2){ std::cout << "Nope.\n"; return -1; } cv::VideoCapture _capture(CV_CAP_OPENNI); std::cout << "Started streaming data to main system..\n"; int c=0; cv::namedWindow("DEPTH"); while(1){ cv::Mat depthMap, rgb; usleep(500000); _capture.grab(); _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP); cv::imshow("DEPTH", depthMap); cv::waitKey(1); _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE); cv::imshow("RGB", rgb); cv::waitKey(1); std::string name=std::string(argv[1])+"/"; imwrite(name+"/rgb1.png", rgb); imwrite(name+"/depth1.png", depthMap); system(("mv "+name+"rgb1.png "+name+"rgb.png ; mv "+name+"depth1.png "+name+"depth.png").c_str()); std::cout << ++c << "\n"; } return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Hotkeys.h" #include <core/support/Preferences.h> #include <app/util/Playback.h> #include <unordered_map> #include <unordered_set> using namespace musik::box; using namespace musik::core; using Id = Hotkeys::Id; /* sigh: http://stackoverflow.com/a/24847480 */ struct EnumHasher { template <typename T> std::size_t operator()(T t) const { return static_cast<std::size_t>(t); } }; /* map from internal ID to user-friendly JSON key name */ static std::unordered_map<std::string, Id> NAME_TO_ID = { { "navigate_library", Id::NavigateLibrary }, { "navigate_library_browse", Id::NavigateLibraryBrowse }, { "navigate_library_browse_artists", Id::NavigateLibraryBrowseArtists }, { "navigate_library_browse_albums", Id::NavigateLibraryBrowseAlbums }, { "navigate_library_browse_genres", Id::NavigateLibraryBrowseGenres }, { "navigate_library_album_artists", Id::NavigateLibraryBrowseAlbumArtists }, { "navigate_library_filter", Id::NavigateLibraryFilter }, { "navigate_library_tracks", Id::NavigateLibraryTracks }, { "navigate_library_play_queue", Id::NavigateLibraryPlayQueue }, { "navigate_settings", Id::NavigateSettings }, { "navigate_console", Id::NavigateConsole }, { "navigate_jump_to_playing", Id::NavigateJumpToPlaying }, { "play_queue_move_up", Id::PlayQueueMoveUp }, { "play_queue_move_up", Id::PlayQueueMoveDown }, { "play_queue_delete", Id::PlayQueueDelete }, { "playback_toggle_mute", Id::ToggleMute }, { "playback_toggle_pause", Id::TogglePause }, { "playback_next", Id::Next }, { "playback_previous", Id::Previous }, { "playback_volume_up", Id::VolumeUp }, { "playback_volume_down", Id::VolumeDown }, { "playback_seek_forward", Id::SeekForward }, { "playback_seek_back", Id::SeekBack }, { "playback_toggle_repeat", Id::ToggleRepeat }, { "playback_toggle_shuffle", Id::ToggleShuffle }, { "playback_stop", Id::Stop }, { "view_refresh", Id::ViewRefresh }, { "toggle_visualizer", Id::ToggleVisualizer }, { "metadata_rescan", Id::RescanMetadata }, { "context_menu", Id::ContextMenu } }; /* default hotkeys */ static std::unordered_map<Id, std::string, EnumHasher> ID_TO_DEFAULT = { { Id::NavigateLibrary, "a" }, { Id::NavigateLibraryBrowse, "b" }, { Id::NavigateLibraryBrowseArtists, "1" }, { Id::NavigateLibraryBrowseAlbums, "2" }, { Id::NavigateLibraryBrowseGenres, "3" }, { Id::NavigateLibraryBrowseAlbumArtists, "4" }, { Id::NavigateLibraryFilter, "f" }, { Id::NavigateLibraryTracks, "t" }, { Id::NavigateLibraryPlayQueue, "n" }, { Id::NavigateSettings, "s" }, { Id::NavigateConsole, "`" }, { Id::NavigateJumpToPlaying, "x" }, #ifdef __APPLE__ /* M-up, M-down don't seem to work on iTerm2, and the delete key doesn't exist on most macbooks. ugly special mappings here. */ { Id::PlayQueueMoveUp, "CTL_UP" }, { Id::PlayQueueMoveDown, "CTL_DOWN" }, { Id::PlayQueueDelete, "KEY_BACKSPACE" }, #else { Id::PlayQueueMoveUp, "M-up" }, { Id::PlayQueueMoveDown, "M-down" }, { Id::PlayQueueDelete, "KEY_DC" }, #endif { Id::ToggleMute, "m" }, { Id::TogglePause, "^P" }, { Id::Next, "l" }, { Id::Previous, "j" }, { Id::VolumeUp, "i" }, { Id::VolumeDown, "k" }, { Id::SeekForward, "o" }, { Id::SeekBack, "u" }, { Id::ToggleRepeat, "." }, { Id::ToggleShuffle, "," }, { Id::Stop, "^X" }, { Id::ViewRefresh, "KEY_F(5)" }, { Id::ToggleVisualizer, "v" }, { Id::RescanMetadata, "^R"}, { Id::ContextMenu, "M-enter" } }; /* custom keys */ static std::unordered_set<std::string> customKeys; static std::unordered_map<Id, std::string, EnumHasher> customIdToKey; /* preferences file */ static std::shared_ptr<Preferences> prefs; static void savePreferences() { for (const std::pair<std::string, Id>& pair : NAME_TO_ID) { prefs->SetString( pair.first.c_str(), Hotkeys::Get(pair.second).c_str()); } prefs->Save(); } static void loadPreferences() { prefs = Preferences::ForComponent("hotkeys", Preferences::ModeReadWrite); try { /* load all of the custom key mappings into customKeys and customIdToKey structures for quick lookup. */ if (prefs) { customKeys.clear(); std::vector<std::string> names; prefs->GetKeys(names); for (auto n : names) { auto it = NAME_TO_ID.find(n); if (it != NAME_TO_ID.end()) { customKeys.insert(prefs->GetString(n)); customIdToKey[it->second] = prefs->GetString(n); } } } /* write back to disk; this way any new hotkey defaults are picked up and saved so the user can edit them easily. */ savePreferences(); } catch (...) { std::cerr << "failed to load hotkeys.json! default hotkeys selected."; customKeys.clear(); customIdToKey.clear(); } } Hotkeys::Hotkeys() { } bool Hotkeys::Is(Id id, const std::string& kn) { if (!prefs) { loadPreferences(); } /* see if the user has specified a custom value for this hotkey. if they have, compare it to the custom value. */ auto custom = customIdToKey.find(id); if (custom != customIdToKey.end()) { return (custom->second == kn); } /* otherwise, let's compare against the default key, assuming the input key doesn't match ANY that the user has customized */ if (customKeys.find(kn) == customKeys.end()) { auto it = ID_TO_DEFAULT.find(id); if (it != ID_TO_DEFAULT.end() && it->second == kn) { return true; } } return false; } std::string Hotkeys::Get(Id id) { if (!prefs) { loadPreferences(); } auto custom = customIdToKey.find(id); if (custom != customIdToKey.end()) { return custom->second; } auto it = ID_TO_DEFAULT.find(id); if (it != ID_TO_DEFAULT.end()) { return it->second; } return ""; } <commit_msg>Fixed play_queue_move_down constant.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2016 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Hotkeys.h" #include <core/support/Preferences.h> #include <app/util/Playback.h> #include <unordered_map> #include <unordered_set> using namespace musik::box; using namespace musik::core; using Id = Hotkeys::Id; /* sigh: http://stackoverflow.com/a/24847480 */ struct EnumHasher { template <typename T> std::size_t operator()(T t) const { return static_cast<std::size_t>(t); } }; /* map from internal ID to user-friendly JSON key name */ static std::unordered_map<std::string, Id> NAME_TO_ID = { { "navigate_library", Id::NavigateLibrary }, { "navigate_library_browse", Id::NavigateLibraryBrowse }, { "navigate_library_browse_artists", Id::NavigateLibraryBrowseArtists }, { "navigate_library_browse_albums", Id::NavigateLibraryBrowseAlbums }, { "navigate_library_browse_genres", Id::NavigateLibraryBrowseGenres }, { "navigate_library_album_artists", Id::NavigateLibraryBrowseAlbumArtists }, { "navigate_library_filter", Id::NavigateLibraryFilter }, { "navigate_library_tracks", Id::NavigateLibraryTracks }, { "navigate_library_play_queue", Id::NavigateLibraryPlayQueue }, { "navigate_settings", Id::NavigateSettings }, { "navigate_console", Id::NavigateConsole }, { "navigate_jump_to_playing", Id::NavigateJumpToPlaying }, { "play_queue_move_up", Id::PlayQueueMoveUp }, { "play_queue_move_down", Id::PlayQueueMoveDown }, { "play_queue_delete", Id::PlayQueueDelete }, { "playback_toggle_mute", Id::ToggleMute }, { "playback_toggle_pause", Id::TogglePause }, { "playback_next", Id::Next }, { "playback_previous", Id::Previous }, { "playback_volume_up", Id::VolumeUp }, { "playback_volume_down", Id::VolumeDown }, { "playback_seek_forward", Id::SeekForward }, { "playback_seek_back", Id::SeekBack }, { "playback_toggle_repeat", Id::ToggleRepeat }, { "playback_toggle_shuffle", Id::ToggleShuffle }, { "playback_stop", Id::Stop }, { "view_refresh", Id::ViewRefresh }, { "toggle_visualizer", Id::ToggleVisualizer }, { "metadata_rescan", Id::RescanMetadata }, { "context_menu", Id::ContextMenu } }; /* default hotkeys */ static std::unordered_map<Id, std::string, EnumHasher> ID_TO_DEFAULT = { { Id::NavigateLibrary, "a" }, { Id::NavigateLibraryBrowse, "b" }, { Id::NavigateLibraryBrowseArtists, "1" }, { Id::NavigateLibraryBrowseAlbums, "2" }, { Id::NavigateLibraryBrowseGenres, "3" }, { Id::NavigateLibraryBrowseAlbumArtists, "4" }, { Id::NavigateLibraryFilter, "f" }, { Id::NavigateLibraryTracks, "t" }, { Id::NavigateLibraryPlayQueue, "n" }, { Id::NavigateSettings, "s" }, { Id::NavigateConsole, "`" }, { Id::NavigateJumpToPlaying, "x" }, #ifdef __APPLE__ /* M-up, M-down don't seem to work on iTerm2, and the delete key doesn't exist on most macbooks. ugly special mappings here. */ { Id::PlayQueueMoveUp, "CTL_UP" }, { Id::PlayQueueMoveDown, "CTL_DOWN" }, { Id::PlayQueueDelete, "KEY_BACKSPACE" }, #else { Id::PlayQueueMoveUp, "M-up" }, { Id::PlayQueueMoveDown, "M-down" }, { Id::PlayQueueDelete, "KEY_DC" }, #endif { Id::ToggleMute, "m" }, { Id::TogglePause, "^P" }, { Id::Next, "l" }, { Id::Previous, "j" }, { Id::VolumeUp, "i" }, { Id::VolumeDown, "k" }, { Id::SeekForward, "o" }, { Id::SeekBack, "u" }, { Id::ToggleRepeat, "." }, { Id::ToggleShuffle, "," }, { Id::Stop, "^X" }, { Id::ViewRefresh, "KEY_F(5)" }, { Id::ToggleVisualizer, "v" }, { Id::RescanMetadata, "^R"}, { Id::ContextMenu, "M-enter" } }; /* custom keys */ static std::unordered_set<std::string> customKeys; static std::unordered_map<Id, std::string, EnumHasher> customIdToKey; /* preferences file */ static std::shared_ptr<Preferences> prefs; static void savePreferences() { for (const std::pair<std::string, Id>& pair : NAME_TO_ID) { prefs->SetString( pair.first.c_str(), Hotkeys::Get(pair.second).c_str()); } prefs->Save(); } static void loadPreferences() { prefs = Preferences::ForComponent("hotkeys", Preferences::ModeReadWrite); try { /* load all of the custom key mappings into customKeys and customIdToKey structures for quick lookup. */ if (prefs) { customKeys.clear(); std::vector<std::string> names; prefs->GetKeys(names); for (auto n : names) { auto it = NAME_TO_ID.find(n); if (it != NAME_TO_ID.end()) { customKeys.insert(prefs->GetString(n)); customIdToKey[it->second] = prefs->GetString(n); } } } /* write back to disk; this way any new hotkey defaults are picked up and saved so the user can edit them easily. */ savePreferences(); } catch (...) { std::cerr << "failed to load hotkeys.json! default hotkeys selected."; customKeys.clear(); customIdToKey.clear(); } } Hotkeys::Hotkeys() { } bool Hotkeys::Is(Id id, const std::string& kn) { if (!prefs) { loadPreferences(); } /* see if the user has specified a custom value for this hotkey. if they have, compare it to the custom value. */ auto custom = customIdToKey.find(id); if (custom != customIdToKey.end()) { return (custom->second == kn); } /* otherwise, let's compare against the default key, assuming the input key doesn't match ANY that the user has customized */ if (customKeys.find(kn) == customKeys.end()) { auto it = ID_TO_DEFAULT.find(id); if (it != ID_TO_DEFAULT.end() && it->second == kn) { return true; } } return false; } std::string Hotkeys::Get(Id id) { if (!prefs) { loadPreferences(); } auto custom = customIdToKey.find(id); if (custom != customIdToKey.end()) { return custom->second; } auto it = ID_TO_DEFAULT.find(id); if (it != ID_TO_DEFAULT.end()) { return it->second; } return ""; } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "rawspeedconfig.h" #include "decoders/DngDecoderSlices.h" #include "common/Common.h" // for uint32, getThrea... #include "common/Point.h" // for iPoint2D #include "decoders/RawDecoderException.h" // for RawDecoderException #include "decompressors/DeflateDecompressor.h" // for DeflateDecompressor #include "decompressors/JpegDecompressor.h" // for JpegDecompressor #include "decompressors/LJpegDecompressor.h" // for LJpegDecompressor #include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco... #include "io/Endianness.h" // for Endianness::big #include "io/IOException.h" // for IOException #include "tiff/TiffEntry.h" // IWYU pragma: keep #include "tiff/TiffIFD.h" // for getTiffEndianness #include <algorithm> // for move #include <cstdio> // for size_t #include <exception> // for exception #include <memory> // for allocator_traits... #include <string> // for string, operator+ #include <vector> // for allocator, vector using namespace std; namespace RawSpeed { void *DecodeThread(void *_this) { auto *me = (DngDecoderThread *)_this; DngDecoderSlices* parent = me->parent; try { parent->decodeSlice(me); } catch (const std::exception &exc) { parent->mRaw->setError(string( string("DNGDEcodeThread: Caught exception: ") + string(exc.what()))); } catch (...) { parent->mRaw->setError("DNGDEcodeThread: Caught unhandled exception."); } return nullptr; } DngDecoderSlices::DngDecoderSlices(FileMap *file, const RawImage &img, int _compression) : mFile(file), mRaw(img) { mFixLjpeg = false; compression = _compression; } void DngDecoderSlices::addSlice(const DngSliceElement &slice) { slices.push(slice); } void DngDecoderSlices::startDecoding() { #ifndef HAVE_PTHREAD DngDecoderThread t; while (!slices.empty()) { t.slices.push(slices.front()); slices.pop(); } t.parent = this; DecodeThread(&t); #else // Create threads nThreads = getThreadCount(); int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads; // decodedSlices = 0; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (uint32 i = 0; i < nThreads; i++) { auto t = make_unique<DngDecoderThread>(this); for (int j = 0; j < slicesPerThread ; j++) { if (!slices.empty()) { t->slices.push(slices.front()); slices.pop(); } } pthread_create(&t->threadid, &attr, DecodeThread, t.get()); threads.push_back(move(t)); } pthread_attr_destroy(&attr); void *status; for (auto& thread : threads) { pthread_join(thread->threadid, &status); } threads.clear(); #endif } void DngDecoderSlices::decodeSlice(DngDecoderThread* t) { if (compression == 1) { while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); UncompressedDecompressor decompressor(*mFile, e.byteOffset, e.byteCount, mRaw, true /* does not matter here */); size_t thisTileLength = e.offY + e.height > (uint32)mRaw->dim.y ? mRaw->dim.y - e.offY : e.height; iPoint2D size(mRaw->dim.x, thisTileLength); iPoint2D pos(0, e.offY); bool big_endian = (getTiffEndianness(mFile) == big); // DNG spec says that if not 8 or 16 bit/sample, always use big endian if (mBps != 8 && mBps != 16) big_endian = true; try { decompressor.readUncompressedRaw( size, pos, mRaw->getCpp() * mRaw->dim.x * mBps / 8, mBps, big_endian ? BitOrder_Jpeg : BitOrder_Plain); } catch (RawDecoderException& err) { mRaw->setError(err.what()); } catch (IOException& err) { mRaw->setError(err.what()); } } } else if (compression == 7) { while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); LJpegDecompressor d(*mFile, e.byteOffset, e.byteCount, mRaw); try { d.decode(e.offX, e.offY, mFixLjpeg); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } /* Deflate compression */ } else if (compression == 8) { #ifdef HAVE_ZLIB unsigned char *uBuffer = nullptr; while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); DeflateDecompressor z(*mFile, e.byteOffset, e.byteCount, mRaw, mPredictor, mBps); try { z.decode(&uBuffer, e.width, e.height, e.offX, e.offY); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } delete [] uBuffer; #else #pragma message \ "ZLIB is not present! Deflate compression will not be supported!" ThrowRDE("DngDecoderSlices: deflate support is disabled."); #endif /* Lossy DNG */ } else if (compression == 0x884c) { #ifdef HAVE_JPEG /* Each slice is a JPEG image */ while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); JpegDecompressor j(*mFile, e.byteOffset, e.byteCount, mRaw); try { j.decode(e.offX, e.offY); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } #else #pragma message "JPEG is not present! Lossy JPEG DNG will not be supported!" ThrowRDE("DngDecoderSlices: jpeg support is disabled."); #endif } else mRaw->setError("DngDecoderSlices: Unknown compression"); } int __attribute__((pure)) DngDecoderSlices::size() { return (int)slices.size(); } } // namespace RawSpeed <commit_msg>DngDecoderSlices::startDecoding(): unbreak !HAVE_PTHREAD build<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "rawspeedconfig.h" #include "decoders/DngDecoderSlices.h" #include "common/Common.h" // for uint32, getThrea... #include "common/Point.h" // for iPoint2D #include "decoders/RawDecoderException.h" // for RawDecoderException #include "decompressors/DeflateDecompressor.h" // for DeflateDecompressor #include "decompressors/JpegDecompressor.h" // for JpegDecompressor #include "decompressors/LJpegDecompressor.h" // for LJpegDecompressor #include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco... #include "io/Endianness.h" // for Endianness::big #include "io/IOException.h" // for IOException #include "tiff/TiffEntry.h" // IWYU pragma: keep #include "tiff/TiffIFD.h" // for getTiffEndianness #include <algorithm> // for move #include <cstdio> // for size_t #include <exception> // for exception #include <memory> // for allocator_traits... #include <string> // for string, operator+ #include <vector> // for allocator, vector using namespace std; namespace RawSpeed { void *DecodeThread(void *_this) { auto *me = (DngDecoderThread *)_this; DngDecoderSlices* parent = me->parent; try { parent->decodeSlice(me); } catch (const std::exception &exc) { parent->mRaw->setError(string( string("DNGDEcodeThread: Caught exception: ") + string(exc.what()))); } catch (...) { parent->mRaw->setError("DNGDEcodeThread: Caught unhandled exception."); } return nullptr; } DngDecoderSlices::DngDecoderSlices(FileMap *file, const RawImage &img, int _compression) : mFile(file), mRaw(img) { mFixLjpeg = false; compression = _compression; } void DngDecoderSlices::addSlice(const DngSliceElement &slice) { slices.push(slice); } void DngDecoderSlices::startDecoding() { #ifndef HAVE_PTHREAD DngDecoderThread t(this); while (!slices.empty()) { t.slices.push(slices.front()); slices.pop(); } DecodeThread(&t); #else // Create threads nThreads = getThreadCount(); int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads; // decodedSlices = 0; pthread_attr_t attr; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (uint32 i = 0; i < nThreads; i++) { auto t = make_unique<DngDecoderThread>(this); for (int j = 0; j < slicesPerThread ; j++) { if (!slices.empty()) { t->slices.push(slices.front()); slices.pop(); } } pthread_create(&t->threadid, &attr, DecodeThread, t.get()); threads.push_back(move(t)); } pthread_attr_destroy(&attr); void *status; for (auto& thread : threads) { pthread_join(thread->threadid, &status); } threads.clear(); #endif } void DngDecoderSlices::decodeSlice(DngDecoderThread* t) { if (compression == 1) { while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); UncompressedDecompressor decompressor(*mFile, e.byteOffset, e.byteCount, mRaw, true /* does not matter here */); size_t thisTileLength = e.offY + e.height > (uint32)mRaw->dim.y ? mRaw->dim.y - e.offY : e.height; iPoint2D size(mRaw->dim.x, thisTileLength); iPoint2D pos(0, e.offY); bool big_endian = (getTiffEndianness(mFile) == big); // DNG spec says that if not 8 or 16 bit/sample, always use big endian if (mBps != 8 && mBps != 16) big_endian = true; try { decompressor.readUncompressedRaw( size, pos, mRaw->getCpp() * mRaw->dim.x * mBps / 8, mBps, big_endian ? BitOrder_Jpeg : BitOrder_Plain); } catch (RawDecoderException& err) { mRaw->setError(err.what()); } catch (IOException& err) { mRaw->setError(err.what()); } } } else if (compression == 7) { while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); LJpegDecompressor d(*mFile, e.byteOffset, e.byteCount, mRaw); try { d.decode(e.offX, e.offY, mFixLjpeg); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } /* Deflate compression */ } else if (compression == 8) { #ifdef HAVE_ZLIB unsigned char *uBuffer = nullptr; while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); DeflateDecompressor z(*mFile, e.byteOffset, e.byteCount, mRaw, mPredictor, mBps); try { z.decode(&uBuffer, e.width, e.height, e.offX, e.offY); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } delete [] uBuffer; #else #pragma message \ "ZLIB is not present! Deflate compression will not be supported!" ThrowRDE("DngDecoderSlices: deflate support is disabled."); #endif /* Lossy DNG */ } else if (compression == 0x884c) { #ifdef HAVE_JPEG /* Each slice is a JPEG image */ while (!t->slices.empty()) { DngSliceElement e = t->slices.front(); t->slices.pop(); JpegDecompressor j(*mFile, e.byteOffset, e.byteCount, mRaw); try { j.decode(e.offX, e.offY); } catch (RawDecoderException &err) { mRaw->setError(err.what()); } catch (IOException &err) { mRaw->setError(err.what()); } } #else #pragma message "JPEG is not present! Lossy JPEG DNG will not be supported!" ThrowRDE("DngDecoderSlices: jpeg support is disabled."); #endif } else mRaw->setError("DngDecoderSlices: Unknown compression"); } int __attribute__((pure)) DngDecoderSlices::size() { return (int)slices.size(); } } // namespace RawSpeed <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNavigationData.h" #include "vnl/vnl_det.h" #include "mitkException.h" mitk::NavigationData::NavigationData() : itk::DataObject(), m_Position(), m_Orientation(0.0, 0.0, 0.0, 0.0), m_CovErrorMatrix(), m_HasPosition(true), m_HasOrientation(true), m_DataValid(false), m_IGTTimeStamp(0.0), m_Name() { m_Position.Fill(0.0); m_CovErrorMatrix.SetIdentity(); } mitk::NavigationData::~NavigationData() { } void mitk::NavigationData::Graft( const DataObject *data ) { // Attempt to cast data to an NavigationData const Self* nd; try { nd = dynamic_cast<const Self *>( data ); } catch( ... ) { itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast " << typeid(data).name() << " to " << typeid(const Self *).name() ); return; } if (!nd) { // pointer could not be cast back down itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast " << typeid(data).name() << " to " << typeid(const Self *).name() ); return; } // Now copy anything that is needed this->SetPosition(nd->GetPosition()); this->SetOrientation(nd->GetOrientation()); this->SetDataValid(nd->IsDataValid()); this->SetIGTTimeStamp(nd->GetIGTTimeStamp()); this->SetHasPosition(nd->GetHasPosition()); this->SetHasOrientation(nd->GetHasOrientation()); this->SetCovErrorMatrix(nd->GetCovErrorMatrix()); this->SetName(nd->GetName()); } bool mitk::NavigationData::IsDataValid() const { return m_DataValid; } void mitk::NavigationData::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "data valid: " << this->IsDataValid() << std::endl; os << indent << "Position: " << this->GetPosition() << std::endl; os << indent << "TimeStamp: " << this->GetIGTTimeStamp() << std::endl; os << indent << "HasPosition: " << this->GetHasPosition() << std::endl; os << indent << "HasOrientation: " << this->GetHasOrientation() << std::endl; os << indent << "CovErrorMatrix: " << this->GetCovErrorMatrix() << std::endl; } void mitk::NavigationData::CopyInformation( const DataObject* data ) { this->Superclass::CopyInformation( data ); const Self * nd = NULL; try { nd = dynamic_cast<const Self*>(data); } catch( ... ) { // data could not be cast back down itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self*).name() ); } if ( !nd ) { // pointer could not be cast back down itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self*).name() ); } /* copy all meta data */ } void mitk::NavigationData::SetPositionAccuracy(mitk::ScalarType error) { for ( int i = 0; i < 3; i++ ) for ( int j = 0; j < 3; j++ ) { m_CovErrorMatrix[ i ][ j ] = 0; // assume independence of position and orientation m_CovErrorMatrix[ i + 3 ][ j ] = 0; m_CovErrorMatrix[ i ][ j + 3 ] = 0; } m_CovErrorMatrix[0][0] = m_CovErrorMatrix[1][1] = m_CovErrorMatrix[2][2] = error * error; } void mitk::NavigationData::SetOrientationAccuracy(mitk::ScalarType error) { for ( int i = 0; i < 3; i++ ) for ( int j = 0; j < 3; j++ ) { m_CovErrorMatrix[ i + 3 ][ j + 3 ] = 0; // assume independence of position and orientation m_CovErrorMatrix[ i + 3 ][ j ] = 0; m_CovErrorMatrix[ i ][ j + 3 ] = 0; } m_CovErrorMatrix[3][3] = m_CovErrorMatrix[4][4] = m_CovErrorMatrix[5][5] = error * error; } mitk::NavigationData::NavigationData( mitk::AffineTransform3D::Pointer affineTransform3D, bool checkForRotationMatrix) : itk::DataObject(), m_Position(), m_CovErrorMatrix(), m_HasPosition(true), m_HasOrientation(true), m_DataValid(true), m_IGTTimeStamp(0.0), m_Name() { mitk::Vector3D offset = affineTransform3D->GetOffset(); m_Position[0] = offset[0]; m_Position[1] = offset[1]; m_Position[2] = offset[2]; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrix = affineTransform3D->GetMatrix().GetVnlMatrix(); vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrixTransposed = rotationMatrix.transpose(); if (checkForRotationMatrix) { // a quadratic matrix is a rotation matrix exactly when determinant is 1 and transposed is inverse if (!Equal(1.0, vnl_det(rotationMatrix)) || !((rotationMatrix*rotationMatrixTransposed).is_identity())) { mitkThrow() << "tried to initialize NavigationData with non-rotation matrix"; } } // the transpose is because vnl_quaterion expects a transposed rotation matrix m_Orientation = Quaternion(rotationMatrixTransposed); } mitk::AffineTransform3D::Pointer mitk::NavigationData::GetAffineTransform3D() { AffineTransform3D::Pointer affineTransform3D = AffineTransform3D::New(); // first set rotation affineTransform3D->SetMatrix(this->getRotationMatrix()); // now set offset Vector3D vector3D; for (int i = 0; i < 3; ++i) { vector3D[i] = m_Position[i]; } affineTransform3D->SetOffset(vector3D); return affineTransform3D; } mitk::Matrix3D mitk::NavigationData::getRotationMatrix() { vnl_matrix_fixed<ScalarType,3,3> vnl_rotation = m_Orientation.rotation_matrix_transpose().transpose(); Matrix3D mitkRotation; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mitkRotation[i][j] = vnl_rotation[i][j]; } } return mitkRotation; } mitk::Point3D mitk::NavigationData::Transform(const mitk::Point3D point) { return point; } <commit_msg>Implemented Transform method.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNavigationData.h" #include "vnl/vnl_det.h" #include "mitkException.h" mitk::NavigationData::NavigationData() : itk::DataObject(), m_Position(), m_Orientation(0.0, 0.0, 0.0, 0.0), m_CovErrorMatrix(), m_HasPosition(true), m_HasOrientation(true), m_DataValid(false), m_IGTTimeStamp(0.0), m_Name() { m_Position.Fill(0.0); m_CovErrorMatrix.SetIdentity(); } mitk::NavigationData::~NavigationData() { } void mitk::NavigationData::Graft( const DataObject *data ) { // Attempt to cast data to an NavigationData const Self* nd; try { nd = dynamic_cast<const Self *>( data ); } catch( ... ) { itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast " << typeid(data).name() << " to " << typeid(const Self *).name() ); return; } if (!nd) { // pointer could not be cast back down itkExceptionMacro( << "mitk::NavigationData::Graft cannot cast " << typeid(data).name() << " to " << typeid(const Self *).name() ); return; } // Now copy anything that is needed this->SetPosition(nd->GetPosition()); this->SetOrientation(nd->GetOrientation()); this->SetDataValid(nd->IsDataValid()); this->SetIGTTimeStamp(nd->GetIGTTimeStamp()); this->SetHasPosition(nd->GetHasPosition()); this->SetHasOrientation(nd->GetHasOrientation()); this->SetCovErrorMatrix(nd->GetCovErrorMatrix()); this->SetName(nd->GetName()); } bool mitk::NavigationData::IsDataValid() const { return m_DataValid; } void mitk::NavigationData::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "data valid: " << this->IsDataValid() << std::endl; os << indent << "Position: " << this->GetPosition() << std::endl; os << indent << "TimeStamp: " << this->GetIGTTimeStamp() << std::endl; os << indent << "HasPosition: " << this->GetHasPosition() << std::endl; os << indent << "HasOrientation: " << this->GetHasOrientation() << std::endl; os << indent << "CovErrorMatrix: " << this->GetCovErrorMatrix() << std::endl; } void mitk::NavigationData::CopyInformation( const DataObject* data ) { this->Superclass::CopyInformation( data ); const Self * nd = NULL; try { nd = dynamic_cast<const Self*>(data); } catch( ... ) { // data could not be cast back down itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self*).name() ); } if ( !nd ) { // pointer could not be cast back down itkExceptionMacro(<< "mitk::NavigationData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self*).name() ); } /* copy all meta data */ } void mitk::NavigationData::SetPositionAccuracy(mitk::ScalarType error) { for ( int i = 0; i < 3; i++ ) for ( int j = 0; j < 3; j++ ) { m_CovErrorMatrix[ i ][ j ] = 0; // assume independence of position and orientation m_CovErrorMatrix[ i + 3 ][ j ] = 0; m_CovErrorMatrix[ i ][ j + 3 ] = 0; } m_CovErrorMatrix[0][0] = m_CovErrorMatrix[1][1] = m_CovErrorMatrix[2][2] = error * error; } void mitk::NavigationData::SetOrientationAccuracy(mitk::ScalarType error) { for ( int i = 0; i < 3; i++ ) for ( int j = 0; j < 3; j++ ) { m_CovErrorMatrix[ i + 3 ][ j + 3 ] = 0; // assume independence of position and orientation m_CovErrorMatrix[ i + 3 ][ j ] = 0; m_CovErrorMatrix[ i ][ j + 3 ] = 0; } m_CovErrorMatrix[3][3] = m_CovErrorMatrix[4][4] = m_CovErrorMatrix[5][5] = error * error; } mitk::NavigationData::NavigationData( mitk::AffineTransform3D::Pointer affineTransform3D, bool checkForRotationMatrix) : itk::DataObject(), m_Position(), m_CovErrorMatrix(), m_HasPosition(true), m_HasOrientation(true), m_DataValid(true), m_IGTTimeStamp(0.0), m_Name() { mitk::Vector3D offset = affineTransform3D->GetOffset(); m_Position[0] = offset[0]; m_Position[1] = offset[1]; m_Position[2] = offset[2]; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrix = affineTransform3D->GetMatrix().GetVnlMatrix(); vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrixTransposed = rotationMatrix.transpose(); if (checkForRotationMatrix) { // a quadratic matrix is a rotation matrix exactly when determinant is 1 and transposed is inverse if (!Equal(1.0, vnl_det(rotationMatrix)) || !((rotationMatrix*rotationMatrixTransposed).is_identity())) { mitkThrow() << "tried to initialize NavigationData with non-rotation matrix"; } } // the transpose is because vnl_quaterion expects a transposed rotation matrix m_Orientation = Quaternion(rotationMatrixTransposed); } mitk::AffineTransform3D::Pointer mitk::NavigationData::GetAffineTransform3D() { AffineTransform3D::Pointer affineTransform3D = AffineTransform3D::New(); // first set rotation affineTransform3D->SetMatrix(this->getRotationMatrix()); // now set offset Vector3D vector3D; for (int i = 0; i < 3; ++i) { vector3D[i] = m_Position[i]; } affineTransform3D->SetOffset(vector3D); return affineTransform3D; } mitk::Matrix3D mitk::NavigationData::getRotationMatrix() { vnl_matrix_fixed<ScalarType,3,3> vnl_rotation = m_Orientation.rotation_matrix_transpose().transpose(); Matrix3D mitkRotation; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mitkRotation[i][j] = vnl_rotation[i][j]; } } return mitkRotation; } mitk::Point3D mitk::NavigationData::Transform(const mitk::Point3D point) { vnl_vector_fixed<ScalarType, 3> vnlPoint; for (int i = 0; i < 3; ++i) { vnlPoint[i] = point[i]; } // first get rotated point vnlPoint = this->GetOrientation().rotate(vnlPoint); Point3D resultingPoint; for (int i = 0; i < 3; ++i) { // now copy it to our format + offset resultingPoint[i] = vnlPoint[i] + this->GetPosition()[i]; } return resultingPoint; } <|endoftext|>
<commit_before>#ifndef __SYMBIONT_SPECIES_HPP_INCLUDED #define __SYMBIONT_SPECIES_HPP_INCLUDED #include "scene.hpp" #include "shader.hpp" #include "species.hpp" #include "species_or_glyph.hpp" #include "symbiont_material.hpp" #include "species_struct.hpp" #include "render_templates.hpp" #include "vboindexer.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <queue> // std::queue #include <string> // std::string #include <vector> // std::vector namespace yli { namespace ontology { class Entity; class Universe; class Biont; class SymbiontSpecies: public yli::ontology::Species { public: void bind_biont(yli::ontology::Biont* const biont); void unbind_biont(const std::size_t childID); // destructor. virtual ~SymbiontSpecies(); std::size_t get_indices_size() const; GLuint get_lightID() const; // constructor. SymbiontSpecies(yli::ontology::Universe* const universe, const SpeciesStruct& species_struct) : Species(universe, species_struct) { // constructor. this->shader = species_struct.shader; this->symbiont_material_parent = species_struct.symbiont_material; this->vertices = species_struct.vertices; this->uvs = species_struct.uvs; this->normals = species_struct.normals; this->light_position = species_struct.light_position; // get `childID` from `SymbiontMaterial` and set pointer to this `SymbiontSpecies`. this->bind_to_parent(); this->number_of_bionts = 0; this->child_vector_pointers_vector.push_back(&this->biont_pointer_vector); this->type_string = "yli::ontology::SymbiontSpecies*"; if (this->shader == nullptr) { std::cerr << "ERROR: `SymbiontSpecies::SymbiontSpecies`: `this->shader` is `nullptr`!\n"; return; } // Get a handle for our buffers. this->vertex_position_modelspaceID = glGetAttribLocation(this->shader->get_programID(), "vertexPosition_modelspace"); this->vertexUVID = glGetAttribLocation(this->shader->get_programID(), "vertexUV"); this->vertex_normal_modelspaceID = glGetAttribLocation(this->shader->get_programID(), "vertexNormal_modelspace"); // Get a handle for our "LightPosition" uniform. glUseProgram(this->shader->get_programID()); this->lightID = glGetUniformLocation(this->shader->get_programID(), "LightPosition_worldspace"); // water level. GLuint water_level_uniform_location = glGetUniformLocation(this->shader->get_programID(), "water_level"); const yli::ontology::Scene* const scene = static_cast<yli::ontology::Scene*>(this->shader->get_parent()); glUniform1f(water_level_uniform_location, scene->get_water_level()); // Fill the index buffer. yli::ontology::indexVBO( this->vertices, this->uvs, this->normals, this->indices, this->indexed_vertices, this->indexed_uvs, this->indexed_normals); // Load it into a VBO. glGenBuffers(1, &this->vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_vertices.size() * sizeof(glm::vec3), &this->indexed_vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &this->uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_uvs.size() * sizeof(glm::vec2), &this->indexed_uvs[0], GL_STATIC_DRAW); glGenBuffers(1, &this->normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->normalbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_normals.size() * sizeof(glm::vec3), &this->indexed_normals[0], GL_STATIC_DRAW); glGenBuffers(1, &this->elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0] , GL_STATIC_DRAW); // TODO: Compute the vertex graph of this `SymbiontSpecies` to enable object vertex modification! } yli::ontology::Entity* get_parent() const override; private: glm::vec3 light_position; // light position. template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend void yli::ontology::render_species_or_glyph(T1 species_or_glyph_pointer); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); void bind_to_parent(); // this method renders all `Object`s of this `SymbiontSpecies`. void render(); std::vector<yli::ontology::Biont*> biont_pointer_vector; std::queue<std::size_t> free_biontID_queue; std::size_t number_of_bionts; yli::ontology::SymbiontMaterial* symbiont_material_parent; // pointer to `SymbiontMaterial`. yli::ontology::Shader* shader; // pointer to `Shader`. std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. }; } } #endif <commit_msg>Bugfix: `SymbiontSpecies` constructor: set value of `type_string`.<commit_after>#ifndef __SYMBIONT_SPECIES_HPP_INCLUDED #define __SYMBIONT_SPECIES_HPP_INCLUDED #include "scene.hpp" #include "shader.hpp" #include "species.hpp" #include "species_or_glyph.hpp" #include "symbiont_material.hpp" #include "species_struct.hpp" #include "render_templates.hpp" #include "vboindexer.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <queue> // std::queue #include <string> // std::string #include <vector> // std::vector namespace yli { namespace ontology { class Entity; class Universe; class Biont; class SymbiontSpecies: public yli::ontology::Species { public: void bind_biont(yli::ontology::Biont* const biont); void unbind_biont(const std::size_t childID); // destructor. virtual ~SymbiontSpecies(); std::size_t get_indices_size() const; GLuint get_lightID() const; // constructor. SymbiontSpecies(yli::ontology::Universe* const universe, const SpeciesStruct& species_struct) : Species(universe, species_struct) { // constructor. this->shader = species_struct.shader; this->symbiont_material_parent = species_struct.symbiont_material; this->vertices = species_struct.vertices; this->uvs = species_struct.uvs; this->normals = species_struct.normals; this->light_position = species_struct.light_position; // get `childID` from `SymbiontMaterial` and set pointer to this `SymbiontSpecies`. this->bind_to_parent(); this->number_of_bionts = 0; this->child_vector_pointers_vector.push_back(&this->biont_pointer_vector); this->type_string = "yli::ontology::SymbiontSpecies*"; if (this->shader == nullptr) { std::cerr << "ERROR: `SymbiontSpecies::SymbiontSpecies`: `this->shader` is `nullptr`!\n"; return; } // Get a handle for our buffers. this->vertex_position_modelspaceID = glGetAttribLocation(this->shader->get_programID(), "vertexPosition_modelspace"); this->vertexUVID = glGetAttribLocation(this->shader->get_programID(), "vertexUV"); this->vertex_normal_modelspaceID = glGetAttribLocation(this->shader->get_programID(), "vertexNormal_modelspace"); // Get a handle for our "LightPosition" uniform. glUseProgram(this->shader->get_programID()); this->lightID = glGetUniformLocation(this->shader->get_programID(), "LightPosition_worldspace"); // water level. GLuint water_level_uniform_location = glGetUniformLocation(this->shader->get_programID(), "water_level"); const yli::ontology::Scene* const scene = static_cast<yli::ontology::Scene*>(this->shader->get_parent()); glUniform1f(water_level_uniform_location, scene->get_water_level()); // Fill the index buffer. yli::ontology::indexVBO( this->vertices, this->uvs, this->normals, this->indices, this->indexed_vertices, this->indexed_uvs, this->indexed_normals); // Load it into a VBO. glGenBuffers(1, &this->vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_vertices.size() * sizeof(glm::vec3), &this->indexed_vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &this->uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_uvs.size() * sizeof(glm::vec2), &this->indexed_uvs[0], GL_STATIC_DRAW); glGenBuffers(1, &this->normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, this->normalbuffer); glBufferData(GL_ARRAY_BUFFER, this->indexed_normals.size() * sizeof(glm::vec3), &this->indexed_normals[0], GL_STATIC_DRAW); glGenBuffers(1, &this->elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0] , GL_STATIC_DRAW); // TODO: Compute the vertex graph of this `SymbiontSpecies` to enable object vertex modification! // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::SymbiontSpecies*"; } yli::ontology::Entity* get_parent() const override; private: glm::vec3 light_position; // light position. template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend void yli::ontology::render_species_or_glyph(T1 species_or_glyph_pointer); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); void bind_to_parent(); // this method renders all `Object`s of this `SymbiontSpecies`. void render(); std::vector<yli::ontology::Biont*> biont_pointer_vector; std::queue<std::size_t> free_biontID_queue; std::size_t number_of_bionts; yli::ontology::SymbiontMaterial* symbiont_material_parent; // pointer to `SymbiontMaterial`. yli::ontology::Shader* shader; // pointer to `Shader`. std::string model_file_format; // type of the model file, eg. `"bmp"`. std::string model_filename; // filename of the model file. }; } } #endif <|endoftext|>
<commit_before>/* binner.cpp Copyright (C) 2015 Braam Research, LLC. */ #include "metrix.h" #include "common.h" #include "OskarBinReader.h" #include <cassert> #include <cstdio> #include <cstring> #include <sstream> using namespace std; template < int grid_size , int over , int w_planes > inline void pregridPoint(double scale, Double3 uvw, Pregridded & res){ uvw.u *= scale; uvw.v *= scale; uvw.w *= scale; int w_plane = int(round (uvw.w / (w_planes/2))) , max_supp = int(get_supp(w_plane)) // We additionally translate these u v by -max_supp/2 // because gridding procedure translates them back , u = int(round(uvw.u) + grid_size/2 - max_supp/2) , v = int(round(uvw.v) + grid_size/2 - max_supp/2) , over_u = int(round(over * (uvw.u - u))) , over_v = int(round(over * (uvw.v - v))) ; res.u = (short)u; res.v = (short)v; res.gcf_layer_w_plane = (char)w_plane; res.gcf_layer_over = (char)(over_u * over + over_v); res.gcf_layer_supp = (short)max_supp; } typedef unsigned int uint; template <int divs> struct filegrid { void flush(const char * prefix) { for(int i = 0; i < divs; i++) { for(int j = 0; j < divs; j++) { if (pre_files[i][j].tellp() > 0) { static char name[512]; char * last = name + sprintf(name, "%s%03u-%03u", prefix, i, j); FILE *f; char * buf; streamoff cnt; sprintf(last, "-pre.dat"); f = fopen(name, "wb"); if (f == nullptr) printf("Gone bad at %s on (%u,%u) with %d\n", name, i, j, errno); cnt = pre_files[i][j].tellp(); buf = new char[cnt]; pre_files[i][j].read(buf, cnt); fwrite(buf, 1, cnt, f); fclose(f); delete [] buf; sprintf(last, "-vis.dat"); f = fopen(name, "wb"); if (f == nullptr) printf("Gone bad at %s on (%u,%u) with %d\n", name, i, j, errno); cnt = vis_files[i][j].tellp(); buf = new char[cnt]; vis_files[i][j].read(buf, cnt); fwrite(buf, 1, cnt, f); fclose(f); delete [] buf; } } } } void put_point(uint x, uint y, const Pregridded & p, const Double4c & vis){ pre_files[x][y].write((char*)&p, sizeof(p)); vis_files[x][y].write((char*)&vis, sizeof(vis)); } private: stringstream pre_files[divs][divs]; stringstream vis_files[divs][divs]; }; template < int grid_size , int over , int w_planes , int divs > // We don't perform baselines sorting yet. // But it is not so hard to implement it. inline int doit(const char * prefix, int num_channels, int num_points, double scale, Double4c* amps, Double3 * uvws) { const int div_size = grid_size / divs; int res = 0; filegrid<divs> * filesp = new filegrid<divs>[num_channels]; Double4c * amps_end = amps + num_points , * amp_curr = amps ; Double3 * uvw_curr = uvws; while(amp_curr < amps_end){ for(int i = 0; i < num_channels; i++){ Pregridded p; pregridPoint<grid_size, over, w_planes>(scale, *uvw_curr, p); // p is passed as reference and updated! div_t us, vs; // NOTE: we have u and v translated by -p.gcf_layer_supp/2 // in pregridPoint, thus we temporarily put them back. us = div(p.u + p.gcf_layer_supp/2, div_size); vs = div(p.v + p.gcf_layer_supp/2, div_size); assert(us.quot >= 0 && vs.quot >= 0 && us.quot < divs && vs.quot < divs ); filesp[i].put_point(us.quot, vs.quot, p, *amp_curr); int margin; margin = p.gcf_layer_supp / 2; // Optimize slightly for most inhabited w-plane if (margin > 0) { bool leftm, rightm, topm, botm; leftm = false; rightm = false; topm = false; botm = false; if (us.rem < margin && us.quot >= 1) { filesp[i].put_point(us.quot-1, vs.quot, p, *amp_curr); leftm = true; } else if (us.rem > 1 - margin && us.quot < divs-1) { filesp[i].put_point(us.quot+1, vs.quot, p, *amp_curr); rightm = true; } if (vs.rem < margin && vs.quot >= 1) { filesp[i].put_point(us.quot, vs.quot-1, p, *amp_curr); botm = true; } else if (vs.rem > 1 - margin && vs.quot < divs-1) { filesp[i].put_point(us.quot, vs.quot+1, p, *amp_curr); topm = true; } if (leftm && botm) { filesp[i].put_point(us.quot-1, vs.quot-1, p, *amp_curr); } else if (leftm && topm) { filesp[i].put_point(us.quot-1, vs.quot+1, p, *amp_curr); } else if (rightm && topm) { filesp[i].put_point(us.quot+1, vs.quot+1, p, *amp_curr); } else if (rightm && botm) { filesp[i].put_point(us.quot+1, vs.quot-1, p, *amp_curr); } } amp_curr++; uvw_curr++; } } printf("Binning is done. Writing...\n"); for(int i = 0; i < num_channels; i++){ char new_prefix[256]; snprintf(new_prefix, 256, "%s%06d-", prefix, i); filesp[i].flush(new_prefix); } delete [] filesp; return res; } extern "C" int bin(const char * prefix, int num_channels, int num_points, double scale, Double4c* amps, Double3 * uvws) { return doit<GRID_SIZE, OVER, WPLANES, DIVIDERS>(prefix, num_channels, num_points, scale, amps, uvws); } <commit_msg>Basic error handling.<commit_after>/* binner.cpp Copyright (C) 2015 Braam Research, LLC. */ #include "metrix.h" #include "common.h" #include "OskarBinReader.h" #include <cassert> #include <cstdio> #include <cstring> #include <sstream> using namespace std; template < int grid_size , int over , int w_planes > inline void pregridPoint(double scale, Double3 uvw, Pregridded & res){ uvw.u *= scale; uvw.v *= scale; uvw.w *= scale; int w_plane = int(round (uvw.w / (w_planes/2))) , max_supp = int(get_supp(w_plane)) // We additionally translate these u v by -max_supp/2 // because gridding procedure translates them back , u = int(round(uvw.u) + grid_size/2 - max_supp/2) , v = int(round(uvw.v) + grid_size/2 - max_supp/2) , over_u = int(round(over * (uvw.u - u))) , over_v = int(round(over * (uvw.v - v))) ; res.u = (short)u; res.v = (short)v; res.gcf_layer_w_plane = (char)w_plane; res.gcf_layer_over = (char)(over_u * over + over_v); res.gcf_layer_supp = (short)max_supp; } typedef unsigned int uint; template <int divs> struct filegrid { int flush(const char * prefix) { for(int i = 0; i < divs; i++) { for(int j = 0; j < divs; j++) { if (pre_files[i][j].tellp() > 0) { static char name[512]; char * last = name + sprintf(name, "%s%03u-%03u", prefix, i, j); FILE *f; char * buf; streamoff cnt; sprintf(last, "-pre.dat"); f = fopen(name, "wb"); if (f == nullptr) { printf("Gone bad at %s on (%u,%u) with %d\n", name, i, j, errno); return errno; } cnt = pre_files[i][j].tellp(); buf = new char[cnt]; pre_files[i][j].read(buf, cnt); fwrite(buf, 1, cnt, f); fclose(f); delete [] buf; sprintf(last, "-vis.dat"); f = fopen(name, "wb"); if (f == nullptr) { printf("Gone bad at %s on (%u,%u) with %d\n", name, i, j, errno); return errno; } cnt = vis_files[i][j].tellp(); buf = new char[cnt]; vis_files[i][j].read(buf, cnt); fwrite(buf, 1, cnt, f); fclose(f); delete [] buf; } } } return 0; } void put_point(uint x, uint y, const Pregridded & p, const Double4c & vis){ pre_files[x][y].write((char*)&p, sizeof(p)); vis_files[x][y].write((char*)&vis, sizeof(vis)); } private: stringstream pre_files[divs][divs]; stringstream vis_files[divs][divs]; }; template < int grid_size , int over , int w_planes , int divs > // We don't perform baselines sorting yet. // But it is not so hard to implement it. inline int doit(const char * prefix, int num_channels, int num_points, double scale, Double4c* amps, Double3 * uvws) { const int div_size = grid_size / divs; int res = 0; filegrid<divs> * filesp = new filegrid<divs>[num_channels]; Double4c * amps_end = amps + num_points , * amp_curr = amps ; Double3 * uvw_curr = uvws; while(amp_curr < amps_end){ for(int i = 0; i < num_channels; i++){ Pregridded p; pregridPoint<grid_size, over, w_planes>(scale, *uvw_curr, p); // p is passed as reference and updated! div_t us, vs; // NOTE: we have u and v translated by -p.gcf_layer_supp/2 // in pregridPoint, thus we temporarily put them back. us = div(p.u + p.gcf_layer_supp/2, div_size); vs = div(p.v + p.gcf_layer_supp/2, div_size); assert(us.quot >= 0 && vs.quot >= 0 && us.quot < divs && vs.quot < divs ); filesp[i].put_point(us.quot, vs.quot, p, *amp_curr); int margin; margin = p.gcf_layer_supp / 2; // Optimize slightly for most inhabited w-plane if (margin > 0) { bool leftm, rightm, topm, botm; leftm = false; rightm = false; topm = false; botm = false; if (us.rem < margin && us.quot >= 1) { filesp[i].put_point(us.quot-1, vs.quot, p, *amp_curr); leftm = true; } else if (us.rem > 1 - margin && us.quot < divs-1) { filesp[i].put_point(us.quot+1, vs.quot, p, *amp_curr); rightm = true; } if (vs.rem < margin && vs.quot >= 1) { filesp[i].put_point(us.quot, vs.quot-1, p, *amp_curr); botm = true; } else if (vs.rem > 1 - margin && vs.quot < divs-1) { filesp[i].put_point(us.quot, vs.quot+1, p, *amp_curr); topm = true; } if (leftm && botm) { filesp[i].put_point(us.quot-1, vs.quot-1, p, *amp_curr); } else if (leftm && topm) { filesp[i].put_point(us.quot-1, vs.quot+1, p, *amp_curr); } else if (rightm && topm) { filesp[i].put_point(us.quot+1, vs.quot+1, p, *amp_curr); } else if (rightm && botm) { filesp[i].put_point(us.quot+1, vs.quot-1, p, *amp_curr); } } amp_curr++; uvw_curr++; } } printf("Binning is done. Writing...\n"); for(int i = 0; i < num_channels; i++){ char new_prefix[256]; snprintf(new_prefix, 256, "%s%06d-", prefix, i); res = filesp[i].flush(new_prefix); if (res != 0) break; } delete [] filesp; return res; } extern "C" int bin(const char * prefix, int num_channels, int num_points, double scale, Double4c* amps, Double3 * uvws) { return doit<GRID_SIZE, OVER, WPLANES, DIVIDERS>(prefix, num_channels, num_points, scale, amps, uvws); } <|endoftext|>
<commit_before>/* * Copyright 2016 - 2019 gtalent2@gmail.com * * 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 <iostream> #include <string_view> #include <vector> #include <ox/claw/read.hpp> #include "pack.hpp" namespace nostalgia { namespace { [[nodiscard]] static constexpr bool endsWith(std::string_view str, std::string_view ending) { return str.size() >= ending.size() && str.substr(str.size() - ending.size()) == ending; } /** * Convert path references to inodes to save space * @param buff buffer holding file * @return error * stub for now */ [[nodiscard]] ox::Error pathToInode(std::vector<uint8_t>*) { return OxError(0); } // stub for now [[nodiscard]] ox::Error toMetalClaw(std::vector<uint8_t> *buff) { auto [mc, err] = ox::stripClawHeader(ox::bit_cast<char*>(buff->data()), buff->size()); std::cout << "buff size: " << buff->size() << '\n'; oxReturnError(err); buff->resize(mc.size()); ox_memcpy(buff->data(), mc.data(), mc.size()); return OxError(0); } // claw file transformations are broken out because path to inode // transformations need to be done after the copy to the new FS is complete [[nodiscard]] ox::Error transformClaw(ox::FileSystem32 *dest, std::string path) { // copy std::cout << "transformClaw: path: " << path << '\n'; oxTrace("pack::transformClaw") << "path:" << path.c_str(); return dest->ls(path.c_str(), [dest, path](const char *name, ox::InodeId_t) { auto filePath = path + name; auto [stat, err] = dest->stat(filePath.c_str()); oxReturnError(err); if (stat.fileType == ox::FileType_Directory) { const auto dir = path + name + '/'; oxReturnError(transformClaw(dest, dir)); } else { std::cout << filePath << '\n'; // do transforms if (endsWith(name, ".ng") || endsWith(name, ".npal")) { // load file std::vector<uint8_t> buff(stat.size); oxReturnError(dest->read(filePath.c_str(), buff.data(), buff.size())); // do transformations oxReturnError(pathToInode(&buff)); oxReturnError(toMetalClaw(&buff)); // write file to dest oxReturnError(dest->write(filePath.c_str(), buff.data(), buff.size())); } } return OxError(0); }); } [[nodiscard]] ox::Error verifyFile(ox::FileSystem32 *fs, const std::string &path, const std::vector<uint8_t> &expected) noexcept { std::vector<uint8_t> buff(expected.size()); oxReturnError(fs->read(path.c_str(), buff.data(), buff.size())); return OxError(buff == expected ? 0 : 1); } struct VerificationPair { std::string path; std::vector<uint8_t> buff; }; [[nodiscard]] ox::Error copy(ox::PassThroughFS *src, ox::FileSystem32 *dest, std::string path) { std::cout << "copying directory: " << path << '\n'; std::vector<VerificationPair> verficationPairs; // copy oxReturnError(src->ls(path.c_str(), [&verficationPairs, src, dest, path](std::string name, ox::InodeId_t) { std::cout << "reading " << name << '\n'; auto currentFile = path + name; auto [stat, err] = src->stat((currentFile).c_str()); oxReturnError(err); if (stat.fileType == ox::FileType_Directory) { oxReturnError(dest->mkdir(currentFile.c_str(), true)); oxReturnError(copy(src, dest, currentFile + '/')); } else { std::vector<uint8_t> buff; // do transforms //const std::string OldExt = path.substr(path.find_last_of('.')); // load file buff.resize(stat.size); oxReturnError(src->read(currentFile.c_str(), buff.data(), buff.size())); // write file to dest std::cout << "writing " << currentFile << '\n'; oxReturnError(dest->write(currentFile.c_str(), buff.data(), buff.size())); oxReturnError(verifyFile(dest, currentFile, buff)); verficationPairs.push_back({currentFile, buff}); } return OxError(0); })); // verify all at once in addition to right after the files are written for (auto v : verficationPairs) { oxReturnError(verifyFile(dest, v.path, v.buff)); } return OxError(0); } } [[nodiscard]] ox::Error pack(ox::PassThroughFS *src, ox::FileSystem32 *dest) { oxReturnError(copy(src, dest, "/")); std::cout << '\n'; oxReturnError(transformClaw(dest, "/")); return OxError(0); } } <commit_msg>[nostalgia/tools/pack] Cleanup debug code<commit_after>/* * Copyright 2016 - 2019 gtalent2@gmail.com * * 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 <iostream> #include <string_view> #include <vector> #include <ox/claw/read.hpp> #include "pack.hpp" namespace nostalgia { namespace { [[nodiscard]] static constexpr bool endsWith(std::string_view str, std::string_view ending) { return str.size() >= ending.size() && str.substr(str.size() - ending.size()) == ending; } /** * Convert path references to inodes to save space * @param buff buffer holding file * @return error * stub for now */ [[nodiscard]] ox::Error pathToInode(std::vector<uint8_t>*) { return OxError(0); } // stub for now [[nodiscard]] ox::Error toMetalClaw(std::vector<uint8_t> *buff) { auto [mc, err] = ox::stripClawHeader(ox::bit_cast<char*>(buff->data()), buff->size()); oxReturnError(err); buff->resize(mc.size()); ox_memcpy(buff->data(), mc.data(), mc.size()); return OxError(0); } // claw file transformations are broken out because path to inode // transformations need to be done after the copy to the new FS is complete [[nodiscard]] ox::Error transformClaw(ox::FileSystem32 *dest, std::string path) { // copy oxTrace("pack::transformClaw") << "path:" << path.c_str(); return dest->ls(path.c_str(), [dest, path](const char *name, ox::InodeId_t) { auto filePath = path + name; auto [stat, err] = dest->stat(filePath.c_str()); oxReturnError(err); if (stat.fileType == ox::FileType_Directory) { const auto dir = path + name + '/'; oxReturnError(transformClaw(dest, dir)); } else { // do transforms if (endsWith(name, ".ng") || endsWith(name, ".npal")) { // load file std::vector<uint8_t> buff(stat.size); oxReturnError(dest->read(filePath.c_str(), buff.data(), buff.size())); // do transformations oxReturnError(pathToInode(&buff)); oxReturnError(toMetalClaw(&buff)); // write file to dest oxReturnError(dest->write(filePath.c_str(), buff.data(), buff.size())); } } return OxError(0); }); } [[nodiscard]] ox::Error verifyFile(ox::FileSystem32 *fs, const std::string &path, const std::vector<uint8_t> &expected) noexcept { std::vector<uint8_t> buff(expected.size()); oxReturnError(fs->read(path.c_str(), buff.data(), buff.size())); return OxError(buff == expected ? 0 : 1); } struct VerificationPair { std::string path; std::vector<uint8_t> buff; }; [[nodiscard]] ox::Error copy(ox::PassThroughFS *src, ox::FileSystem32 *dest, std::string path) { std::cout << "copying directory: " << path << '\n'; std::vector<VerificationPair> verficationPairs; // copy oxReturnError(src->ls(path.c_str(), [&verficationPairs, src, dest, path](std::string name, ox::InodeId_t) { std::cout << "reading " << name << '\n'; auto currentFile = path + name; auto [stat, err] = src->stat((currentFile).c_str()); oxReturnError(err); if (stat.fileType == ox::FileType_Directory) { oxReturnError(dest->mkdir(currentFile.c_str(), true)); oxReturnError(copy(src, dest, currentFile + '/')); } else { std::vector<uint8_t> buff; // do transforms //const std::string OldExt = path.substr(path.find_last_of('.')); // load file buff.resize(stat.size); oxReturnError(src->read(currentFile.c_str(), buff.data(), buff.size())); // write file to dest std::cout << "writing " << currentFile << '\n'; oxReturnError(dest->write(currentFile.c_str(), buff.data(), buff.size())); oxReturnError(verifyFile(dest, currentFile, buff)); verficationPairs.push_back({currentFile, buff}); } return OxError(0); })); // verify all at once in addition to right after the files are written for (auto v : verficationPairs) { oxReturnError(verifyFile(dest, v.path, v.buff)); } return OxError(0); } } [[nodiscard]] ox::Error pack(ox::PassThroughFS *src, ox::FileSystem32 *dest) { oxReturnError(copy(src, dest, "/")); oxReturnError(transformClaw(dest, "/")); return OxError(0); } } <|endoftext|>
<commit_before>%% %% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 %% %% Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> %% $header $includes $beginSlotsClass $slot=5,3,0|statusChanged( QQuickWidget::Status status ) $slot=5,3,0|sceneGraphError( QQuickWindow::SceneGraphError error, const QString & message ) $endSlotsClass <commit_msg>QtQuickWidgets: data for code generation updated<commit_after>%% %% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 %% %% Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> %% $header $includes=5,3,0 $beginSlotsClass $slot=5,3,0|statusChanged( QQuickWidget::Status status ) $slot=5,3,0|sceneGraphError( QQuickWindow::SceneGraphError error, const QString & message ) $endSlotsClass <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertystatecontainer.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:59:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX #include "comphelper/propertystatecontainer.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; namespace { static ::rtl::OUString lcl_getUnknownPropertyErrorMessage( const ::rtl::OUString& _rPropertyName ) { // TODO: perhaps it's time to think about resources in the comphelper module? // Would be nice to have localized exception strings (a simply resource file containing // strings only would suffice, and could be realized with an UNO service, so we do not // need the dependency to the Tools project) ::rtl::OUStringBuffer sMessage; sMessage.appendAscii( "The property \"" ); sMessage.append( _rPropertyName ); sMessage.appendAscii( "\" is unknown." ); return sMessage.makeStringAndClear(); } } //===================================================================== //= OPropertyStateContainer //===================================================================== //--------------------------------------------------------------------- OPropertyStateContainer::OPropertyStateContainer( ::cppu::OBroadcastHelper& _rBHelper ) :OPropertyContainer( _rBHelper ) { } //-------------------------------------------------------------------- Any SAL_CALL OPropertyStateContainer::queryInterface( const Type& _rType ) throw (RuntimeException) { Any aReturn = OPropertyContainer::queryInterface( _rType ); if ( !aReturn.hasValue() ) aReturn = OPropertyStateContainer_TBase::queryInterface( _rType ); return aReturn; } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XTYPEPROVIDER2( OPropertyStateContainer, OPropertyContainer, OPropertyStateContainer_TBase ) //-------------------------------------------------------------------- sal_Int32 OPropertyStateContainer::getHandleForName( const ::rtl::OUString& _rPropertyName ) SAL_THROW( ( UnknownPropertyException ) ) { // look up the handle for the name ::cppu::IPropertyArrayHelper& rPH = getInfoHelper(); sal_Int32 nHandle = rPH.getHandleByName( _rPropertyName ); if ( -1 == nHandle ) throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( _rPropertyName ), static_cast< XPropertyState* >( this ) ); return nHandle; } //-------------------------------------------------------------------- PropertyState SAL_CALL OPropertyStateContainer::getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException) { return getPropertyStateByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- Sequence< PropertyState > SAL_CALL OPropertyStateContainer::getPropertyStates( const Sequence< ::rtl::OUString >& _rPropertyNames ) throw (UnknownPropertyException, RuntimeException) { sal_Int32 nProperties = _rPropertyNames.getLength(); Sequence< PropertyState> aStates( nProperties ); if ( !nProperties ) return aStates; #ifdef _DEBUG // precondition: property sequence is sorted (the algorythm below relies on this) { const ::rtl::OUString* pNames = _rPropertyNames.getConstArray(); const ::rtl::OUString* pNamesCompare = pNames + 1; const ::rtl::OUString* pNamesEnd = _rPropertyNames.getConstArray() + _rPropertyNames.getLength(); for ( ; pNamesCompare != pNamesEnd; ++pNames, ++pNamesCompare ) OSL_PRECOND( pNames->compareTo( *pNamesCompare ) < 0, "OPropertyStateContainer::getPropertyStates: property sequence not sorted!" ); } #endif const ::rtl::OUString* pLookup = _rPropertyNames.getConstArray(); const ::rtl::OUString* pLookupEnd = pLookup + nProperties; PropertyState* pStates = aStates.getArray(); cppu::IPropertyArrayHelper& rHelper = getInfoHelper(); Sequence< Property> aAllProperties = rHelper.getProperties(); sal_Int32 nAllProperties = aAllProperties.getLength(); const Property* pAllProperties = aAllProperties.getConstArray(); const Property* pAllPropertiesEnd = pAllProperties + nAllProperties; osl::MutexGuard aGuard( rBHelper.rMutex ); for ( ; ( pAllProperties != pAllPropertiesEnd ) && ( pLookup != pLookupEnd ); ++pAllProperties ) { #ifdef _DEBUG if ( pAllProperties < pAllPropertiesEnd - 1 ) OSL_ENSURE( pAllProperties->Name.compareTo( (pAllProperties + 1)->Name ) < 0, "OPropertyStateContainer::getPropertyStates: all-properties not sorted!" ); #endif if ( pAllProperties->Name.equals( *pLookup ) ) { *pStates++ = getPropertyState( *pLookup ); ++pLookup; } } if ( pLookup != pLookupEnd ) // we run out of properties from the IPropertyArrayHelper, but still have properties to lookup // -> we were asked for a nonexistent property throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( *pLookup ), static_cast< XPropertyState* >( this ) ); return aStates; } //-------------------------------------------------------------------- void SAL_CALL OPropertyStateContainer::setPropertyToDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException) { setPropertyToDefaultByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- Any SAL_CALL OPropertyStateContainer::getPropertyDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, WrappedTargetException, RuntimeException) { return getPropertyDefaultByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- PropertyState OPropertyStateContainer::getPropertyStateByHandle( sal_Int32 _nHandle ) { // simply compare the current and the default value Any aCurrentValue; getFastPropertyValue( aCurrentValue, _nHandle ); Any aDefaultValue = getPropertyDefaultByHandle( _nHandle ); sal_Bool bEqual = uno_type_equalData( const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(), const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(), cpp_queryInterface, cpp_release ); if ( bEqual ) return PropertyState_DEFAULT_VALUE; else return PropertyState_DIRECT_VALUE; } //-------------------------------------------------------------------- void OPropertyStateContainer::setPropertyToDefaultByHandle( sal_Int32 _nHandle ) { setFastPropertyValue( _nHandle, getPropertyDefaultByHandle( _nHandle ) ); } //......................................................................... } // namespace comphelper //......................................................................... #ifdef FS_PRIV_DEBUG #define STATECONTAINER_TEST #endif #ifdef STATECONTAINER_TEST #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; //===================================================================== //= Test - compiler test //===================================================================== typedef ::cppu::OWeakAggObject Test_RefCountBase; class Test :public OMutexAndBroadcastHelper ,public OPropertyStateContainer ,public OPropertyArrayUsageHelper< Test > ,public Test_RefCountBase { private: ::rtl::OUString m_sStringProperty; Reference< XInterface > m_xInterfaceProperty; Any m_aMayBeVoidProperty; protected: Test( ); DECLARE_XINTERFACE( ) public: static Test* Create( ); protected: virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; protected: // OPropertyStateContainer overridables virtual Any getPropertyDefaultByHandle( sal_Int32 _nHandle ) const; }; //--------------------------------------------------------------------- Test::Test( ) :OPropertyStateContainer( GetBroadcastHelper() ) { registerProperty( ::rtl::OUString::createFromAscii( "StringProperty" ), 1, PropertyAttribute::BOUND, &m_sStringProperty, ::getCppuType( &m_sStringProperty ) ); registerProperty( ::rtl::OUString::createFromAscii( "InterfaceProperty" ), 2, PropertyAttribute::BOUND, &m_xInterfaceProperty, ::getCppuType( &m_xInterfaceProperty ) ); registerMayBeVoidProperty( ::rtl::OUString::createFromAscii( "IntProperty" ), 3, PropertyAttribute::BOUND, &m_aMayBeVoidProperty, ::getCppuType( static_cast< sal_Int32* >( NULL ) ) ); registerPropertyNoMember( ::rtl::OUString::createFromAscii( "OtherInterfaceProperty" ), 4, PropertyAttribute::BOUND | PropertyAttribute::MAYBEVOID, ::getCppuType( static_cast< Reference< XInterface >* >( NULL ) ), NULL ); } //--------------------------------------------------------------------- IMPLEMENT_FORWARD_XINTERFACE2( Test, Test_RefCountBase, OPropertyStateContainer ) //--------------------------------------------------------------------- Any Test::getPropertyDefaultByHandle( sal_Int32 _nHandle ) const { Any aDefault; switch ( _nHandle ) { case 1: aDefault = makeAny( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringPropertyDefault" ) ) ); break; case 2: aDefault = makeAny( Reference< XInterface >( ) ); break; case 3: // void break; case 4: aDefault = makeAny( Reference< XInterface >( ) ); break; default: OSL_ENSURE( sal_False, "Test::getPropertyDefaultByHandle: invalid handle!" ); } return aDefault; } //--------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL Test::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ); } //--------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& SAL_CALL Test::getInfoHelper() { return *getArrayHelper(); } //--------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* Test::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties( aProps ); return new ::cppu::OPropertyArrayHelper( aProps ); } //--------------------------------------------------------------------- Test* Test::Create( ) { Test* pInstance = new Test; return pInstance; } //......................................................................... } // namespace comphelper //......................................................................... #endif <commit_msg>INTEGRATION: CWS warnings01 (1.2.118); FILE MERGED 2005/09/23 03:23:55 sb 1.2.118.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/08 13:16:55 sb 1.2.118.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertystatecontainer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 22:52:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX #include "comphelper/propertystatecontainer.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; namespace { static ::rtl::OUString lcl_getUnknownPropertyErrorMessage( const ::rtl::OUString& _rPropertyName ) { // TODO: perhaps it's time to think about resources in the comphelper module? // Would be nice to have localized exception strings (a simply resource file containing // strings only would suffice, and could be realized with an UNO service, so we do not // need the dependency to the Tools project) ::rtl::OUStringBuffer sMessage; sMessage.appendAscii( "The property \"" ); sMessage.append( _rPropertyName ); sMessage.appendAscii( "\" is unknown." ); return sMessage.makeStringAndClear(); } } //===================================================================== //= OPropertyStateContainer //===================================================================== //--------------------------------------------------------------------- OPropertyStateContainer::OPropertyStateContainer( ::cppu::OBroadcastHelper& _rBHelper ) :OPropertyContainer( _rBHelper ) { } //-------------------------------------------------------------------- Any SAL_CALL OPropertyStateContainer::queryInterface( const Type& _rType ) throw (RuntimeException) { Any aReturn = OPropertyContainer::queryInterface( _rType ); if ( !aReturn.hasValue() ) aReturn = OPropertyStateContainer_TBase::queryInterface( _rType ); return aReturn; } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XTYPEPROVIDER2( OPropertyStateContainer, OPropertyContainer, OPropertyStateContainer_TBase ) //-------------------------------------------------------------------- sal_Int32 OPropertyStateContainer::getHandleForName( const ::rtl::OUString& _rPropertyName ) SAL_THROW( ( UnknownPropertyException ) ) { // look up the handle for the name ::cppu::IPropertyArrayHelper& rPH = getInfoHelper(); sal_Int32 nHandle = rPH.getHandleByName( _rPropertyName ); if ( -1 == nHandle ) throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( _rPropertyName ), static_cast< XPropertyState* >( this ) ); return nHandle; } //-------------------------------------------------------------------- PropertyState SAL_CALL OPropertyStateContainer::getPropertyState( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException) { return getPropertyStateByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- Sequence< PropertyState > SAL_CALL OPropertyStateContainer::getPropertyStates( const Sequence< ::rtl::OUString >& _rPropertyNames ) throw (UnknownPropertyException, RuntimeException) { sal_Int32 nProperties = _rPropertyNames.getLength(); Sequence< PropertyState> aStates( nProperties ); if ( !nProperties ) return aStates; #ifdef _DEBUG // precondition: property sequence is sorted (the algorythm below relies on this) { const ::rtl::OUString* pNames = _rPropertyNames.getConstArray(); const ::rtl::OUString* pNamesCompare = pNames + 1; const ::rtl::OUString* pNamesEnd = _rPropertyNames.getConstArray() + _rPropertyNames.getLength(); for ( ; pNamesCompare != pNamesEnd; ++pNames, ++pNamesCompare ) OSL_PRECOND( pNames->compareTo( *pNamesCompare ) < 0, "OPropertyStateContainer::getPropertyStates: property sequence not sorted!" ); } #endif const ::rtl::OUString* pLookup = _rPropertyNames.getConstArray(); const ::rtl::OUString* pLookupEnd = pLookup + nProperties; PropertyState* pStates = aStates.getArray(); cppu::IPropertyArrayHelper& rHelper = getInfoHelper(); Sequence< Property> aAllProperties = rHelper.getProperties(); sal_Int32 nAllProperties = aAllProperties.getLength(); const Property* pAllProperties = aAllProperties.getConstArray(); const Property* pAllPropertiesEnd = pAllProperties + nAllProperties; osl::MutexGuard aGuard( rBHelper.rMutex ); for ( ; ( pAllProperties != pAllPropertiesEnd ) && ( pLookup != pLookupEnd ); ++pAllProperties ) { #ifdef _DEBUG if ( pAllProperties < pAllPropertiesEnd - 1 ) OSL_ENSURE( pAllProperties->Name.compareTo( (pAllProperties + 1)->Name ) < 0, "OPropertyStateContainer::getPropertyStates: all-properties not sorted!" ); #endif if ( pAllProperties->Name.equals( *pLookup ) ) { *pStates++ = getPropertyState( *pLookup ); ++pLookup; } } if ( pLookup != pLookupEnd ) // we run out of properties from the IPropertyArrayHelper, but still have properties to lookup // -> we were asked for a nonexistent property throw UnknownPropertyException( lcl_getUnknownPropertyErrorMessage( *pLookup ), static_cast< XPropertyState* >( this ) ); return aStates; } //-------------------------------------------------------------------- void SAL_CALL OPropertyStateContainer::setPropertyToDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, RuntimeException) { setPropertyToDefaultByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- Any SAL_CALL OPropertyStateContainer::getPropertyDefault( const ::rtl::OUString& _rPropertyName ) throw (UnknownPropertyException, WrappedTargetException, RuntimeException) { return getPropertyDefaultByHandle( getHandleForName( _rPropertyName ) ); } //-------------------------------------------------------------------- PropertyState OPropertyStateContainer::getPropertyStateByHandle( sal_Int32 _nHandle ) { // simply compare the current and the default value Any aCurrentValue; getFastPropertyValue( aCurrentValue, _nHandle ); Any aDefaultValue = getPropertyDefaultByHandle( _nHandle ); sal_Bool bEqual = uno_type_equalData( const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(), const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(), reinterpret_cast< uno_QueryInterfaceFunc >(cpp_queryInterface), reinterpret_cast< uno_ReleaseFunc >(cpp_release) ); if ( bEqual ) return PropertyState_DEFAULT_VALUE; else return PropertyState_DIRECT_VALUE; } //-------------------------------------------------------------------- void OPropertyStateContainer::setPropertyToDefaultByHandle( sal_Int32 _nHandle ) { setFastPropertyValue( _nHandle, getPropertyDefaultByHandle( _nHandle ) ); } //......................................................................... } // namespace comphelper //......................................................................... #ifdef FS_PRIV_DEBUG #define STATECONTAINER_TEST #endif #ifdef STATECONTAINER_TEST #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; //===================================================================== //= Test - compiler test //===================================================================== typedef ::cppu::OWeakAggObject Test_RefCountBase; class Test :public OMutexAndBroadcastHelper ,public OPropertyStateContainer ,public OPropertyArrayUsageHelper< Test > ,public Test_RefCountBase { private: ::rtl::OUString m_sStringProperty; Reference< XInterface > m_xInterfaceProperty; Any m_aMayBeVoidProperty; protected: Test( ); DECLARE_XINTERFACE( ) public: static Test* Create( ); protected: virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; protected: // OPropertyStateContainer overridables virtual Any getPropertyDefaultByHandle( sal_Int32 _nHandle ) const; }; //--------------------------------------------------------------------- Test::Test( ) :OPropertyStateContainer( GetBroadcastHelper() ) { registerProperty( ::rtl::OUString::createFromAscii( "StringProperty" ), 1, PropertyAttribute::BOUND, &m_sStringProperty, ::getCppuType( &m_sStringProperty ) ); registerProperty( ::rtl::OUString::createFromAscii( "InterfaceProperty" ), 2, PropertyAttribute::BOUND, &m_xInterfaceProperty, ::getCppuType( &m_xInterfaceProperty ) ); registerMayBeVoidProperty( ::rtl::OUString::createFromAscii( "IntProperty" ), 3, PropertyAttribute::BOUND, &m_aMayBeVoidProperty, ::getCppuType( static_cast< sal_Int32* >( NULL ) ) ); registerPropertyNoMember( ::rtl::OUString::createFromAscii( "OtherInterfaceProperty" ), 4, PropertyAttribute::BOUND | PropertyAttribute::MAYBEVOID, ::getCppuType( static_cast< Reference< XInterface >* >( NULL ) ), NULL ); } //--------------------------------------------------------------------- IMPLEMENT_FORWARD_XINTERFACE2( Test, Test_RefCountBase, OPropertyStateContainer ) //--------------------------------------------------------------------- Any Test::getPropertyDefaultByHandle( sal_Int32 _nHandle ) const { Any aDefault; switch ( _nHandle ) { case 1: aDefault = makeAny( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringPropertyDefault" ) ) ); break; case 2: aDefault = makeAny( Reference< XInterface >( ) ); break; case 3: // void break; case 4: aDefault = makeAny( Reference< XInterface >( ) ); break; default: OSL_ENSURE( sal_False, "Test::getPropertyDefaultByHandle: invalid handle!" ); } return aDefault; } //--------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL Test::getPropertySetInfo( ) throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ); } //--------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& SAL_CALL Test::getInfoHelper() { return *getArrayHelper(); } //--------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* Test::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties( aProps ); return new ::cppu::OPropertyArrayHelper( aProps ); } //--------------------------------------------------------------------- Test* Test::Create( ) { Test* pInstance = new Test; return pInstance; } //......................................................................... } // namespace comphelper //......................................................................... #endif <|endoftext|>
<commit_before>#include <Eigen/Core> #include <iostream> #include "writer.hpp" #include <cmath> #include <stdexcept> #include <functional> //----------------GodunovBegin---------------- /// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[out] u solution at time T /// @param[out] X Grid Points void Godunov(int N, double T, const std::function<double(double)>& f, const std::function<double(double)>& df, const std::function<double(double)>& u0, Eigen::VectorXd& u, Eigen::VectorXd& X) { // Create space discretization for interval [-2,2] // (write your solution here) // The Godunov flux // (write your solution here) //setup vectors to store (old) solution // (write your solution here) // choose dt such that if obeys CFL condition // (write your solution here) double t = 0; //Please uncomment the next line: // while( t <= T){ // Update dT according to current CFL condition // (write your solution here) // Update current time // (write your solution here) // Update the internal values of u // (write your solution here) // Update boundary with non-reflecting Neumann bc // (write your solution here) //Please uncomment the next line: //} } //----------------GodunovEnd---------------- //----------------convGodBegin---------------- //! Computes error for a range of cell lengths and stores them to error vectors /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[in] uex exact solution /// @param[in] baseName string containing name to save the computed errors and resolution void GodunovConvergence( double T, const std::function<double(double)>& f, const std::function<double(double)>& df, const std::function<double(double)>& u0, const std::function<double(double, double)>& uex, const std::string& baseName) { std::vector<int> resolutions = {100, 200, 400, 800, 1600}; std::vector<double> L1_errors; std::vector<double> Linf_errors; for (auto& N: resolutions) { // find approximate solution using Godunov scheme // (write your solution here) // compute errors and push them bach to the corresponfing error vectors // (write your solution here) } writeToFile(baseName + "_L1errors_Godunov.txt", L1_errors); writeToFile(baseName + "_Linferrors_Godunov.txt", Linf_errors); writeToFile(baseName + "_resolutions.txt", resolutions); } //----------------convGodEnd---------------- //----------------LFBegin---------------- /// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[out] u solution at time T /// @param[out] X Grid Points void LaxFriedrichs(int N, double T, const std::function<double(double)>& f, const std::function<double(double)>& df, const std::function<double(double)>& u0, Eigen::VectorXd& u, Eigen::VectorXd& X) { // Create space discretization for interval [-2,2] // (write your solution here) double CFL = 0.5; //setup vectors to store solution // (write your solution here) // choose dt such that if obeys CFL condition // (write your solution here) double t = 0; // The Lax-Friedrichs flux // (write your solution here) //Please uncomment the next line: //while( t <= T){ // Update dT according to current CFL condition // (write your solution here) // Update current time // (write your solution here) // Update the internal values of u // (write your solution here) // Update boundary with non-reflecting Neumann bc // (write your solution here) //Please uncomment the next line: //} } //----------------LFEnd---------------- //----------------convLFBegin---------------- //! Computes error for a range of cell lengths and stores them to error vectors /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[in] uex exact solution /// @param[in] baseName string containing name to save the computed errors and resolution void LFConvergence( double T, const std::function<double(double)>& f, const std::function<double(double)>& df, const std::function<double(double)>& u0, const std::function<double(double, double)>& uex, const std::string& baseName) { std::vector<int> resolutions = {100, 200, 400, 800, 1600}; std::vector<double> L1_errors; std::vector<double> Linf_errors; for (auto& N: resolutions) { // find approximate solution using Lax-Friedrichs scheme // (write your solution here) // compute errors and push them bach to the corresponfing error vectors // (write your solution here) } writeToFile(baseName + "_L1errors_LF.txt", L1_errors); writeToFile(baseName + "_Linferrors_LF.txt", Linf_errors); writeToFile(baseName + "_resolutions.txt", resolutions); } //----------------convLFEnd---------------- /* Fluxes for Burgers' equation */ double fBurgers(double u) { return std::pow(u,2)/2.; } double dfBurgers(double u) { return u; } /* Initial data and exact solutions for Burgers' equation */ // i) double U0i(double x) { if(x<0.) return 1.; else return 0.; } double Uexi(double x, double t) { if(x<0.5*t) return 1.; else return 0.; } // ii) double U0ii(double x) { if(x<0.) return 0.; else return -2.; } double Uexii(double x, double t) { if(x<-t) return 0.; else return -2.; } // iii) double U0iii(double x) { if(x<0.) return 0.; else return 1.; } double Uexiii(double x, double t) { if(x<0) return 0.; else if(x<t && t<2) return x/t; else return 1.; } // iv) double U0iv(double x) { if(0.<x && x<1.) return 1.; else return 0.; } double Uexiv(double x, double t) { if(x<=0) return 0.; else if((x<=t && t<=2) || (x<std::sqrt(2*t) && t>2)) return x/t; else if( t<=2 && t<x && (x<1+t/2.)) return 1.; else return 0.; } /* Flux for Buckley-Leverett equation*/ double fBL(double u) { return std::pow(u,2)/(std::pow(u,2) + std::pow(1-u,2)); } double dfBL(double u) { return (2*u*(u*u+(1-u)*(1-u)) - u*u*(2*u-2*(1-u)) )/ std::pow(u*u + (1-u)*(1-u),2); } /* Initial data for Buckley-Leverett */ double U0BL(double x) { if(x<0.) return 0.1; else return 0.9; } int main(int, char**) { double T = 0.8; int N=100; Eigen::VectorXd u,X; // Test for Burgers with initiald data i Godunov(N, T, fBurgers, dfBurgers, U0i, u, X); writeToFile("uBi_G.txt", u); LaxFriedrichs(N, T, fBurgers, dfBurgers, U0i, u, X); writeToFile("uBi_LF.txt", u); // compute convergence for Burgers with initial data i GodunovConvergence(T, fBurgers, dfBurgers, U0i, Uexi, "Burgers1"); LFConvergence(T, fBurgers, dfBurgers, U0i, Uexi, "Burgers1"); // compute convergence for Burgers with initial data ii GodunovConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, "Burgers2"); LFConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, "Burgers2"); // compute convergence for Burgers with initial data iii GodunovConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, "Burgers3"); LFConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, "Burgers3"); // compute convergence for Burgers with initial data iv GodunovConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, "Burgers4"); LFConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, "Burgers4"); // Test for Buckley-Leverett Godunov(N, T, fBL, dfBL, U0BL, u,X); writeToFile("uBL_G.txt", u); LaxFriedrichs(N, T, fBL, dfBL, U0BL, u, X); writeToFile("uBL_LF.txt", u); } <commit_msg>Clang format Series 5 part 1.<commit_after>#include "writer.hpp" #include <Eigen/Core> #include <cmath> #include <functional> #include <iostream> #include <stdexcept> //----------------GodunovBegin---------------- /// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[out] u solution at time T /// @param[out] X Grid Points void Godunov(int N, double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, Eigen::VectorXd &u, Eigen::VectorXd &X) { // Create space discretization for interval [-2,2] // (write your solution here) // The Godunov flux // (write your solution here) //setup vectors to store (old) solution // (write your solution here) // choose dt such that if obeys CFL condition // (write your solution here) double t = 0; //Please uncomment the next line: // while( t <= T){ // Update dT according to current CFL condition // (write your solution here) // Update current time // (write your solution here) // Update the internal values of u // (write your solution here) // Update boundary with non-reflecting Neumann bc // (write your solution here) //Please uncomment the next line: //} } //----------------GodunovEnd---------------- //----------------convGodBegin---------------- //! Computes error for a range of cell lengths and stores them to error vectors /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[in] uex exact solution /// @param[in] baseName string containing name to save the computed errors and resolution void GodunovConvergence(double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, const std::function<double(double, double)> &uex, const std::string &baseName) { std::vector<int> resolutions = {100, 200, 400, 800, 1600}; std::vector<double> L1_errors; std::vector<double> Linf_errors; for (auto &N : resolutions) { // find approximate solution using Godunov scheme // (write your solution here) // compute errors and push them bach to the corresponfing error vectors // (write your solution here) } writeToFile(baseName + "_L1errors_Godunov.txt", L1_errors); writeToFile(baseName + "_Linferrors_Godunov.txt", Linf_errors); writeToFile(baseName + "_resolutions.txt", resolutions); } //----------------convGodEnd---------------- //----------------LFBegin---------------- /// @param[in] N the number of grid points, NOT INCLUDING BOUNDARY POINTS /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[out] u solution at time T /// @param[out] X Grid Points void LaxFriedrichs(int N, double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, Eigen::VectorXd &u, Eigen::VectorXd &X) { // Create space discretization for interval [-2,2] // (write your solution here) double CFL = 0.5; //setup vectors to store solution // (write your solution here) // choose dt such that if obeys CFL condition // (write your solution here) double t = 0; // The Lax-Friedrichs flux // (write your solution here) //Please uncomment the next line: //while( t <= T){ // Update dT according to current CFL condition // (write your solution here) // Update current time // (write your solution here) // Update the internal values of u // (write your solution here) // Update boundary with non-reflecting Neumann bc // (write your solution here) //Please uncomment the next line: //} } //----------------LFEnd---------------- //----------------convLFBegin---------------- //! Computes error for a range of cell lengths and stores them to error vectors /// @param[in] T the final time at which to compute the solution /// @param[in] f flux function, as function /// @param[in] df derivative of flux function, as function /// @param[in] u0 the initial conditions, as function /// @param[in] uex exact solution /// @param[in] baseName string containing name to save the computed errors and resolution void LFConvergence(double T, const std::function<double(double)> &f, const std::function<double(double)> &df, const std::function<double(double)> &u0, const std::function<double(double, double)> &uex, const std::string &baseName) { std::vector<int> resolutions = {100, 200, 400, 800, 1600}; std::vector<double> L1_errors; std::vector<double> Linf_errors; for (auto &N : resolutions) { // find approximate solution using Lax-Friedrichs scheme // (write your solution here) // compute errors and push them bach to the corresponfing error vectors // (write your solution here) } writeToFile(baseName + "_L1errors_LF.txt", L1_errors); writeToFile(baseName + "_Linferrors_LF.txt", Linf_errors); writeToFile(baseName + "_resolutions.txt", resolutions); } //----------------convLFEnd---------------- /* Fluxes for Burgers' equation */ double fBurgers(double u) { return std::pow(u, 2) / 2.; } double dfBurgers(double u) { return u; } /* Initial data and exact solutions for Burgers' equation */ // i) double U0i(double x) { if (x < 0.) return 1.; else return 0.; } double Uexi(double x, double t) { if (x < 0.5 * t) return 1.; else return 0.; } // ii) double U0ii(double x) { if (x < 0.) return 0.; else return -2.; } double Uexii(double x, double t) { if (x < -t) return 0.; else return -2.; } // iii) double U0iii(double x) { if (x < 0.) return 0.; else return 1.; } double Uexiii(double x, double t) { if (x < 0) return 0.; else if (x < t && t < 2) return x / t; else return 1.; } // iv) double U0iv(double x) { if (0. < x && x < 1.) return 1.; else return 0.; } double Uexiv(double x, double t) { if (x <= 0) return 0.; else if ((x <= t && t <= 2) || (x < std::sqrt(2 * t) && t > 2)) return x / t; else if (t <= 2 && t < x && (x < 1 + t / 2.)) return 1.; else return 0.; } /* Flux for Buckley-Leverett equation*/ double fBL(double u) { return std::pow(u, 2) / (std::pow(u, 2) + std::pow(1 - u, 2)); } double dfBL(double u) { return (2 * u * (u * u + (1 - u) * (1 - u)) - u * u * (2 * u - 2 * (1 - u))) / std::pow(u * u + (1 - u) * (1 - u), 2); } /* Initial data for Buckley-Leverett */ double U0BL(double x) { if (x < 0.) return 0.1; else return 0.9; } int main(int, char **) { double T = 0.8; int N = 100; Eigen::VectorXd u, X; // Test for Burgers with initiald data i Godunov(N, T, fBurgers, dfBurgers, U0i, u, X); writeToFile("uBi_G.txt", u); LaxFriedrichs(N, T, fBurgers, dfBurgers, U0i, u, X); writeToFile("uBi_LF.txt", u); // compute convergence for Burgers with initial data i GodunovConvergence(T, fBurgers, dfBurgers, U0i, Uexi, "Burgers1"); LFConvergence(T, fBurgers, dfBurgers, U0i, Uexi, "Burgers1"); // compute convergence for Burgers with initial data ii GodunovConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, "Burgers2"); LFConvergence(T, fBurgers, dfBurgers, U0ii, Uexii, "Burgers2"); // compute convergence for Burgers with initial data iii GodunovConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, "Burgers3"); LFConvergence(T, fBurgers, dfBurgers, U0iii, Uexiii, "Burgers3"); // compute convergence for Burgers with initial data iv GodunovConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, "Burgers4"); LFConvergence(T, fBurgers, dfBurgers, U0iv, Uexiv, "Burgers4"); // Test for Buckley-Leverett Godunov(N, T, fBL, dfBL, U0BL, u, X); writeToFile("uBL_G.txt", u); LaxFriedrichs(N, T, fBL, dfBL, U0BL, u, X); writeToFile("uBL_LF.txt", u); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id$ * */ #ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #include <pcl/point_types.h> namespace pcl { namespace common { template<> struct IntensityFieldAccessor<pcl::PointNormal> { inline float operator () (const pcl::PointNormal &p) const { return (p.curvature); } inline void get (const pcl::PointNormal &p, float &intensity) const { intensity = p.curvature; } inline void set (pcl::PointNormal &p, float intensity) const { p.curvature = intensity; } inline void demean (pcl::PointNormal& p, float value) const { p.curvature -= value; } inline void add (pcl::PointNormal& p, float value) const { p.curvature += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZ> { inline float operator () (const pcl::PointXYZ &p) const { return (p.z); } inline void get (const pcl::PointXYZ &p, float &intensity) const { intensity = p.z; } inline void set (pcl::PointXYZ &p, float intensity) const { p.z = intensity; } inline void demean (pcl::PointXYZ& p, float value) const { p.z -= value; } inline void add (pcl::PointXYZ& p, float value) const { p.z += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGB> { inline float operator () (const pcl::PointXYZRGB &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGB &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGB &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBA> { inline float operator () (const pcl::PointXYZRGBA &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBA &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBA &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBL> { inline float operator () (const pcl::PointXYZRGBL &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBL &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBL &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; } } #endif <commit_msg>added specialization for XYZRGBNormal<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id$ * */ #ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP #include <pcl/point_types.h> namespace pcl { namespace common { template<> struct IntensityFieldAccessor<pcl::PointNormal> { inline float operator () (const pcl::PointNormal &p) const { return (p.curvature); } inline void get (const pcl::PointNormal &p, float &intensity) const { intensity = p.curvature; } inline void set (pcl::PointNormal &p, float intensity) const { p.curvature = intensity; } inline void demean (pcl::PointNormal& p, float value) const { p.curvature -= value; } inline void add (pcl::PointNormal& p, float value) const { p.curvature += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZ> { inline float operator () (const pcl::PointXYZ &p) const { return (p.z); } inline void get (const pcl::PointXYZ &p, float &intensity) const { intensity = p.z; } inline void set (pcl::PointXYZ &p, float intensity) const { p.z = intensity; } inline void demean (pcl::PointXYZ& p, float value) const { p.z -= value; } inline void add (pcl::PointXYZ& p, float value) const { p.z += value; } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGB> { inline float operator () (const pcl::PointXYZRGB &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGB &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGB &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGB& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBA> { inline float operator () (const pcl::PointXYZRGBA &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBA &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBA &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBA& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBNormal> { inline float operator () (const pcl::PointXYZRGBNormal &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBNormal &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBNormal &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBNormal &p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBNormal &p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; template<> struct IntensityFieldAccessor<pcl::PointXYZRGBL> { inline float operator () (const pcl::PointXYZRGBL &p) const { return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f); } inline void get (const pcl::PointXYZRGBL &p, float& intensity) const { intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f; } inline void set (pcl::PointXYZRGBL &p, float intensity) const { p.r = static_cast<uint8_t> (1000 * intensity / 299); p.g = static_cast<uint8_t> (1000 * intensity / 587); p.b = static_cast<uint8_t> (1000 * intensity / 114); } inline void demean (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity -= value; set (p, intensity); } inline void add (pcl::PointXYZRGBL& p, float value) const { float intensity = this->operator () (p); intensity += value; set (p, intensity); } }; } } #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkSingleton.h" namespace { // This ensures that m_GlobalSingletonIndex has been initialized once the library // has been loaded. In some cases, this call will perform the initialization. // In other cases, static initializers like the IO factory initialization code // will have done the initialization. ::itk::SingletonIndex * initializedGlobalSingletonIndex = ::itk::SingletonIndex::GetInstance(); /** \class GlobalSingletonIndexInitializer * * \brief Initialize a GlobalSingletonIndex and delete it on program * completion. * */ class GlobalSingletonIndexInitializer { public: using Self = GlobalSingletonIndexInitializer; using SingletonIndex = ::itk::SingletonIndex; GlobalSingletonIndexInitializer() = default; /** Delete the time stamp if it was created. */ ~GlobalSingletonIndexInitializer() { delete m_GlobalSingletonIndex; m_GlobalSingletonIndex = nullptr; } /** Create the GlobalSingletonIndex if needed and return it. */ static SingletonIndex * GetGlobalSingletonIndex() { if (m_GlobalSingletonIndex == nullptr) { m_GlobalSingletonIndex = new SingletonIndex; // To avoid being optimized out. The compiler does not like this // statement at a higher scope. Unused(initializedGlobalSingletonIndex); } return m_GlobalSingletonIndex; } private: static SingletonIndex * m_GlobalSingletonIndex; }; // Takes care of cleaning up the GlobalSingletonIndex static GlobalSingletonIndexInitializer GlobalSingletonIndexInitializerInstance; // Initialized by the compiler to zero GlobalSingletonIndexInitializer::SingletonIndex * GlobalSingletonIndexInitializer::m_GlobalSingletonIndex; } // end anonymous namespace // may return NULL if string is not registered already // // access something like a std::map<std::string, void *> or // registered globals, it may be possible to restrict the held // classes to be derived from itk::LightObject, so dynamic cast can // work, and could use some type of Holder<T> class for intrinsic types namespace itk { void * SingletonIndex::GetGlobalInstancePrivate(const char * globalName) { SingletonData::iterator it; it = m_GlobalObjects.find(globalName); if (it == m_GlobalObjects.end()) { return nullptr; } return std::get<0>(it->second); } // If globalName is already registered remove it from map, // otherwise global is added to the singleton index under globalName bool SingletonIndex::SetGlobalInstancePrivate(const char * globalName, void * global, std::function<void(void *)> func, std::function<void(void)> deleteFunc) { m_GlobalObjects.erase(globalName); m_GlobalObjects.insert(std::make_pair(globalName, std::make_tuple(global, func, deleteFunc))); return true; } SingletonIndex * SingletonIndex::GetInstance() { if (m_Instance == nullptr) { m_Instance = GlobalSingletonIndexInitializer::GetGlobalSingletonIndex(); } return m_Instance; } void SingletonIndex::SetInstance(Self * instance) { m_Instance = instance; } SingletonIndex::~SingletonIndex() { for (auto & pair : m_GlobalObjects) { std::get<2>(pair.second)(); } } SingletonIndex::Self * SingletonIndex::m_Instance; } // end namespace itk <commit_msg>ENH: Use std::once_flag for GlobalSingletonIndexInitializer<commit_after>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkSingleton.h" #include <mutex> namespace { std::once_flag globalSingletonOnceFlag; // This ensures that m_GlobalSingletonIndex has been initialized once the library // has been loaded. In some cases, this call will perform the initialization. // In other cases, static initializers like the IO factory initialization code // will have done the initialization. ::itk::SingletonIndex * initializedGlobalSingletonIndex = ::itk::SingletonIndex::GetInstance(); /** \class GlobalSingletonIndexInitializer * * \brief Initialize a GlobalSingletonIndex and delete it on program * completion. * */ class GlobalSingletonIndexInitializer { public: using Self = GlobalSingletonIndexInitializer; using SingletonIndex = ::itk::SingletonIndex; GlobalSingletonIndexInitializer() = default; /** Delete the time stamp if it was created. */ ~GlobalSingletonIndexInitializer() { delete m_GlobalSingletonIndex; m_GlobalSingletonIndex = nullptr; } /** Create the GlobalSingletonIndex if needed and return it. */ static SingletonIndex * GetGlobalSingletonIndex() { std::call_once(globalSingletonOnceFlag, []() { m_GlobalSingletonIndex = new SingletonIndex; // To avoid being optimized out. The compiler does not like this // statement at a higher scope. Unused(initializedGlobalSingletonIndex); }); return m_GlobalSingletonIndex; } private: static SingletonIndex * m_GlobalSingletonIndex; }; // Takes care of cleaning up the GlobalSingletonIndex static GlobalSingletonIndexInitializer GlobalSingletonIndexInitializerInstance; // Initialized by the compiler to zero GlobalSingletonIndexInitializer::SingletonIndex * GlobalSingletonIndexInitializer::m_GlobalSingletonIndex; } // end anonymous namespace // may return NULL if string is not registered already // // access something like a std::map<std::string, void *> or // registered globals, it may be possible to restrict the held // classes to be derived from itk::LightObject, so dynamic cast can // work, and could use some type of Holder<T> class for intrinsic types namespace itk { void * SingletonIndex::GetGlobalInstancePrivate(const char * globalName) { SingletonData::iterator it; it = m_GlobalObjects.find(globalName); if (it == m_GlobalObjects.end()) { return nullptr; } return std::get<0>(it->second); } // If globalName is already registered remove it from map, // otherwise global is added to the singleton index under globalName bool SingletonIndex::SetGlobalInstancePrivate(const char * globalName, void * global, std::function<void(void *)> func, std::function<void(void)> deleteFunc) { m_GlobalObjects.erase(globalName); m_GlobalObjects.insert(std::make_pair(globalName, std::make_tuple(global, func, deleteFunc))); return true; } SingletonIndex * SingletonIndex::GetInstance() { if (m_Instance == nullptr) { m_Instance = GlobalSingletonIndexInitializer::GetGlobalSingletonIndex(); } return m_Instance; } void SingletonIndex::SetInstance(Self * instance) { m_Instance = instance; } SingletonIndex::~SingletonIndex() { for (auto & pair : m_GlobalObjects) { std::get<2>(pair.second)(); } } SingletonIndex::Self * SingletonIndex::m_Instance; } // end namespace itk <|endoftext|>
<commit_before>/* * Copyright 2004-2015 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "resolveIntents.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "type.h" #include "stlUtil.h" static Type* getWrapRecordBaseType(Type* type); // // removes _array and _domain wrapper records // void removeWrapRecords() { // // do not remove wrap records if dead code elimination is disabled // (or weakened because inlining or copy propagation is disabled) // because code associated with accesses to the removed // _valueType field will remain // if (fNoDeadCodeElimination || fNoInline || fNoCopyPropagation) return; // // replace use of _valueType field with type // forv_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive(PRIM_GET_PRIV_CLASS)) { SET_LINENO(call); call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol)); } } // // remove defs of _valueType field // forv_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive(PRIM_SET_MEMBER) || call->isPrimitive(PRIM_GET_MEMBER) || call->isPrimitive(PRIM_GET_MEMBER_VALUE)) { if (SymExpr* se = toSymExpr(call->get(2))) { if (!strcmp(se->var->name, "_valueType")) { se->getStmtExpr()->remove(); } } } } // // remove _valueType fields // forv_Vec(AggregateType, ct, gAggregateTypes) { for_fields(field, ct) { if (!strcmp(field->name, "_valueType")) field->defPoint->remove(); } } // // Remove actuals bound to _valueType formals. // compute_call_sites(); forv_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { if (!strcmp(formal->name, "_valueType")) { forv_Vec(CallExpr, call, *fn->calledBy) { formal_to_actual(call, formal)->remove(); } } } } // // Remove all uses of _valueType formals, and then the formal itself. // // We need to complete the above action on all functions/formals first, // before proceeding to the following loop. Otherwise in the following // scenario: // // proc fun1(..., _valueType) { // ... // tmp = fun2(..., _valueType); <-- need to preserve this call. // ... // } // // Suppose we process fun1() before fun2(). In that case, the code below // would remove the indicated call because _valueType still appears as an // argument. Most likely, that call is a call to the compiler-generated // default constructor for a record-wrapped type. It needs to be preserved // in its reduced form, e.g. _construct_array(_value). If the call is // removed entirely, then the array tmp is never initialized, and the program // computes garbage. // In this revised formulation, all _valueType formals and their // corresponding actual arguments are removed first. Then, the call to // fun2() no longer contains a reference to the _valueType argument of // fun1(), so it is preserved as desired. // forv_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { if (!strcmp(formal->name, "_valueType")) { // Remove all uses of _valueType within the body of this function. std::vector<SymExpr*> symExprs; collectSymExprs(fn->body, symExprs); for_vector(SymExpr, se, symExprs) { // Ignore dead ones. if (se->parentSymbol == NULL) continue; // Weed out all but the formal we're interested in. if (se->var != formal) continue; // OK, remove the entire statement accessing the _valueType formal. Expr* stmt = se->getStmtExpr(); stmt->remove(); } formal->defPoint->remove(); } } } // // replace accesses of _value with wrap record // forv_Vec(CallExpr, call, gCallExprs) { if (call->parentSymbol == NULL) continue; if (call->isPrimitive(PRIM_SET_MEMBER)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->primitive = primitives[PRIM_MOVE]; call->get(2)->remove(); } } } else if (call->isPrimitive(PRIM_GET_MEMBER)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->primitive = primitives[PRIM_ADDR_OF]; call->get(2)->remove(); } } } else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->replace(se->remove()); } if (se->var->type->symbol->hasFlag(FLAG_REF)) { Type* vt = se->getValType(); if (isRecordWrappedType(vt)) { SET_LINENO(call); call->replace(new CallExpr(PRIM_DEREF, se->remove())); } } } } } // // scalar replace wrap records // forv_Vec(VarSymbol, var, gVarSymbols) { if (Type* type = getWrapRecordBaseType(var->type)) if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF)) { var->type = type; // // record-wrapped arrays should be local fields // TODO: Domains don't work generally due to some case in Sparse. // What about dist classes? // if (TypeSymbol* ts = toTypeSymbol(var->defPoint->parentSymbol)) { if (!(ts->hasFlag(FLAG_REF) || ts->hasFlag(FLAG_RUNTIME_TYPE_VALUE) || ts->hasEitherFlag(FLAG_TUPLE, FLAG_STAR_TUPLE) || ts->hasEitherFlag(FLAG_ITERATOR_CLASS, FLAG_ITERATOR_RECORD) || ts->hasFlag(FLAG_HEAP))) { const char* bundlePrefix = "_class_locals"; if (strncmp(ts->name, bundlePrefix, strlen(bundlePrefix))) { if (isArrayClass(type)) { var->addFlag(FLAG_LOCAL_FIELD); } } } } } } forv_Vec(ArgSymbol, arg, gArgSymbols) { if (Type* type = getWrapRecordBaseType(arg->type)) { arg->intent = blankIntentForType(type); // see test/arrays/deitz/part7/test_out_array arg->type = type; } } forv_Vec(FnSymbol, fn, gFnSymbols) { if (Type* type = getWrapRecordBaseType(fn->retType)) fn->retType = type; } // // fix array element type for arrays of arrays and arrays of domains // forv_Vec(AggregateType, ct, gAggregateTypes) { if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) { if (TypeSymbol* ts = getDataClassType(ct->symbol)) { if (isRecordWrappedType(ts->typeInfo())) { setDataClassType(ct->symbol, ts->type->getField("_value")->type->symbol); } } } } } static Type* getWrapRecordBaseType(Type* type) { if (isRecordWrappedType(type)) { return type->getField("_value")->type; } else if (type->symbol->hasFlag(FLAG_REF)) { Type* vt = type->getValType(); if (isRecordWrappedType(vt)) { return vt->getField("_value")->type->refType; } } return NULL; } <commit_msg>Allow removeWrapRecords to operate when --no-inline or --no-copy-propagation is tossed.<commit_after>/* * Copyright 2004-2015 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "resolveIntents.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "type.h" #include "stlUtil.h" static Type* getWrapRecordBaseType(Type* type); // // removes _array and _domain wrapper records // void removeWrapRecords() { // // do not remove wrap records if dead code elimination is disabled // (or weakened because inlining or copy propagation is disabled) // because code associated with accesses to the removed // _valueType field will remain // // I think the above comment no longer applies after PR#1387. if (fNoDeadCodeElimination) // || fNoInline || fNoCopyPropagation) return; // // replace use of _valueType field with type // forv_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive(PRIM_GET_PRIV_CLASS)) { SET_LINENO(call); call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol)); } } // // remove defs of _valueType field // forv_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive(PRIM_SET_MEMBER) || call->isPrimitive(PRIM_GET_MEMBER) || call->isPrimitive(PRIM_GET_MEMBER_VALUE)) { if (SymExpr* se = toSymExpr(call->get(2))) { if (!strcmp(se->var->name, "_valueType")) { se->getStmtExpr()->remove(); } } } } // // remove _valueType fields // forv_Vec(AggregateType, ct, gAggregateTypes) { for_fields(field, ct) { if (!strcmp(field->name, "_valueType")) field->defPoint->remove(); } } // // Remove actuals bound to _valueType formals. // compute_call_sites(); forv_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { if (!strcmp(formal->name, "_valueType")) { forv_Vec(CallExpr, call, *fn->calledBy) { formal_to_actual(call, formal)->remove(); } } } } // // Remove all uses of _valueType formals, and then the formal itself. // // We need to complete the above action on all functions/formals first, // before proceeding to the following loop. Otherwise in the following // scenario: // // proc fun1(..., _valueType) { // ... // tmp = fun2(..., _valueType); <-- need to preserve this call. // ... // } // // Suppose we process fun1() before fun2(). In that case, the code below // would remove the indicated call because _valueType still appears as an // argument. Most likely, that call is a call to the compiler-generated // default constructor for a record-wrapped type. It needs to be preserved // in its reduced form, e.g. _construct_array(_value). If the call is // removed entirely, then the array tmp is never initialized, and the program // computes garbage. // In this revised formulation, all _valueType formals and their // corresponding actual arguments are removed first. Then, the call to // fun2() no longer contains a reference to the _valueType argument of // fun1(), so it is preserved as desired. // forv_Vec(FnSymbol, fn, gFnSymbols) { for_formals(formal, fn) { if (!strcmp(formal->name, "_valueType")) { // Remove all uses of _valueType within the body of this function. std::vector<SymExpr*> symExprs; collectSymExprs(fn->body, symExprs); for_vector(SymExpr, se, symExprs) { // Ignore dead ones. if (se->parentSymbol == NULL) continue; // Weed out all but the formal we're interested in. if (se->var != formal) continue; // OK, remove the entire statement accessing the _valueType formal. Expr* stmt = se->getStmtExpr(); stmt->remove(); } formal->defPoint->remove(); } } } // // replace accesses of _value with wrap record // forv_Vec(CallExpr, call, gCallExprs) { if (call->parentSymbol == NULL) continue; if (call->isPrimitive(PRIM_SET_MEMBER)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->primitive = primitives[PRIM_MOVE]; call->get(2)->remove(); } } } else if (call->isPrimitive(PRIM_GET_MEMBER)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->primitive = primitives[PRIM_ADDR_OF]; call->get(2)->remove(); } } } else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE)) { if (SymExpr* se = toSymExpr(call->get(1))) { if (isRecordWrappedType(se->var->type)) { call->replace(se->remove()); } if (se->var->type->symbol->hasFlag(FLAG_REF)) { Type* vt = se->getValType(); if (isRecordWrappedType(vt)) { SET_LINENO(call); call->replace(new CallExpr(PRIM_DEREF, se->remove())); } } } } } // // scalar replace wrap records // forv_Vec(VarSymbol, var, gVarSymbols) { if (Type* type = getWrapRecordBaseType(var->type)) if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF)) { var->type = type; // // record-wrapped arrays should be local fields // TODO: Domains don't work generally due to some case in Sparse. // What about dist classes? // if (TypeSymbol* ts = toTypeSymbol(var->defPoint->parentSymbol)) { if (!(ts->hasFlag(FLAG_REF) || ts->hasFlag(FLAG_RUNTIME_TYPE_VALUE) || ts->hasEitherFlag(FLAG_TUPLE, FLAG_STAR_TUPLE) || ts->hasEitherFlag(FLAG_ITERATOR_CLASS, FLAG_ITERATOR_RECORD) || ts->hasFlag(FLAG_HEAP))) { const char* bundlePrefix = "_class_locals"; if (strncmp(ts->name, bundlePrefix, strlen(bundlePrefix))) { if (isArrayClass(type)) { var->addFlag(FLAG_LOCAL_FIELD); } } } } } } forv_Vec(ArgSymbol, arg, gArgSymbols) { if (Type* type = getWrapRecordBaseType(arg->type)) { arg->intent = blankIntentForType(type); // see test/arrays/deitz/part7/test_out_array arg->type = type; } } forv_Vec(FnSymbol, fn, gFnSymbols) { if (Type* type = getWrapRecordBaseType(fn->retType)) fn->retType = type; } // // fix array element type for arrays of arrays and arrays of domains // forv_Vec(AggregateType, ct, gAggregateTypes) { if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) { if (TypeSymbol* ts = getDataClassType(ct->symbol)) { if (isRecordWrappedType(ts->typeInfo())) { setDataClassType(ct->symbol, ts->type->getField("_value")->type->symbol); } } } } } static Type* getWrapRecordBaseType(Type* type) { if (isRecordWrappedType(type)) { return type->getField("_value")->type; } else if (type->symbol->hasFlag(FLAG_REF)) { Type* vt = type->getValType(); if (isRecordWrappedType(vt)) { return vt->getField("_value")->type->refType; } } return NULL; } <|endoftext|>
<commit_before>/*==LICENSE== This file is part of Musec. Copyright (C) 2013 Florian Meißner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ==LICENSE==*/ #include "Musec.h" #include <QtGui> #include <QMediaMetaData> #include <QMediaPlayer> #include <QFileDialog> #define POINTS_TITLE 3 #define POINTS_ARTIST 1 #define POINTS_ALBUM 2 #define TIME_EASY 5 #define TIME_MEDIUM 3 #define TIME_HARD 1 #define MULTIPLIER_EASY 1 #define MULTIPLIER_MEDIUM 2 #define MULTIPLIER_HARD 5 Musec::Musec(QMainWindow* parent) : QMainWindow(parent) { setupUi(this); setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint); fPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency); fTimer = new QTimer(this); fTimer->setSingleShot(true); fDir = QDir::homePath(); fScore = 0; fSongsPlayed = 0; fIsActive = false; fExtensions << "*.mp3" << "*.m4a"; // These should contain meta data connect(fTimer, &QTimer::timeout, this, &Musec::timeout); connect(fPlayer, &QMediaPlayer::durationChanged, this, &Musec::durationChanged); connect(slDifficulty, &QSlider::valueChanged, this, &Musec::difficultyChanged); qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } void Musec::shuffleList() { // Shuffle song list for (int i = fSongs.size() - 1; i >= 0; i--) { int random = qrand() % fSongs.size(); QString str = fSongs[i]; fSongs[i] = fSongs[random]; fSongs[random] = str; } // Load first song loadSong(fSongs.first()); } void Musec::loadSong(const QString& filename) { fStartTime = 0; fPlayer->setMedia(QUrl::fromLocalFile(filename)); updateMultiplier(); statusbar->showMessage(tr("Played: %1 (%2 in queue)").arg( QString::number(fSongsPlayed)).arg(QString::number(fSongs.size()))); } void Musec::playSong() { statusbar->showMessage(QTime(0,0,0).addSecs(fStartTime).toString("mm:ss")); fPlayer->setPosition(fStartTime * 1000); fPlayer->play(); fTimer->start(); } void Musec::evaluate() { QString title = fPlayer->metaData(QMediaMetaData::Title).toString(); QString artist = fPlayer->metaData(QMediaMetaData::Author).toString(); QString album = fPlayer->metaData(QMediaMetaData::AlbumTitle).toString(); quint32 score = 0; if (match(edTitle->text(), title) || title.isEmpty()) { score += POINTS_TITLE; chkTitle->setChecked(true); } if (match(edArtist->text(), artist) || artist.isEmpty()) { score += POINTS_ARTIST; chkArtist->setChecked(true); } if (match(edAlbum->text(), album) || album.isEmpty()) { score += POINTS_ALBUM; chkAlbum->setChecked(true); } score = score * fMultiplier + 0.5f; fScore += score; edTitle->setText(title); edArtist->setText(artist); edAlbum->setText(album); fSongsPlayed++; lblScore->setText(tr("Score: %1").arg(QString::number(fScore))); float avg = fScore/fSongsPlayed; lblAverage->setText(tr("Average: %1").arg(QString::number(avg, 'f', 2))); lblLast->setText(tr("Last Score: %1").arg(QString::number(score))); } bool Musec::match(QString str1, QString str2) { // Cast to lower case str1 = str1.toLower(); str2 = str2.toLower(); // Remove (..., [... and non-alphabetic characters QRegularExpression regex("(\\(.*\\)?)|(\\[.*\\]?)|[^a-zA-Z]"); str1.remove(regex); str2.remove(regex); // Exact match if (str1 == str2) return true; // Allow one mistake every 5 letters int tolerance = str1.length()/5; int i = 0, j = 0, diff = 0, mismatches = 0; while (i < str1.length() && j < str2.length()) { if (str1.at(i) == str2.at(j)) { diff = i - j; i++; j++; } else { if (diff == i - j) { mismatches++; diff--; i++; } else { j++; } } } mismatches += str1.length() - i; mismatches += str2.length() - j; if (mismatches <= tolerance) return true; return false; } void Musec::updateMultiplier() { // Multiplier for number of songs in queue fMultiplier = 1 + fSongs.size()/200; // Multiplier for difficulty switch (slDifficulty->value()) { case 3: fMultiplier *= MULTIPLIER_EASY; fTimer->setInterval(TIME_EASY * 1000); lblDifficulty->setText(QString::number(TIME_EASY) + "s"); break; case 2: fMultiplier *= MULTIPLIER_MEDIUM; fTimer->setInterval(TIME_MEDIUM * 1000); lblDifficulty->setText(QString::number(TIME_MEDIUM) + "s"); break; default: fMultiplier *= MULTIPLIER_HARD; fTimer->setInterval(TIME_HARD * 1000); lblDifficulty->setText(QString::number(TIME_HARD) + "s"); } lblMultiplier->setText(tr("Multiplier: %1").arg( QString::number(fMultiplier, 'f', 2))); } void Musec::resetForm() { fIsActive = false; btnPlay->setText(tr("Play")); btnPlay->setDisabled(true); btnNext->setDisabled(true); edTitle->setDisabled(true); edArtist->setDisabled(true); edAlbum->setDisabled(true); // Reset difficulty slDifficulty->setMinimum(1); slDifficulty->setValue(1); } void Musec::activateForm() { fIsActive = true; edTitle->clear(); edArtist->clear(); edAlbum->clear(); btnPlay->setText(tr("Play Again")); btnNext->setEnabled(true); edTitle->setEnabled(true); edArtist->setEnabled(true); edAlbum->setEnabled(true); chkTitle->setChecked(false); chkArtist->setChecked(false); chkAlbum->setChecked(false); } void Musec::timeout() { fPlayer->stop(); } void Musec::durationChanged(qint64 duration) { if (duration <= 0) return; duration /= 1000; qint64 startRange = duration * 0.1f; qint64 timeRange = duration * 0.8f; qint64 random = qrand() % timeRange; fStartTime = startRange + random; qDebug() << fPlayer->metaData(QMediaMetaData::Title).toString(); qDebug() << fPlayer->metaData(QMediaMetaData::Author).toString(); qDebug() << fPlayer->metaData(QMediaMetaData::AlbumTitle).toString(); btnPlay->setEnabled(true); } void Musec::difficultyChanged(int value) { updateMultiplier(); } void Musec::on_btnPlay_clicked() { // Activate input if (!fIsActive) activateForm(); // Prevent difficulty cheating slDifficulty->setMinimum(slDifficulty->value()); playSong(); } void Musec::on_btnNext_clicked() { evaluate(); resetForm(); // Remove song from queue if (!fSongs.isEmpty()) fSongs.pop_front(); // Load next song if (!fSongs.isEmpty()) loadSong(fSongs.first()); else statusbar->showMessage(tr("No more songs left")); } void Musec::on_actAddDir_triggered() { statusbar->showMessage(tr("Loading...")); // Open dir and add music files to fSongs QString dir = QFileDialog::getExistingDirectory(this, tr("Select Directory"), fDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir.isEmpty()) { statusbar->clearMessage(); return; } QDirIterator it(dir, fExtensions, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) fSongs << it.next(); fDir = dir; if (fSongs.isEmpty()) { statusbar->showMessage(tr("No Songs found")); return; } shuffleList(); } void Musec::on_actAddFiles_triggered() { statusbar->showMessage(tr("Loading...")); // Add music files to fSongs QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files"), fDir, "Music (" + fExtensions.join(" ") + ")"); if (files.isEmpty()) { statusbar->clearMessage(); return; } fDir = QFileInfo(files[0]).absolutePath(); fSongs += files; if (fSongs.isEmpty()) { statusbar->showMessage(tr("No Songs found")); return; } shuffleList(); } void Musec::on_actClear_triggered() { resetForm(); fSongs.clear(); statusbar->showMessage(tr("No more songs left")); } <commit_msg>Revert change to allow broken parentheses/brackets<commit_after>/*==LICENSE== This file is part of Musec. Copyright (C) 2013 Florian Meißner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ==LICENSE==*/ #include "Musec.h" #include <QtGui> #include <QMediaMetaData> #include <QMediaPlayer> #include <QFileDialog> #define POINTS_TITLE 3 #define POINTS_ARTIST 1 #define POINTS_ALBUM 2 #define TIME_EASY 5 #define TIME_MEDIUM 3 #define TIME_HARD 1 #define MULTIPLIER_EASY 1 #define MULTIPLIER_MEDIUM 2 #define MULTIPLIER_HARD 5 Musec::Musec(QMainWindow* parent) : QMainWindow(parent) { setupUi(this); setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint); fPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency); fTimer = new QTimer(this); fTimer->setSingleShot(true); fDir = QDir::homePath(); fScore = 0; fSongsPlayed = 0; fIsActive = false; fExtensions << "*.mp3" << "*.m4a"; // These should contain meta data connect(fTimer, &QTimer::timeout, this, &Musec::timeout); connect(fPlayer, &QMediaPlayer::durationChanged, this, &Musec::durationChanged); connect(slDifficulty, &QSlider::valueChanged, this, &Musec::difficultyChanged); qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } void Musec::shuffleList() { // Shuffle song list for (int i = fSongs.size() - 1; i >= 0; i--) { int random = qrand() % fSongs.size(); QString str = fSongs[i]; fSongs[i] = fSongs[random]; fSongs[random] = str; } // Load first song loadSong(fSongs.first()); } void Musec::loadSong(const QString& filename) { fStartTime = 0; fPlayer->setMedia(QUrl::fromLocalFile(filename)); updateMultiplier(); statusbar->showMessage(tr("Played: %1 (%2 in queue)").arg( QString::number(fSongsPlayed)).arg(QString::number(fSongs.size()))); } void Musec::playSong() { statusbar->showMessage(QTime(0,0,0).addSecs(fStartTime).toString("mm:ss")); fPlayer->setPosition(fStartTime * 1000); fPlayer->play(); fTimer->start(); } void Musec::evaluate() { QString title = fPlayer->metaData(QMediaMetaData::Title).toString(); QString artist = fPlayer->metaData(QMediaMetaData::Author).toString(); QString album = fPlayer->metaData(QMediaMetaData::AlbumTitle).toString(); quint32 score = 0; if (match(edTitle->text(), title) || title.isEmpty()) { score += POINTS_TITLE; chkTitle->setChecked(true); } if (match(edArtist->text(), artist) || artist.isEmpty()) { score += POINTS_ARTIST; chkArtist->setChecked(true); } if (match(edAlbum->text(), album) || album.isEmpty()) { score += POINTS_ALBUM; chkAlbum->setChecked(true); } score = score * fMultiplier + 0.5f; fScore += score; edTitle->setText(title); edArtist->setText(artist); edAlbum->setText(album); fSongsPlayed++; lblScore->setText(tr("Score: %1").arg(QString::number(fScore))); float avg = fScore/fSongsPlayed; lblAverage->setText(tr("Average: %1").arg(QString::number(avg, 'f', 2))); lblLast->setText(tr("Last Score: %1").arg(QString::number(score))); } bool Musec::match(QString str1, QString str2) { // Cast to lower case str1 = str1.toLower(); str2 = str2.toLower(); // Remove (..., [... and non-alphabetic characters QRegularExpression regex("(\\(.*\\))|(\\[.*\\])|[^a-zA-Z]"); str1.remove(regex); str2.remove(regex); // Exact match if (str1 == str2) return true; // Allow one mistake every 5 letters int tolerance = str1.length()/5; int i = 0, j = 0, diff = 0, mismatches = 0; while (i < str1.length() && j < str2.length()) { if (str1.at(i) == str2.at(j)) { diff = i - j; i++; j++; } else { if (diff == i - j) { mismatches++; diff--; i++; } else { j++; } } } mismatches += str1.length() - i; mismatches += str2.length() - j; if (mismatches <= tolerance) return true; return false; } void Musec::updateMultiplier() { // Multiplier for number of songs in queue fMultiplier = 1 + fSongs.size()/200; // Multiplier for difficulty switch (slDifficulty->value()) { case 3: fMultiplier *= MULTIPLIER_EASY; fTimer->setInterval(TIME_EASY * 1000); lblDifficulty->setText(QString::number(TIME_EASY) + "s"); break; case 2: fMultiplier *= MULTIPLIER_MEDIUM; fTimer->setInterval(TIME_MEDIUM * 1000); lblDifficulty->setText(QString::number(TIME_MEDIUM) + "s"); break; default: fMultiplier *= MULTIPLIER_HARD; fTimer->setInterval(TIME_HARD * 1000); lblDifficulty->setText(QString::number(TIME_HARD) + "s"); } lblMultiplier->setText(tr("Multiplier: %1").arg( QString::number(fMultiplier, 'f', 2))); } void Musec::resetForm() { fIsActive = false; btnPlay->setText(tr("Play")); btnPlay->setDisabled(true); btnNext->setDisabled(true); edTitle->setDisabled(true); edArtist->setDisabled(true); edAlbum->setDisabled(true); // Reset difficulty slDifficulty->setMinimum(1); slDifficulty->setValue(1); } void Musec::activateForm() { fIsActive = true; edTitle->clear(); edArtist->clear(); edAlbum->clear(); btnPlay->setText(tr("Play Again")); btnNext->setEnabled(true); edTitle->setEnabled(true); edArtist->setEnabled(true); edAlbum->setEnabled(true); chkTitle->setChecked(false); chkArtist->setChecked(false); chkAlbum->setChecked(false); } void Musec::timeout() { fPlayer->stop(); } void Musec::durationChanged(qint64 duration) { if (duration <= 0) return; duration /= 1000; qint64 startRange = duration * 0.1f; qint64 timeRange = duration * 0.8f; qint64 random = qrand() % timeRange; fStartTime = startRange + random; qDebug() << fPlayer->metaData(QMediaMetaData::Title).toString(); qDebug() << fPlayer->metaData(QMediaMetaData::Author).toString(); qDebug() << fPlayer->metaData(QMediaMetaData::AlbumTitle).toString(); btnPlay->setEnabled(true); } void Musec::difficultyChanged(int value) { updateMultiplier(); } void Musec::on_btnPlay_clicked() { // Activate input if (!fIsActive) activateForm(); // Prevent difficulty cheating slDifficulty->setMinimum(slDifficulty->value()); playSong(); } void Musec::on_btnNext_clicked() { evaluate(); resetForm(); // Remove song from queue if (!fSongs.isEmpty()) fSongs.pop_front(); // Load next song if (!fSongs.isEmpty()) loadSong(fSongs.first()); else statusbar->showMessage(tr("No more songs left")); } void Musec::on_actAddDir_triggered() { statusbar->showMessage(tr("Loading...")); // Open dir and add music files to fSongs QString dir = QFileDialog::getExistingDirectory(this, tr("Select Directory"), fDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir.isEmpty()) { statusbar->clearMessage(); return; } QDirIterator it(dir, fExtensions, QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) fSongs << it.next(); fDir = dir; if (fSongs.isEmpty()) { statusbar->showMessage(tr("No Songs found")); return; } shuffleList(); } void Musec::on_actAddFiles_triggered() { statusbar->showMessage(tr("Loading...")); // Add music files to fSongs QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Files"), fDir, "Music (" + fExtensions.join(" ") + ")"); if (files.isEmpty()) { statusbar->clearMessage(); return; } fDir = QFileInfo(files[0]).absolutePath(); fSongs += files; if (fSongs.isEmpty()) { statusbar->showMessage(tr("No Songs found")); return; } shuffleList(); } void Musec::on_actClear_triggered() { resetForm(); fSongs.clear(); statusbar->showMessage(tr("No more songs left")); } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Python.h> #include <boost/python.hpp> #include <gtest/gtest.h> #include <Testing/ModuleTestBase/ModuleTestBase.h> #include <Core/Python/PythonDatatypeConverter.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Matlab/matlabconverter.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> #include <Testing/Utils/MatrixTestUtilities.h> #include <Testing/Utils/SCIRunUnitTests.h> #include <Testing/Utils/SCIRunFieldSamples.h> #include <Core/Python/PythonInterpreter.h> using namespace SCIRun; using namespace SCIRun::Core; using namespace Core::Python; using namespace Testing; using namespace TestUtils; class FieldConversionTests : public testing::Test { protected: virtual void SetUp() override { #ifdef WIN32 PythonInterpreter::Instance().initialize(false, "Core_Python_Tests", boost::filesystem::current_path().string()); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); #else Py_Initialize(); #endif } static FieldHandle roundTripThroughMatlabConverter(FieldHandle field) { MatlabIO::matlabarray ma; { MatlabIO::matlabconverter mc(nullptr); mc.converttostructmatrix(); mc.sciFieldTOmlArray(field, ma); } FieldHandle actual; { MatlabIO::matlabconverter mc(nullptr); mc.mlArrayTOsciField(ma, actual); } return actual; } static FieldHandle TetMesh1() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_mapfielddatafromelemtonode.fld"); } static FieldHandle TetMesh2() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_mapfielddatafromnodetoelem.fld"); } static FieldHandle CreateTriSurfScalarOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tri_surf/data_defined_on_node/scalar/tri_scalar_on_node.fld"); } static FieldHandle CreateTriSurfVectorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tri_surf/data_defined_on_node/vector/tri_vector_on_node.fld"); } static FieldHandle CreateTetMeshVectorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/vector/tet_vector_on_node.fld"); } static FieldHandle CreateTetMeshScalarOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/scalar/tet_scalar_on_node.fld"); } static FieldHandle CreateTetMeshScalarOnElem() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_elem/scalar/tet_scalar_on_elem.fld"); } static FieldHandle CreateTetMeshTensorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/tensor/tet_tensor_on_node.fld"); } static FieldHandle CreatePointCloudScalar() { return loadFieldFromFile(TestResources::rootDir() / "Fields/point_cloud/scalar/pts_scalar.fld"); } static FieldHandle CreateCurveMeshElem() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_curve_elem.fld"); } static FieldHandle CreateImageNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_image_node.fld"); } //static FieldHandle CreatePointCloudScalar() //{ // return loadFieldFromFile(TestResources::rootDir() / "Fields/point_cloud/scalar/pts_scalar.fld"); //} static std::vector<FieldHandle> fileExamples() { return{ TetMesh1(), TetMesh2(), CreateTriSurfScalarOnNode(), CreateTriSurfVectorOnNode(), CreateTetMeshVectorOnNode(), CreateTetMeshScalarOnElem(), CreateTetMeshScalarOnNode(), CreateTetMeshTensorOnNode(), CreatePointCloudScalar(), CreateCurveMeshElem(), CreateImageNode() }; } }; TEST_F(FieldConversionTests, RoundTripLatVolUsingJustMatlabConversion) { auto expected = CreateEmptyLatVol(2,2,2); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_latvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("LatVolMesh<HexTrilinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("LatVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point>>,HexTrilinearLgn<double>,FData3d<double,LatVolMesh<HexTrilinearLgn<Point>>>>", info.get_field_type_id()); auto expectedTransform = expected->vmesh()->get_transform(); auto actualTransform = actualField->vmesh()->get_transform(); ASSERT_EQ(expectedTransform, actualTransform); } TEST_F(FieldConversionTests, RoundTripTetVolUsingJustMatlabConversion) { auto expected = TetMesh1(); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_constantdata()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,ConstantBasis<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTriSurfUsingJustMatlabConversion) { auto expected = CreateTriSurfScalarOnNode(); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_trisurf()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TriSurfMesh<TriLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TriSurfMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TriSurfMesh<TriLinearLgn<Point>>,TriLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, LoopThroughFieldFilesMatlabOnly) { for (const auto& field : fileExamples()) { auto expected = field; FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); } } TEST_F(FieldConversionTests, LoopThroughFieldFiles) { for (const auto& field : fileExamples()) { auto expected = field; FieldInformation expectedInfo(expected); // std::cout << "Converting " << expectedInfo.get_field_type_id() << " to python." << std::endl; auto pyField = convertFieldToPython(expected); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); // std::cout << "Converting " << expectedInfo.get_field_type_id() << " from python." << std::endl; auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); ASSERT_TRUE(compareNodes(expected, actualField)); std::cout << "Done testing " << expectedInfo.get_field_type_id() << "." << std::endl; } } TEST_F(FieldConversionTests, RoundTripLatVol) { auto expected = CreateEmptyLatVol(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(9, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_latvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("LatVolMesh<HexTrilinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("LatVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point>>,HexTrilinearLgn<double>,FData3d<double,LatVolMesh<HexTrilinearLgn<Point>>>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTriSurf) { auto expected = CreateTriSurfScalarOnNode(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_trisurf()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TriSurfMesh<TriLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TriSurfMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TriSurfMesh<TriLinearLgn<Point>>,TriLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTetVolNode) { auto expected = CreateTetMeshScalarOnNode(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,TetLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTetVolCell) { auto expected = CreateTetMeshScalarOnElem(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_constantdata()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,ConstantBasis<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RejectsEmptyDictionary) { boost::python::dict emptyDict; FieldExtractor converter(emptyDict); ASSERT_FALSE(converter.check()); } TEST_F(FieldConversionTests, RejectsIncompatibleDictionary) { boost::python::dict dict; dict.setdefault(2, 5); ASSERT_EQ(1, len(dict)); FieldExtractor converter(dict); ASSERT_FALSE(converter.check()); } <commit_msg>Fix debug build<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Python.h> #include <boost/python.hpp> #include <gtest/gtest.h> #include <Testing/ModuleTestBase/ModuleTestBase.h> #include <Core/Python/PythonDatatypeConverter.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Matlab/matlabconverter.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> #include <Testing/Utils/MatrixTestUtilities.h> #include <Testing/Utils/SCIRunUnitTests.h> #include <Testing/Utils/SCIRunFieldSamples.h> #ifdef WIN32 #ifndef DEBUG #include <Core/Python/PythonInterpreter.h> #endif #endif using namespace SCIRun; using namespace SCIRun::Core; using namespace Core::Python; using namespace Testing; using namespace TestUtils; class FieldConversionTests : public testing::Test { protected: virtual void SetUp() override { #ifdef WIN32 #ifndef DEBUG PythonInterpreter::Instance().initialize(false, "Core_Python_Tests", boost::filesystem::current_path().string()); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); #endif #else Py_Initialize(); #endif } static FieldHandle roundTripThroughMatlabConverter(FieldHandle field) { MatlabIO::matlabarray ma; { MatlabIO::matlabconverter mc(nullptr); mc.converttostructmatrix(); mc.sciFieldTOmlArray(field, ma); } FieldHandle actual; { MatlabIO::matlabconverter mc(nullptr); mc.mlArrayTOsciField(ma, actual); } return actual; } static FieldHandle TetMesh1() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_mapfielddatafromelemtonode.fld"); } static FieldHandle TetMesh2() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_mapfielddatafromnodetoelem.fld"); } static FieldHandle CreateTriSurfScalarOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tri_surf/data_defined_on_node/scalar/tri_scalar_on_node.fld"); } static FieldHandle CreateTriSurfVectorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tri_surf/data_defined_on_node/vector/tri_vector_on_node.fld"); } static FieldHandle CreateTetMeshVectorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/vector/tet_vector_on_node.fld"); } static FieldHandle CreateTetMeshScalarOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/scalar/tet_scalar_on_node.fld"); } static FieldHandle CreateTetMeshScalarOnElem() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_elem/scalar/tet_scalar_on_elem.fld"); } static FieldHandle CreateTetMeshTensorOnNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/tet_mesh/data_defined_on_node/tensor/tet_tensor_on_node.fld"); } static FieldHandle CreatePointCloudScalar() { return loadFieldFromFile(TestResources::rootDir() / "Fields/point_cloud/scalar/pts_scalar.fld"); } static FieldHandle CreateCurveMeshElem() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_curve_elem.fld"); } static FieldHandle CreateImageNode() { return loadFieldFromFile(TestResources::rootDir() / "Fields/test_image_node.fld"); } //static FieldHandle CreatePointCloudScalar() //{ // return loadFieldFromFile(TestResources::rootDir() / "Fields/point_cloud/scalar/pts_scalar.fld"); //} static std::vector<FieldHandle> fileExamples() { return{ TetMesh1(), TetMesh2(), CreateTriSurfScalarOnNode(), CreateTriSurfVectorOnNode(), CreateTetMeshVectorOnNode(), CreateTetMeshScalarOnElem(), CreateTetMeshScalarOnNode(), CreateTetMeshTensorOnNode(), CreatePointCloudScalar(), CreateCurveMeshElem(), CreateImageNode() }; } }; TEST_F(FieldConversionTests, RoundTripLatVolUsingJustMatlabConversion) { auto expected = CreateEmptyLatVol(2,2,2); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_latvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("LatVolMesh<HexTrilinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("LatVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point>>,HexTrilinearLgn<double>,FData3d<double,LatVolMesh<HexTrilinearLgn<Point>>>>", info.get_field_type_id()); auto expectedTransform = expected->vmesh()->get_transform(); auto actualTransform = actualField->vmesh()->get_transform(); ASSERT_EQ(expectedTransform, actualTransform); } TEST_F(FieldConversionTests, RoundTripTetVolUsingJustMatlabConversion) { auto expected = TetMesh1(); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_constantdata()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,ConstantBasis<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTriSurfUsingJustMatlabConversion) { auto expected = CreateTriSurfScalarOnNode(); FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); EXPECT_TRUE(info.is_trisurf()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TriSurfMesh<TriLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TriSurfMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TriSurfMesh<TriLinearLgn<Point>>,TriLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, LoopThroughFieldFilesMatlabOnly) { for (const auto& field : fileExamples()) { auto expected = field; FieldInformation expectedInfo(expected); auto actual = roundTripThroughMatlabConverter(expected); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); } } TEST_F(FieldConversionTests, LoopThroughFieldFiles) { for (const auto& field : fileExamples()) { auto expected = field; FieldInformation expectedInfo(expected); // std::cout << "Converting " << expectedInfo.get_field_type_id() << " to python." << std::endl; auto pyField = convertFieldToPython(expected); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); // std::cout << "Converting " << expectedInfo.get_field_type_id() << " from python." << std::endl; auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); ASSERT_EQ(expectedInfo, info); ASSERT_TRUE(compareNodes(expected, actualField)); std::cout << "Done testing " << expectedInfo.get_field_type_id() << "." << std::endl; } } TEST_F(FieldConversionTests, RoundTripLatVol) { auto expected = CreateEmptyLatVol(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(9, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_latvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("LatVolMesh<HexTrilinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("LatVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point>>,HexTrilinearLgn<double>,FData3d<double,LatVolMesh<HexTrilinearLgn<Point>>>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTriSurf) { auto expected = CreateTriSurfScalarOnNode(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_trisurf()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TriSurfMesh<TriLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TriSurfMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TriSurfMesh<TriLinearLgn<Point>>,TriLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTetVolNode) { auto expected = CreateTetMeshScalarOnNode(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_linear()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,TetLinearLgn<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RoundTripTetVolCell) { auto expected = CreateTetMeshScalarOnElem(); auto pyField = convertFieldToPython(expected); EXPECT_EQ(10, len(pyField.items())); FieldExtractor converter(pyField); ASSERT_TRUE(converter.check()); auto actual = converter(); ASSERT_TRUE(actual != nullptr); auto actualField = boost::dynamic_pointer_cast<Field>(actual); ASSERT_TRUE(actualField != nullptr); FieldInformation info(actualField); EXPECT_TRUE(info.is_tetvolmesh()); EXPECT_TRUE(info.is_double()); EXPECT_TRUE(info.is_scalar()); EXPECT_TRUE(info.is_constantdata()); EXPECT_EQ("TetVolMesh<TetLinearLgn<Point>>", info.get_mesh_type_id()); EXPECT_EQ("TetVolMesh", info.get_mesh_type()); EXPECT_EQ("GenericField<TetVolMesh<TetLinearLgn<Point>>,ConstantBasis<double>,vector<double>>", info.get_field_type_id()); } TEST_F(FieldConversionTests, RejectsEmptyDictionary) { boost::python::dict emptyDict; FieldExtractor converter(emptyDict); ASSERT_FALSE(converter.check()); } TEST_F(FieldConversionTests, RejectsIncompatibleDictionary) { boost::python::dict dict; dict.setdefault(2, 5); ASSERT_EQ(1, len(dict)); FieldExtractor converter(dict); ASSERT_FALSE(converter.check()); } <|endoftext|>
<commit_before>// // Created by Matthias Stumpp on 27/09/15. // #ifndef THRILL_BUCKET_BLOCK_POOL_HPP #define THRILL_BUCKET_BLOCK_POOL_HPP #include <stack> #include <thrill/common/functional.hpp> namespace thrill { namespace core { template<typename BucketBlock> class BucketBlockPool { public: //constructor (we don't need to do anything here) BucketBlockPool() { } //delete the copy constructor; we can't copy it: BucketBlockPool(const BucketBlockPool &) = delete; //move constructor, so we can move it: BucketBlockPool(BucketBlockPool &&other) { this->free(std::move(other.free)); } //allocate a chunk of memory as big as Type needs: BucketBlock* GetBlock() { BucketBlock* place; if (!free.empty()) { place = static_cast<BucketBlock*>(free.top()); free.pop(); } else { place = static_cast<BucketBlock*>(operator new(sizeof(BucketBlock))); place->size = 0; place->next = nullptr; } return place; } //mark some memory as available (no longer used): void Deallocate(BucketBlock *o) { o->size = 0; o->next = nullptr; free.push(static_cast<BucketBlock*>(o)); } void Destroy() { while (!free.empty()) { free.top()->destroy_items(); operator delete(free.top()); free.pop(); } } //delete all of the available memory chunks: ~BucketBlockPool() { } private: //stack to hold pointers to free chunks: std::stack<BucketBlock*> free; }; } } #endif //THRILL_BUCKET_BLOCK_POOL_HPP <commit_msg>added header<commit_after>/******************************************************************************* * thrill/core/bucket_block_pool.hpp * * BucketBlockPool to stack allocated BucketBlocks. * * Part of Project Thrill. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #ifndef THRILL_BUCKET_BLOCK_POOL_HPP #define THRILL_BUCKET_BLOCK_POOL_HPP #include <stack> #include <thrill/common/functional.hpp> namespace thrill { namespace core { template<typename BucketBlock> class BucketBlockPool { public: //constructor (we don't need to do anything here) BucketBlockPool() { } //delete the copy constructor; we can't copy it: BucketBlockPool(const BucketBlockPool &) = delete; //move constructor, so we can move it: BucketBlockPool(BucketBlockPool &&other) { this->free(std::move(other.free)); } //allocate a chunk of memory as big as Type needs: BucketBlock* GetBlock() { BucketBlock* place; if (!free.empty()) { place = static_cast<BucketBlock*>(free.top()); free.pop(); } else { place = static_cast<BucketBlock*>(operator new(sizeof(BucketBlock))); place->size = 0; place->next = nullptr; } return place; } //mark some memory as available (no longer used): void Deallocate(BucketBlock *o) { o->size = 0; o->next = nullptr; free.push(static_cast<BucketBlock*>(o)); } void Destroy() { while (!free.empty()) { free.top()->destroy_items(); operator delete(free.top()); free.pop(); } } //delete all of the available memory chunks: ~BucketBlockPool() { } private: //stack to hold pointers to free chunks: std::stack<BucketBlock*> free; }; } } #endif //THRILL_BUCKET_BLOCK_POOL_HPP <|endoftext|>
<commit_before>#include "hirestimer.hpp" #ifdef __APPLE__ #include <mach/mach.h> #include <mach/mach_time.h> HiResTimer::HiResTimer() : elapsedTicks(0), running(0), startTicks(0) { } void HiResTimer::start() { if (++running == 1) startTicks = mach_absolute_time(); } void HiResTimer::stop() { if (--running == 0) { unsigned long long end = mach_absolute_time(); elapsedTicks += (end - startTicks); } } unsigned long long HiResTimer::elapsedNanos() { static mach_timebase_info_data_t timeBaseInfo; if (timeBaseInfo.denom == 0) { mach_timebase_info(&timeBaseInfo); } return elapsedTicks * timeBaseInfo.numer / timeBaseInfo.denom; } #elif defined(_WIN32) || defined(_WIN64) HiResTimer::HiResTimer() {} void HiResTimer::start() {} void HiResTimer::stop() {} unsigned long long HiResTimer::elapsedNanos() { return 0; } #else // Unices #include <time.h> HiResTimer::HiResTimer() : elapsedTicks(0), running(0), startTicks(0) { } void HiResTimer::start() { if (++running == 1) { struct timespec t; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t); startTicks = (unsigned long long)t.tv_sec * 1000000000 + t.tv_nsec; } } void HiResTimer::stop() { if (--running == 0) { struct timespec t; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t); elapsedTicks = (unsigned long long)t.tv_sec * 1000000000 + t.tv_nsec - startTicks; } } unsigned long long HiResTimer::elapsedNanos() { return elapsedTicks; } #endif // __APPLE__ <commit_msg>FreeBSD compiler fix.<commit_after>#include "hirestimer.hpp" #ifdef __APPLE__ #include <mach/mach.h> #include <mach/mach_time.h> HiResTimer::HiResTimer() : elapsedTicks(0), running(0), startTicks(0) { } void HiResTimer::start() { if (++running == 1) startTicks = mach_absolute_time(); } void HiResTimer::stop() { if (--running == 0) { unsigned long long end = mach_absolute_time(); elapsedTicks += (end - startTicks); } } unsigned long long HiResTimer::elapsedNanos() { static mach_timebase_info_data_t timeBaseInfo; if (timeBaseInfo.denom == 0) { mach_timebase_info(&timeBaseInfo); } return elapsedTicks * timeBaseInfo.numer / timeBaseInfo.denom; } #elif defined(_WIN32) || defined(_WIN64) HiResTimer::HiResTimer() {} void HiResTimer::start() {} void HiResTimer::stop() {} unsigned long long HiResTimer::elapsedNanos() { return 0; } #else // Unices #if defined(CLOCK_PROCESS_CPUTIME_ID) && defined(__linux__) # define CLOCK CLOCK_PROCESS_CPUTIME_ID #elif defined(CLOCK_PROF) && defined(__FreeBSD__) # define CLOCK CLOCK_PROF #else # define CLOCK CLOCK_REALTIME #endif #include <time.h> HiResTimer::HiResTimer() : elapsedTicks(0), running(0), startTicks(0) { } void HiResTimer::start() { if (++running == 1) { struct timespec t; clock_gettime(CLOCK, &t); startTicks = (unsigned long long)t.tv_sec * 1000000000 + t.tv_nsec; } } void HiResTimer::stop() { if (--running == 0) { struct timespec t; clock_gettime(CLOCK, &t); elapsedTicks = (unsigned long long)t.tv_sec * 1000000000 + t.tv_nsec - startTicks; } } unsigned long long HiResTimer::elapsedNanos() { return elapsedTicks; } #endif // __APPLE__ <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAbsImageFilter.h" #include "itkAbsoluteValueDifferenceImageFilter.h" #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAdaptiveHistogramEqualizationImageFilter.txx" #include "itkAddImageFilter.h" #include "itkAndImageFilter.h" #include "itkAnisotropicDiffusionFunction.h" #include "itkAnisotropicDiffusionImageFilter.txx" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBSplineCenteredL2ResampleImageFilterBase.txx" #include "itkBSplineCenteredResampleImageFilterBase.txx" #include "itkBSplineDecompositionImageFilter.txx" #include "itkBSplineDownsampleImageFilter.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBSplineL2ResampleImageFilterBase.txx" #include "itkBSplineResampleImageFilterBase.txx" #include "itkBSplineResampleImageFunction.h" #include "itkBSplineUpsampleImageFilter.txx" #include "itkBilateralImageFilter.txx" #include "itkBinaryDilateImageFilter.txx" #include "itkBinaryErodeImageFilter.txx" #include "itkBinaryFunctorImageFilter.txx" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMaskToNarrowBandPointSetFilter.txx" #include "itkBinaryMedianImageFilter.txx" #include "itkBinaryThresholdImageFilter.txx" #include "itkBinomialBlurImageFilter.txx" #include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx" #include "itkBloxBoundaryPointToCoreAtomImageFilter.txx" #include "itkBloxBoundaryProfileImageToBloxCoreAtomImageFilter.txx" #include "itkBoundedReciprocalImageFilter.h" #include "itkCannyEdgeDetectionImageFilter.txx" #include "itkCastImageFilter.h" #include "itkChainCodeToFourierSeriesPathFilter.txx" #include "itkChangeInformationImageFilter.txx" #include "itkCompose2DCovariantVectorImageFilter.h" #include "itkCompose2DVectorImageFilter.h" #include "itkCompose3DCovariantVectorImageFilter.h" #include "itkCompose3DVectorImageFilter.h" #include "itkComposeRGBImageFilter.h" #include "itkConfidenceConnectedImageFilter.txx" #include "itkConnectedComponentImageFilter.txx" #include "itkConnectedThresholdImageFilter.txx" #include "itkConstantPadImageFilter.txx" #include "itkCosImageFilter.h" #include "itkCropImageFilter.txx" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkDanielssonDistanceMapImageFilter.txx" #include "itkSignedDanielssonDistanceMapImageFilter.txx" #include "itkDeformationFieldSource.txx" #include "itkDerivativeImageFilter.txx" #include "itkDifferenceOfGaussiansGradientImageFilter.txx" #include "itkDiffusionTensor3DReconstructionImageFilter.txx" #include "itkDilateObjectMorphologyImageFilter.txx" #include "itkDirectedHausdorffDistanceImageFilter.txx" #include "itkDiscreteGaussianImageFilter.txx" #include "itkDivideImageFilter.h" #include "itkDoubleThresholdImageFilter.txx" #include "itkEdgePotentialImageFilter.h" #include "itkEigenAnalysis2DImageFilter.txx" #include "itkErodeObjectMorphologyImageFilter.txx" #include "itkExpImageFilter.h" #include "itkExpNegativeImageFilter.h" #include "itkExpandImageFilter.txx" #include "itkExtractImageFilter.txx" #include "itkExtractImageFilterRegionCopier.h" #include "itkExtractOrthogonalSwath2DImageFilter.txx" #include "itkFlipImageFilter.txx" #include "itkGaussianImageSource.txx" #include "itkGetAverageSliceImageFilter.txx" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientImageFilter.txx" #include "itkGradientImageToBloxBoundaryPointImageFilter.txx" #include "itkGradientMagnitudeImageFilter.txx" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx" #include "itkGradientNDAnisotropicDiffusionFunction.txx" #include "itkGradientRecursiveGaussianImageFilter.txx" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleConnectedClosingImageFilter.txx" #include "itkGrayscaleConnectedOpeningImageFilter.txx" #include "itkGrayscaleDilateImageFilter.txx" #include "itkGrayscaleErodeImageFilter.txx" #include "itkGrayscaleFillholeImageFilter.txx" #include "itkGrayscaleFunctionDilateImageFilter.txx" #include "itkGrayscaleFunctionErodeImageFilter.txx" #include "itkGrayscaleGeodesicDilateImageFilter.txx" #include "itkGrayscaleGeodesicErodeImageFilter.txx" #include "itkGrayscaleGrindPeakImageFilter.txx" #include "itkHConcaveImageFilter.txx" #include "itkHConvexImageFilter.txx" #include "itkHMaximaImageFilter.txx" #include "itkHMinimaImageFilter.txx" #include "itkHardConnectedComponentImageFilter.txx" #include "itkHausdorffDistanceImageFilter.txx" #include "itkHoughTransform2DCirclesImageFilter.txx" #include "itkHoughTransform2DLinesImageFilter.txx" #include "itkImageToMeshFilter.txx" #include "itkImageToParametricSpaceFilter.txx" #include "itkImplicitManifoldNormalVectorFilter.txx" #include "itkImportImageFilter.txx" #include "itkIntensityWindowingImageFilter.txx" #include "itkInteriorExteriorMeshFilter.txx" #include "itkInterpolateImageFilter.txx" #include "itkInterpolateImagePointsFilter.txx" #include "itkInverseDeformationFieldImageFilter.txx" #include "itkIsolatedConnectedImageFilter.txx" #include "itkIterativeInverseDeformationFieldImageFilter.txx" #include "itkJoinImageFilter.h" #include "itkLabelStatisticsImageFilter.txx" #include "itkLaplacianImageFilter.txx" #include "itkLaplacianRecursiveGaussianImageFilter.txx" #include "itkLaplacianSharpeningImageFilter.txx" #include "itkLevelSetFunctionWithRefitTerm.txx" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMaskImageFilter.h" #include "itkMaskNegatedImageFilter.h" #include "itkMaximumImageFilter.h" #include "itkMeanImageFilter.txx" #include "itkMedianImageFilter.txx" #include "itkMinimumImageFilter.h" #include "itkMinimumMaximumImageCalculator.txx" #include "itkMinimumMaximumImageFilter.txx" #include "itkMirrorPadImageFilter.txx" #include "itkMorphologyImageFilter.txx" #include "itkMultiplyImageFilter.h" #include "itkNarrowBand.txx" #include "itkNarrowBandImageFilterBase.txx" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.txx" #include "itkNaryMaximumImageFilter.h" #include "itkNeighborhoodConnectedImageFilter.txx" #include "itkNeighborhoodOperatorImageFilter.txx" #include "itkNoiseImageFilter.txx" #include "itkNonThreadedShrinkImageFilter.txx" #include "itkNormalVectorDiffusionFunction.txx" #include "itkNormalVectorFunctionBase.txx" #include "itkNormalizeImageFilter.txx" #include "itkNotImageFilter.h" #include "itkObjectMorphologyImageFilter.txx" #include "itkOrImageFilter.h" #include "itkOrientImageFilter.txx" #include "itkPadImageFilter.txx" #include "itkParallelSparseFieldLevelSetImageFilter.txx" #include "itkParametricSpaceToImageSpaceMeshFilter.txx" #include "itkPasteImageFilter.txx" #include "itkPathToChainCodePathFilter.txx" #include "itkPathToImageFilter.txx" #include "itkPermuteAxesImageFilter.txx" #include "itkPointSetToImageFilter.txx" #include "itkRGBToLuminanceImageFilter.h" #include "itkRandomImageSource.txx" #include "itkRecursiveGaussianImageFilter.txx" #include "itkRecursiveSeparableImageFilter.txx" #include "itkReflectImageFilter.txx" #include "itkReflectiveImageRegionConstIterator.txx" #include "itkReflectiveImageRegionIterator.txx" #include "itkRegionOfInterestImageFilter.txx" #include "itkRelabelComponentImageFilter.txx" #include "itkResampleImageFilter.txx" #include "itkRescaleIntensityImageFilter.txx" #include "itkScalarAnisotropicDiffusionFunction.txx" #include "itkScalarToArrayCastImageFilter.txx" #include "itkShiftScaleImageFilter.txx" #include "itkShiftScaleInPlaceImageFilter.txx" #include "itkShrinkImageFilter.txx" #include "itkSigmoidImageFilter.h" #include "itkSimilarityIndexImageFilter.txx" #include "itkSimplexMeshAdaptTopologyFilter.txx" #include "itkSimplexMeshToTriangleMeshFilter.txx" #include "itkSinImageFilter.h" #include "itkSmoothingRecursiveGaussianImageFilter.txx" #include "itkSobelEdgeDetectionImageFilter.txx" #include "itkSparseFieldFourthOrderLevelSetImageFilter.txx" #include "itkSparseFieldLayer.txx" #include "itkSparseFieldLevelSetImageFilter.txx" #include "itkSpatialFunctionImageEvaluatorFilter.txx" #include "itkSpatialObjectToImageFilter.txx" #include "itkSpatialObjectToImageStatisticsCalculator.txx" #include "itkSpatialObjectToPointSetFilter.txx" #include "itkSqrtImageFilter.h" #include "itkSquareImageFilter.h" #include "itkSquaredDifferenceImageFilter.h" #include "itkStatisticsImageFilter.txx" #include "itkStreamingImageFilter.txx" #include "itkSubtractImageFilter.h" #include "itkTanImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.txx" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.txx" #include "itkThresholdLabelerImageFilter.txx" #include "itkTileImageFilter.txx" #include "itkTobogganImageFilter.txx" #include "itkTransformMeshFilter.txx" #include "itkTriangleMeshToSimplexMeshFilter.txx" #include "itkTwoOutputExampleImageFilter.txx" #include "itkUnaryFunctorImageFilter.txx" #include "itkVTKImageExport.txx" #include "itkVTKImageExportBase.h" #include "itkVTKImageImport.txx" #include "itkVectorAnisotropicDiffusionFunction.txx" #include "itkVectorCastImageFilter.h" #include "itkVectorConfidenceConnectedImageFilter.txx" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkVectorExpandImageFilter.txx" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientMagnitudeImageFilter.txx" #include "itkVectorGradientNDAnisotropicDiffusionFunction.txx" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkVectorNeighborhoodOperatorImageFilter.txx" #include "itkVectorResampleImageFilter.txx" #include "itkVectorRescaleIntensityImageFilter.txx" #include "itkWarpImageFilter.txx" #include "itkWarpVectorImageFilter.txx" #include "itkWeightedAddImageFilter.h" #include "itkWrapPadImageFilter.txx" #include "itkXorImageFilter.h" #include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx" #include "itkZeroCrossingImageFilter.txx" int main ( int , char* ) { return 0; } <commit_msg>ENH: Added missing classes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAbsImageFilter.h" #include "itkAbsoluteValueDifferenceImageFilter.h" #include "itkAccumulateImageFilter.txx" #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAdaptiveHistogramEqualizationImageFilter.txx" #include "itkAddImageFilter.h" #include "itkAndImageFilter.h" #include "itkAnisotropicDiffusionFunction.h" #include "itkAnisotropicDiffusionImageFilter.txx" #include "itkApproximateSignedDistanceMapImageFilter.txx" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBSplineCenteredL2ResampleImageFilterBase.txx" #include "itkBSplineCenteredResampleImageFilterBase.txx" #include "itkBSplineDecompositionImageFilter.txx" #include "itkBSplineDownsampleImageFilter.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBSplineL2ResampleImageFilterBase.txx" #include "itkBSplineResampleImageFilterBase.txx" #include "itkBSplineResampleImageFunction.h" #include "itkBSplineUpsampleImageFilter.txx" #include "itkBilateralImageFilter.txx" #include "itkBinaryDilateImageFilter.txx" #include "itkBinaryErodeImageFilter.txx" #include "itkBinaryFunctorImageFilter.txx" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMaskToNarrowBandPointSetFilter.txx" #include "itkBinaryMedianImageFilter.txx" #include "itkBinaryMorphologyImageFilter.txx" #include "itkBinaryThresholdImageFilter.txx" #include "itkBinomialBlurImageFilter.txx" #include "itkBlackTopHatImageFilter.txx" #include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx" #include "itkBloxBoundaryPointToCoreAtomImageFilter.txx" #include "itkBloxBoundaryProfileImageToBloxCoreAtomImageFilter.txx" #include "itkBoundedReciprocalImageFilter.h" #include "itkCannyEdgeDetectionImageFilter.txx" #include "itkCastImageFilter.h" #include "itkChainCodeToFourierSeriesPathFilter.txx" #include "itkChangeInformationImageFilter.txx" #include "itkChangeLabelImageFilter.txx" #include "itkCheckerBoardImageFilter.txx" #include "itkClosingByReconstructionImageFilter.txx" #include "itkComplexToImaginaryImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkComplexToPhaseImageFilter.h" #include "itkComplexToRealImageFilter.h" #include "itkCompose2DCovariantVectorImageFilter.h" #include "itkCompose2DVectorImageFilter.h" #include "itkCompose3DCovariantVectorImageFilter.h" #include "itkCompose3DVectorImageFilter.h" #include "itkComposeRGBImageFilter.h" #include "itkConfidenceConnectedImageFilter.txx" #include "itkConnectedComponentFunctorImageFilter.txx" #include "itkConnectedComponentImageFilter.txx" #include "itkConnectedThresholdImageFilter.txx" #include "itkConstantPadImageFilter.txx" #include "itkConstrainedValueAdditionImageFilter.h" #include "itkConstrainedValueDifferenceImageFilter.h" #include "itkContourDirectedMeanDistanceImageFilter.txx" #include "itkContourMeanDistanceImageFilter.txx" #include "itkCosImageFilter.h" #include "itkCropImageFilter.txx" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkDanielssonDistanceMapImageFilter.txx" #include "itkDeformationFieldJacobianDeterminantFilter.txx" #include "itkDeformationFieldSource.txx" #include "itkDerivativeImageFilter.txx" #include "itkDifferenceOfGaussiansGradientImageFilter.txx" #include "itkDiffusionTensor3DReconstructionImageFilter.txx" #include "itkDilateObjectMorphologyImageFilter.txx" #include "itkDirectedHausdorffDistanceImageFilter.txx" #include "itkDiscreteGaussianImageFilter.txx" #include "itkDivideImageFilter.h" #include "itkDoubleThresholdImageFilter.txx" #include "itkEdgePotentialImageFilter.h" #include "itkEigenAnalysis2DImageFilter.txx" #include "itkErodeObjectMorphologyImageFilter.txx" #include "itkExpImageFilter.h" #include "itkExpNegativeImageFilter.h" #include "itkExpandImageFilter.txx" #include "itkExtractImageFilter.txx" #include "itkExtractImageFilterRegionCopier.h" #include "itkExtractOrthogonalSwath2DImageFilter.txx" #include "itkFastIncrementalBinaryDilateImageFilter.h" #include "itkFlipImageFilter.txx" #include "itkGaussianImageSource.txx" #include "itkGetAverageSliceImageFilter.txx" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientImageFilter.txx" #include "itkGradientImageToBloxBoundaryPointImageFilter.txx" #include "itkGradientMagnitudeImageFilter.txx" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx" #include "itkGradientNDAnisotropicDiffusionFunction.txx" #include "itkGradientRecursiveGaussianImageFilter.txx" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleConnectedClosingImageFilter.txx" #include "itkGrayscaleConnectedOpeningImageFilter.txx" #include "itkGrayscaleDilateImageFilter.txx" #include "itkGrayscaleErodeImageFilter.txx" #include "itkGrayscaleFillholeImageFilter.txx" #include "itkGrayscaleFunctionDilateImageFilter.txx" #include "itkGrayscaleFunctionErodeImageFilter.txx" #include "itkGrayscaleGeodesicDilateImageFilter.txx" #include "itkGrayscaleGeodesicErodeImageFilter.txx" #include "itkGrayscaleGrindPeakImageFilter.txx" #include "itkGrayscaleMorphologicalClosingImageFilter.txx" #include "itkGrayscaleMorphologicalOpeningImageFilter.txx" #include "itkHConcaveImageFilter.txx" #include "itkHConvexImageFilter.txx" #include "itkHMaximaImageFilter.txx" #include "itkHMinimaImageFilter.txx" #include "itkHardConnectedComponentImageFilter.txx" #include "itkHausdorffDistanceImageFilter.txx" #include "itkHessianRecursiveGaussianImageFilter.txx" #include "itkHoughTransform2DCirclesImageFilter.txx" #include "itkHoughTransform2DLinesImageFilter.txx" #include "itkImageToMeshFilter.txx" #include "itkImageToParametricSpaceFilter.txx" #include "itkImplicitManifoldNormalVectorFilter.txx" #include "itkImportImageFilter.txx" #include "itkIntensityWindowingImageFilter.txx" #include "itkInteriorExteriorMeshFilter.txx" #include "itkInterpolateImageFilter.txx" #include "itkInterpolateImagePointsFilter.txx" #include "itkInverseDeformationFieldImageFilter.txx" #include "itkIsolatedConnectedImageFilter.txx" #include "itkIterativeInverseDeformationFieldImageFilter.txx" #include "itkJoinImageFilter.h" #include "itkJoinSeriesImageFilter.txx" #include "itkLabelStatisticsImageFilter.txx" #include "itkLaplacianImageFilter.txx" #include "itkLaplacianRecursiveGaussianImageFilter.txx" #include "itkLaplacianSharpeningImageFilter.txx" #include "itkLevelSetFunctionWithRefitTerm.txx" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMaskImageFilter.h" #include "itkMaskNegatedImageFilter.h" #include "itkMaskNeighborhoodOperatorImageFilter.txx" #include "itkMatrixIndexSelectionImageFilter.h" #include "itkMaximumImageFilter.h" #include "itkMeanImageFilter.txx" #include "itkMedianImageFilter.txx" #include "itkMinimumImageFilter.h" #include "itkMinimumMaximumImageCalculator.txx" #include "itkMinimumMaximumImageFilter.txx" #include "itkMirrorPadImageFilter.txx" #include "itkMorphologyImageFilter.txx" #include "itkMultiplyImageFilter.h" #include "itkNarrowBand.txx" #include "itkNarrowBandImageFilterBase.txx" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.txx" #include "itkNaryMaximumImageFilter.h" #include "itkNeighborhoodConnectedImageFilter.txx" #include "itkNeighborhoodOperatorImageFilter.txx" #include "itkNoiseImageFilter.txx" #include "itkNonThreadedShrinkImageFilter.txx" #include "itkNormalVectorDiffusionFunction.txx" #include "itkNormalVectorFunctionBase.txx" #include "itkNormalizeImageFilter.txx" #include "itkNormalizedCorrelationImageFilter.txx" #include "itkNotImageFilter.h" #include "itkObjectMorphologyImageFilter.txx" #include "itkOpeningByReconstructionImageFilter.txx" #include "itkOrImageFilter.h" #include "itkOrientImageFilter.txx" #include "itkPadImageFilter.txx" #include "itkParallelSparseFieldLevelSetImageFilter.txx" #include "itkParametricSpaceToImageSpaceMeshFilter.txx" #include "itkPasteImageFilter.txx" #include "itkPathToChainCodePathFilter.txx" #include "itkPathToImageFilter.txx" #include "itkPermuteAxesImageFilter.txx" #include "itkPointSetToImageFilter.txx" #include "itkPolylineMask2DImageFilter.txx" #include "itkPolylineMaskImageFilter.txx" #include "itkRGBToLuminanceImageFilter.h" #include "itkRandomImageSource.txx" #include "itkReconstructionByDilationImageFilter.txx" #include "itkReconstructionByErosionImageFilter.txx" #include "itkRecursiveGaussianImageFilter.txx" #include "itkRecursiveSeparableImageFilter.txx" #include "itkReflectImageFilter.txx" #include "itkReflectiveImageRegionConstIterator.txx" #include "itkReflectiveImageRegionIterator.txx" #include "itkRegionOfInterestImageFilter.txx" #include "itkRelabelComponentImageFilter.txx" #include "itkResampleImageFilter.txx" #include "itkRescaleIntensityImageFilter.txx" #include "itkScalarAnisotropicDiffusionFunction.txx" #include "itkScalarConnectedComponentImageFilter.h" #include "itkScalarToArrayCastImageFilter.txx" #include "itkShiftScaleImageFilter.txx" #include "itkShiftScaleInPlaceImageFilter.txx" #include "itkShrinkImageFilter.txx" #include "itkSigmoidImageFilter.h" #include "itkSignedDanielssonDistanceMapImageFilter.txx" #include "itkSimilarityIndexImageFilter.txx" #include "itkSimpleContourExtractorImageFilter.txx" #include "itkSimplexMeshAdaptTopologyFilter.txx" #include "itkSimplexMeshToTriangleMeshFilter.txx" #include "itkSinImageFilter.h" #include "itkSmoothingRecursiveGaussianImageFilter.txx" #include "itkSobelEdgeDetectionImageFilter.txx" #include "itkSparseFieldFourthOrderLevelSetImageFilter.txx" #include "itkSparseFieldLayer.txx" #include "itkSparseFieldLevelSetImageFilter.txx" #include "itkSpatialFunctionImageEvaluatorFilter.txx" #include "itkSpatialObjectToImageFilter.txx" #include "itkSpatialObjectToImageStatisticsCalculator.txx" #include "itkSpatialObjectToPointSetFilter.txx" #include "itkSqrtImageFilter.h" #include "itkSquareImageFilter.h" #include "itkSquaredDifferenceImageFilter.h" #include "itkStatisticsImageFilter.txx" #include "itkStreamingImageFilter.txx" #include "itkSubtractImageFilter.h" #include "itkSymmetricEigenAnalysisImageFilter.h" #include "itkTanImageFilter.h" #include "itkTensorFractionalAnisotropyImageFilter.h" #include "itkTensorRelativeAnisotropyImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.txx" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.txx" #include "itkThresholdLabelerImageFilter.txx" #include "itkTileImageFilter.txx" #include "itkTobogganImageFilter.txx" #include "itkTransformMeshFilter.txx" #include "itkTriangleMeshToBinaryImageFilter.txx" #include "itkTriangleMeshToSimplexMeshFilter.txx" #include "itkTwoOutputExampleImageFilter.txx" #include "itkUnaryFunctorImageFilter.txx" #include "itkVTKImageExport.txx" #include "itkVTKImageExportBase.h" #include "itkVTKImageImport.txx" #include "itkVectorAnisotropicDiffusionFunction.txx" #include "itkVectorCastImageFilter.h" #include "itkVectorConfidenceConnectedImageFilter.txx" #include "itkVectorConnectedComponentImageFilter.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkVectorExpandImageFilter.txx" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientMagnitudeImageFilter.txx" #include "itkVectorGradientNDAnisotropicDiffusionFunction.txx" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkVectorNeighborhoodOperatorImageFilter.txx" #include "itkVectorResampleImageFilter.txx" #include "itkVectorRescaleIntensityImageFilter.txx" #include "itkVotingBinaryHoleFillingImageFilter.txx" #include "itkVotingBinaryImageFilter.txx" #include "itkVotingBinaryIterativeHoleFillingImageFilter.txx" #include "itkWarpImageFilter.txx" #include "itkWarpMeshFilter.txx" #include "itkWarpVectorImageFilter.txx" #include "itkWeightedAddImageFilter.h" #include "itkWhiteTopHatImageFilter.txx" #include "itkWrapPadImageFilter.txx" #include "itkXorImageFilter.h" #include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx" #include "itkZeroCrossingImageFilter.txx" int main ( int , char* ) { return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, 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 "IECore/PrimitiveImplicitSurfaceFunction.h" using namespace IECore; PrimitiveImplicitSurfaceFunction::PrimitiveImplicitSurfaceFunction( PrimitivePtr primitive ) : m_primitive( primitive ) { m_evaluator = PrimitiveEvaluator::create( primitive ); if (! m_evaluator ) { throw InvalidArgumentException( "Cannot create evaluator in PrimitiveImplicitSurfaceFunction" ); } nIt = m_primitive->variables.find("N"); } PrimitiveImplicitSurfaceFunction::~PrimitiveImplicitSurfaceFunction() { } PrimitiveImplicitSurfaceFunction::Value PrimitiveImplicitSurfaceFunction::operator()( const PrimitiveImplicitSurfaceFunction::Point &p ) { PrimitiveEvaluator::ResultPtr result = m_evaluator->createResult(); bool found = m_evaluator->closestPoint( p, result ); if (found) { Point n = result->normal(); // Use shading normal if available if ( nIt != m_primitive->variables.end() ) { n = result->vectorPrimVar( nIt->second ); } /// Compute signed distance from plane, which is defined by closestPoint and closestNormal PrimitiveImplicitSurfaceFunction::Value planeConstant = n.dot( result->point() ); PrimitiveImplicitSurfaceFunction::Value distance = n.dot( p ) - planeConstant; /// \todo This won't always work with meshes, e.g /// If closest point is a vertex or an edge we need to check faces connected to that component too /// \todo We culd fire a ray at closest point and see how many intsections we get? odd implies /// we're inside, even implies outside return distance; } else { return Imath::limits<PrimitiveImplicitSurfaceFunction::Value>::min(); } } PrimitiveImplicitSurfaceFunction::Value PrimitiveImplicitSurfaceFunction::getValue( const Point &p ) { return this->operator()(p); } <commit_msg>Removed todo<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, 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 "IECore/PrimitiveImplicitSurfaceFunction.h" using namespace IECore; PrimitiveImplicitSurfaceFunction::PrimitiveImplicitSurfaceFunction( PrimitivePtr primitive ) : m_primitive( primitive ) { m_evaluator = PrimitiveEvaluator::create( primitive ); if (! m_evaluator ) { throw InvalidArgumentException( "Cannot create evaluator in PrimitiveImplicitSurfaceFunction" ); } nIt = m_primitive->variables.find("N"); } PrimitiveImplicitSurfaceFunction::~PrimitiveImplicitSurfaceFunction() { } PrimitiveImplicitSurfaceFunction::Value PrimitiveImplicitSurfaceFunction::operator()( const PrimitiveImplicitSurfaceFunction::Point &p ) { PrimitiveEvaluator::ResultPtr result = m_evaluator->createResult(); bool found = m_evaluator->closestPoint( p, result ); if (found) { Point n = result->normal(); // Use shading normal if available if ( nIt != m_primitive->variables.end() ) { n = result->vectorPrimVar( nIt->second ); } /// Compute signed distance from plane, which is defined by closestPoint and closestNormal PrimitiveImplicitSurfaceFunction::Value planeConstant = n.dot( result->point() ); PrimitiveImplicitSurfaceFunction::Value distance = n.dot( p ) - planeConstant; return distance; } else { return Imath::limits<PrimitiveImplicitSurfaceFunction::Value>::min(); } } PrimitiveImplicitSurfaceFunction::Value PrimitiveImplicitSurfaceFunction::getValue( const Point &p ) { return this->operator()(p); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAddConstantToImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkAddConstantToImageFilter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkSubtractImageFilter.h" int itkAddConstantToImageFilterTest(int, char* [] ) { // Define the dimension of the images const unsigned int ImageDimension = 3; // Declare the types of the images typedef itk::Image<float, ImageDimension> InputImageType; typedef itk::Image<float, ImageDimension> OutputImageType; typedef float FactorType; // Declare Iterator types apropriated for each image typedef itk::ImageRegionIteratorWithIndex< InputImageType> InputIteratorType; typedef itk::ImageRegionIteratorWithIndex< OutputImageType> OutputIteratorType; // Declare the type of the index to access images typedef itk::Index<ImageDimension> IndexType; // Declare the type of the size typedef itk::Size<ImageDimension> SizeType; // Declare the type of the Region typedef itk::ImageRegion<ImageDimension> RegionType; // Create two images InputImageType::Pointer inputImage = InputImageType::New(); // Define their size, and start index SizeType size; size[0] = 2; size[1] = 2; size[2] = 2; IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; RegionType region; region.SetIndex( start ); region.SetSize( size ); // Initialize Image A inputImage->SetLargestPossibleRegion( region ); inputImage->SetBufferedRegion( region ); inputImage->SetRequestedRegion( region ); inputImage->Allocate(); // Create one iterator for the Input Image (this is a light object) InputIteratorType it( inputImage, inputImage->GetBufferedRegion() ); // Initialize the content of Image A const double pi = atan( 1.0 ) * 4.0; const double value = pi / 6.0; std::cout << "Content of the Input " << std::endl; it.GoToBegin(); while( !it.IsAtEnd() ) { it.Set( value ); std::cout << it.Get() << std::endl; ++it; } // Declare the type for the Log filter typedef itk::AddConstantToImageFilter< InputImageType, FactorType, OutputImageType > FilterType; // Create an ADD Filter FilterType::Pointer filter = FilterType::New(); // Connect the input images filter->SetInput( inputImage ); // Get the Smart Pointer to the Filter Output OutputImageType::Pointer outputImage = filter->GetOutput(); const FactorType factor = 17.0; filter->SetConstant( factor ); // Execute the filter filter->Update(); // Create an iterator for going through the image output OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion()); // Check the content of the result image std::cout << "Verification of the output " << std::endl; const OutputImageType::PixelType epsilon = 1e-6; ot.GoToBegin(); it.GoToBegin(); while( !ot.IsAtEnd() ) { const InputImageType::PixelType input = it.Get(); const OutputImageType::PixelType output = ot.Get(); const float expectedValue = factor + input; std::cout << output << " = "; std::cout << expectedValue << std::endl; if( fabs( expectedValue - output ) > epsilon ) { std::cerr << "Error " << std::endl; std::cerr << " expected Value = " << expectedValue << std::endl; std::cerr << " differs from " << output; std::cerr << " by more than " << epsilon << std::endl; return EXIT_FAILURE; } ++ot; ++it; } return EXIT_SUCCESS; } <commit_msg>COMP: testing kwstyle commit check. Restrict to Insight/Code/Review.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAddConstantToImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkAddConstantToImageFilter.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkSubtractImageFilter.h" int itkAddConstantToImageFilterTest(int, char* [] ) { // Define the dimension of the images const unsigned int ImageDimension = 3; // Declare the types of the images typedef itk::Image<float, ImageDimension> InputImageType; typedef itk::Image<float, ImageDimension> OutputImageType; typedef float FactorType; // Declare Iterator types apropriated for each image typedef itk::ImageRegionIteratorWithIndex< InputImageType> InputIteratorType; typedef itk::ImageRegionIteratorWithIndex< OutputImageType> OutputIteratorType; // Declare the type of the index to access images typedef itk::Index<ImageDimension> IndexType; // Declare the type of the size typedef itk::Size<ImageDimension> SizeType; // Declare the type of the Region typedef itk::ImageRegion<ImageDimension> RegionType; // Create two images InputImageType::Pointer inputImage = InputImageType::New(); // Define their size, and start index SizeType size; size[0] = 2; size[1] = 2; size[2] = 2; IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; RegionType region; region.SetIndex( start ); region.SetSize( size ); // Initialize Image A inputImage->SetLargestPossibleRegion( region ); inputImage->SetBufferedRegion( region ); inputImage->SetRequestedRegion( region ); inputImage->Allocate(); // Create one iterator for the Input Image (this is a light object) InputIteratorType it( inputImage, inputImage->GetBufferedRegion() ); // Initialize the content of Image A const double pi = atan( 1.0 ) * 4.0; const double value = pi / 6.0; std::cout << "Content of the Input " << std::endl; it.GoToBegin(); while( !it.IsAtEnd() ) { it.Set( value ); std::cout << it.Get() << std::endl; ++it; } // Declare the type for the Log filter typedef itk::AddConstantToImageFilter< InputImageType, FactorType, OutputImageType > FilterType; // Create an ADD Filter FilterType::Pointer filter = FilterType::New(); // Connect the input images filter->SetInput( inputImage ); // Get the Smart Pointer to the Filter Output OutputImageType::Pointer outputImage = filter->GetOutput(); const FactorType factor = 17.0; filter->SetConstant( factor ); // Execute the filter filter->Update(); // Create an iterator for going through the image output OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion()); // Check the content of the result image std::cout << "Verification of the output " << std::endl; const OutputImageType::PixelType epsilon = 1e-6; ot.GoToBegin(); it.GoToBegin(); while( !ot.IsAtEnd() ) { const InputImageType::PixelType input = it.Get(); const OutputImageType::PixelType output = ot.Get(); const float expectedValue = factor + input; std::cout << output << " = "; std::cout << expectedValue << std::endl; if( fabs( expectedValue - output ) > epsilon ) { std::cerr << "Error " << std::endl; std::cerr << " expected Value = " << expectedValue << std::endl; std::cerr << " differs from " << output; std::cerr << " by more than " << epsilon << std::endl; return EXIT_FAILURE; } ++ot; ++it; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * Fichier ComportementIA.hpp * \brief Définition du type ComportementIA */ #ifndef COMPORTEMENTIA_HPP #define COMPORTEMENTIA_HPP #include <string> // pour le type std::string #include "ClassesUtiles/Aleatoire.cpp" class ComportementIA{ private : public : ComportementIA();//constructeur de la classe ComportementIA void jouer(Partie p, Joueur j); void choisirPersonnage(Partie p, vector<Personnage> persosDispo); void choisirGainTour(Joueur *j); }; /******************************************************************************/ #include "ComportementIA.cpp" #endif // COMPORTEMENTIA_HPP <commit_msg>fwdgnbfx<commit_after>/** * Fichier ComportementIA.hpp * \brief Définition du type ComportementIA */ #ifndef COMPORTEMENTIA_HPP #define COMPORTEMENTIA_HPP #include <string> // pour le type std::string #include "../../../ClassesUtiles/Aleatoire.cpp" class ComportementIA{ private : public : ComportementIA();//constructeur de la classe ComportementIA void jouer(Partie p, Joueur j); void choisirPersonnage(Partie p, vector<Personnage> persosDispo); void choisirGainTour(Joueur *j); }; /******************************************************************************/ #include "ComportementIA.cpp" #endif // COMPORTEMENTIA_HPP <|endoftext|>
<commit_before>/* * OTRadioLink_Messaging.cpp * * Created on: 18 May 2017 * Author: denzo */ #include "OTRadioLink_Messaging.h" #ifdef ARDUINO #include <Arduino.h> #endif namespace OTRadioLink { /** * @brief Validate, authenticate and decrypt secure frames. * @param msg: message to decrypt * @param outBuf: output buffer * @param decryptedBodyOutSize: Size of decrypted message */ static bool authAndDecodeOTSecureableFrame(const uint8_t * const msg, uint8_t * const outBuf, const uint8_t outBufSize, uint8_t &decryptedBodyOutSize) { const uint8_t msglen = msg[-1]; // Validate structure of header/frame first. // This is quick and checks for insane/dangerous values throughout. SecurableFrameHeader sfh; const uint8_t l = sfh.checkAndDecodeSmallFrameHeader(msg-1, msglen+1); #if 0 && defined(DEBUG) if(!isOK) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX bad secure header"); } #endif // If failed this early and this badly, let someone else try parsing the message buffer... if(0 == l) { return(false); } // Validate integrity of frame (CRC for non-secure, auth for secure). const bool secureFrame = sfh.isSecure(); // Body length after any decryption, etc. // uint8_t receivedBodyLength; XXX // TODO: validate entire message, eg including auth, or CRC if insecure msg rcvd&allowed. // #if defined(ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED) // Allow insecure. // // Only bother to check insecure form (and link code to do so) if insecure RX is allowed. // if(!secureFrame) // { // // Reject if CRC fails. // if(0 == decodeNonsecureSmallFrameRaw(&sfh, msg-1, msglen+1)) // { isOK = false; } // else // { receivedBodyLength = sfh.bl; } // } // #else // ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED // Only allow secure frames by default. if(!secureFrame) { return (false); } // #endif // ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED // Validate (authenticate) and decrypt body of secure frames. uint8_t key[16]; if(secureFrame) { // Get the 'building' key. if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key)) { OTV0P2BASE::serialPrintlnAndFlush(F("!RX key")); return(false); } } uint8_t senderNodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes]; if(secureFrame) { // Look up full ID in associations table, // validate RX message counter, // authenticate and decrypt, // update RX message counter. const bool isOK = (0 != SimpleSecureFrame32or0BodyRXV0p2::getInstance().decodeSecureSmallFrameSafely(&sfh, msg-1, msglen+1, OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleDec_DEFAULT_STATELESS, NULL, key, outBuf, outBufSize, decryptedBodyOutSize, senderNodeID, true)); #if 1 // && defined(DEBUG) if(!isOK) { // Useful brief network diagnostics: a couple of bytes of the claimed ID of rejected frames. // Warnings rather than errors because there may legitimately be multiple disjoint networks. OTV0P2BASE::serialPrintAndFlush(F("?RX auth")); // Missing association or failed auth. if(sfh.getIl() > 0) { OTV0P2BASE::serialPrintAndFlush(' '); OTV0P2BASE::serialPrintAndFlush(sfh.id[0], HEX); } if(sfh.getIl() > 1) { OTV0P2BASE::serialPrintAndFlush(' '); OTV0P2BASE::serialPrintAndFlush(sfh.id[1], HEX); } OTV0P2BASE::serialPrintlnAndFlush(); return (false); } #endif } return(true); // Stop if not OK. } // Returns true on successful frame type match, false if no suitable frame was found/decoded and another parser should be tried. bool decodeAndHandleOTSecureableFrame(Print * /*p*/, const bool /*secure*/, const uint8_t * const msg, OTRadioLink &rt) { const uint8_t msglen = msg[-1]; const uint8_t firstByte = msg[0]; // Buffer for receiving secure frame body. // (Non-secure frame bodies should be read directly from the frame buffer.) uint8_t secBodyBuf[ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE]; uint8_t decryptedBodyOutSize = 0; if(!authAndDecodeOTSecureableFrame(msg, secBodyBuf, sizeof(secBodyBuf), decryptedBodyOutSize)) return false; // If frame still OK to process then switch on frame type. #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("RX seq#"); DEBUG_SERIAL_PRINT(sfh.getSeq()); DEBUG_SERIAL_PRINTLN(); #endif switch(firstByte) // Switch on type. { #if defined(ENABLE_SECURE_RADIO_BEACON) #if defined(ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED) // Allow insecure. // Beacon / Alive frame, non-secure. case OTRadioLink::FTS_ALIVE: { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Beacon nonsecure"); #endif // Ignores any body data. return(true); } #endif // defined(ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED) // Beacon / Alive frame, secure. case OTRadioLink::FTS_ALIVE | 0x80: { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Beacon"); #endif // Does not expect any body data. if(decryptedBodyOutSize != 0) { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("!Beacon data "); DEBUG_SERIAL_PRINT(decryptedBodyOutSize); DEBUG_SERIAL_PRINTLN(); #endif break; } return(true); } #endif // defined(ENABLE_SECURE_RADIO_BEACON) case 'O' | 0x80: // Basic OpenTRV secure frame... { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("'O'"); #endif if(decryptedBodyOutSize < 2) { #if 1 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX O short"); // "O' frame too short. #endif break; } //#ifdef ENABLE_BOILER_HUB // FIXME // // If acting as a boiler hub // // then extract the valve %age and pass to boiler controller // // but use only if valid. // // Ignore explicit call-for-heat flag for now. // const uint8_t percentOpen = secBodyBuf[0]; // if(percentOpen <= 100) { remoteCallForHeatRX(0, percentOpen); } // TODO call for heat valve id not passed in. //#endif // If the frame contains JSON stats // then forward entire secure frame as-is across the secondary radio relay link, // else print directly to console/Serial. if((0 != (secBodyBuf[1] & 0x10)) && (decryptedBodyOutSize > 3) && ('{' == secBodyBuf[2])) { //#ifdef ENABLE_RADIO_SECONDARY_MODULE_AS_RELAY rt.queueToSend(msg, msglen); //#else // Don't write to console/Serial also if relayed. // // Write out the JSON message, inserting synthetic ID/@ and seq/+. // Serial.print(F("{\"@\":\"")); // for(int i = 0; i < OTV0P2BASE::OpenTRV_Node_ID_Bytes; ++i) { Serial.print(senderNodeID[i], HEX); } // Serial.print(F("\",\"+\":")); // Serial.print(sfh.getSeq()); // Serial.print(','); // Serial.write(secBodyBuf + 3, decryptedBodyOutSize - 3); // Serial.println('}'); //// OTV0P2BASE::outputJSONStats(&Serial, secure, msg, msglen); // // Attempt to ensure that trailing characters are pushed out fully. // OTV0P2BASE::flushSerialProductive(); //#endif // ENABLE_RADIO_SECONDARY_MODULE_AS_RELAY } return(true); } // Reject unrecognised type, though fall through potentially to recognise other encodings. default: break; } // Failed to parse; let another handler try. return(false); } } <commit_msg>templated authAndDecrypt<commit_after>/* * OTRadioLink_Messaging.cpp * * Created on: 18 May 2017 * Author: denzo */ #include "OTRadioLink_Messaging.h" #ifdef ARDUINO #include <Arduino.h> #endif namespace OTRadioLink { /** * @brief Validate, authenticate and decrypt secure frames. * @param msg: message to decrypt * @param outBuf: output buffer * @param decryptedBodyOutSize: Size of decrypted message * @param allowInsecureRX: Allows insecure frames to be received. Defaults to false. */ template <bool allowInsecureRX = false> static bool authAndDecodeOTSecureableFrame(const uint8_t * const msg, uint8_t * const outBuf, const uint8_t outBufSize, uint8_t &decryptedBodyOutSize) { const uint8_t msglen = msg[-1]; // Validate structure of header/frame first. // This is quick and checks for insane/dangerous values throughout. SecurableFrameHeader sfh; const uint8_t l = sfh.checkAndDecodeSmallFrameHeader(msg-1, msglen+1); #if 0 && defined(DEBUG) if(!isOK) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX bad secure header"); } #endif // If failed this early and this badly, let someone else try parsing the message buffer... if(0 == l) { return(false); } // Validate integrity of frame (CRC for non-secure, auth for secure). const bool secureFrame = sfh.isSecure(); // TODO: validate entire message, eg including auth, or CRC if insecure msg rcvd&allowed. if(!secureFrame) { if (allowInsecureRX) { // Only bother to check insecure form (and link code to do so) if insecure RX is allowed. // Reject if CRC fails. if(0 == decodeNonsecureSmallFrameRaw(&sfh, msg-1, msglen+1)) { return false; } } else { // Decode fails return (false); } } // #endif // ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED // Validate (authenticate) and decrypt body of secure frames. uint8_t key[16]; if(secureFrame) { // Get the 'building' key. if(!OTV0P2BASE::getPrimaryBuilding16ByteSecretKey(key)) { OTV0P2BASE::serialPrintlnAndFlush(F("!RX key")); return(false); } } uint8_t senderNodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes]; if(secureFrame) { // Look up full ID in associations table, // validate RX message counter, // authenticate and decrypt, // update RX message counter. const bool isOK = (0 != SimpleSecureFrame32or0BodyRXV0p2::getInstance().decodeSecureSmallFrameSafely(&sfh, msg-1, msglen+1, OTAESGCM::fixed32BTextSize12BNonce16BTagSimpleDec_DEFAULT_STATELESS, NULL, key, outBuf, outBufSize, decryptedBodyOutSize, senderNodeID, true)); #if 1 // && defined(DEBUG) if(!isOK) { // Useful brief network diagnostics: a couple of bytes of the claimed ID of rejected frames. // Warnings rather than errors because there may legitimately be multiple disjoint networks. OTV0P2BASE::serialPrintAndFlush(F("?RX auth")); // Missing association or failed auth. if(sfh.getIl() > 0) { OTV0P2BASE::serialPrintAndFlush(' '); OTV0P2BASE::serialPrintAndFlush(sfh.id[0], HEX); } if(sfh.getIl() > 1) { OTV0P2BASE::serialPrintAndFlush(' '); OTV0P2BASE::serialPrintAndFlush(sfh.id[1], HEX); } OTV0P2BASE::serialPrintlnAndFlush(); return (false); } #endif } return(true); // Stop if not OK. } // Returns true on successful frame type match, false if no suitable frame was found/decoded and another parser should be tried. bool decodeAndHandleOTSecureableFrame(Print * /*p*/, const bool /*secure*/, const uint8_t * const msg, OTRadioLink &rt) { const uint8_t msglen = msg[-1]; const uint8_t firstByte = msg[0]; // Buffer for receiving secure frame body. // (Non-secure frame bodies should be read directly from the frame buffer.) uint8_t secBodyBuf[ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE]; uint8_t decryptedBodyOutSize = 0; if(!authAndDecodeOTSecureableFrame(msg, secBodyBuf, sizeof(secBodyBuf), decryptedBodyOutSize)) return false; // If frame still OK to process then switch on frame type. #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("RX seq#"); DEBUG_SERIAL_PRINT(sfh.getSeq()); DEBUG_SERIAL_PRINTLN(); #endif switch(firstByte) // Switch on type. { #if defined(ENABLE_SECURE_RADIO_BEACON) #if defined(ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED) // Allow insecure. // Beacon / Alive frame, non-secure. case OTRadioLink::FTS_ALIVE: { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Beacon nonsecure"); #endif // Ignores any body data. return(true); } #endif // defined(ENABLE_OTSECUREFRAME_INSECURE_RX_PERMITTED) // Beacon / Alive frame, secure. case OTRadioLink::FTS_ALIVE | 0x80: { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("Beacon"); #endif // Does not expect any body data. if(decryptedBodyOutSize != 0) { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("!Beacon data "); DEBUG_SERIAL_PRINT(decryptedBodyOutSize); DEBUG_SERIAL_PRINTLN(); #endif break; } return(true); } #endif // defined(ENABLE_SECURE_RADIO_BEACON) case 'O' | 0x80: // Basic OpenTRV secure frame... { #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("'O'"); #endif if(decryptedBodyOutSize < 2) { #if 1 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("!RX O short"); // "O' frame too short. #endif break; } //#ifdef ENABLE_BOILER_HUB // FIXME // // If acting as a boiler hub // // then extract the valve %age and pass to boiler controller // // but use only if valid. // // Ignore explicit call-for-heat flag for now. // const uint8_t percentOpen = secBodyBuf[0]; // if(percentOpen <= 100) { remoteCallForHeatRX(0, percentOpen); } // TODO call for heat valve id not passed in. //#endif // If the frame contains JSON stats // then forward entire secure frame as-is across the secondary radio relay link, // else print directly to console/Serial. if((0 != (secBodyBuf[1] & 0x10)) && (decryptedBodyOutSize > 3) && ('{' == secBodyBuf[2])) { //#ifdef ENABLE_RADIO_SECONDARY_MODULE_AS_RELAY rt.queueToSend(msg, msglen); //#else // Don't write to console/Serial also if relayed. // // Write out the JSON message, inserting synthetic ID/@ and seq/+. // Serial.print(F("{\"@\":\"")); // for(int i = 0; i < OTV0P2BASE::OpenTRV_Node_ID_Bytes; ++i) { Serial.print(senderNodeID[i], HEX); } // Serial.print(F("\",\"+\":")); // Serial.print(sfh.getSeq()); // Serial.print(','); // Serial.write(secBodyBuf + 3, decryptedBodyOutSize - 3); // Serial.println('}'); //// OTV0P2BASE::outputJSONStats(&Serial, secure, msg, msglen); // // Attempt to ensure that trailing characters are pushed out fully. // OTV0P2BASE::flushSerialProductive(); //#endif // ENABLE_RADIO_SECONDARY_MODULE_AS_RELAY } return(true); } // Reject unrecognised type, though fall through potentially to recognise other encodings. default: break; } // Failed to parse; let another handler try. return(false); } } <|endoftext|>
<commit_before>/** ** \file ast/cloner.hxx ** \brief Template methods of ast::Cloner. */ #ifndef AST_CLONER_HXX # define AST_CLONER_HXX # include <libport/foreach.hh> # include "ast/cloner.hh" namespace ast { template <typename T> T* Cloner::recurse (const T& t) { t.accept (*this); T* res = dynamic_cast<T*> (result_); assert (res); return res; } template <typename T> typename boost::remove_const<T>::type* Cloner::recurse (T* t) { return t ? recurse(*t) : 0; } // args_type can include 0 in its list of args to denote the default // target. So use an iteration that is OK with 0 in arguments. // FIXME: Maybe by default we should reject 0, and overload for the // specific case of args_type. template <typename CollectionType> CollectionType* Cloner::recurse_collection (const CollectionType& c) { CollectionType* res = new CollectionType; foreach (typename CollectionType::const_reference e, c) res->push_back(recurse(e)); return res; } // Specializations to workaround some limitations of ast-cloner-gen. template <> inline symbols_type* Cloner::recurse_collection<symbols_type> (const symbols_type& c) { symbols_type* ret = new symbols_type(); foreach(libport::Symbol* s, c) ret->push_back(new libport::Symbol(*s)); return ret; } } // namespace ast #endif // !AST_CLONER_HXX <commit_msg>Make cloning more resilient.<commit_after>/** ** \file ast/cloner.hxx ** \brief Template methods of ast::Cloner. */ #ifndef AST_CLONER_HXX # define AST_CLONER_HXX # include <libport/foreach.hh> # include "ast/cloner.hh" # include "ast/pretty-printer.hh" namespace ast { template <typename T> T* Cloner::recurse(const T& t) { t.accept(*this); T* res = dynamic_cast<T*>(result_); // We do have situations where t is not null, but result_ is, for // instance when we process a ParametricAst which substitutes a // MetaVar for a target, and the effective target is 0. // // FIXME: We should stop accepting 0 in our tree, this is really // painful and dangerous. passert(t, !result_ || res); return res; } template <typename T> typename boost::remove_const<T>::type* Cloner::recurse (T* t) { return t ? recurse(*t) : 0; } // args_type can include 0 in its list of args to denote the default // target. So use an iteration that is OK with 0 in arguments. // FIXME: Maybe by default we should reject 0, and overload for the // specific case of args_type. template <typename CollectionType> CollectionType* Cloner::recurse_collection (const CollectionType& c) { CollectionType* res = new CollectionType; foreach (typename CollectionType::const_reference e, c) res->push_back(recurse(e)); return res; } // Specializations to workaround some limitations of ast-cloner-gen. template <> inline symbols_type* Cloner::recurse_collection<symbols_type> (const symbols_type& c) { symbols_type* ret = new symbols_type(); foreach(libport::Symbol* s, c) ret->push_back(new libport::Symbol(*s)); return ret; } } // namespace ast #endif // !AST_CLONER_HXX <|endoftext|>
<commit_before>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include "listareaimpl.hh" //#define IFDEBUG(...) do { /*__VA_ARGS__*/ } while (0) #define IFDEBUG(...) __VA_ARGS__ namespace Rapicorn { const PropertyList& ItemList::list_properties() { static Property *properties[] = { MakeProperty (ItemList, browse, _("Browse Mode"), _("Browse selection mode"), "rw"), MakeProperty (ItemList, model, _("Model URL"), _("Resource locator for 1D list model"), "rw:M1"), }; static const PropertyList property_list (properties, Container::list_properties()); return property_list; } static uint n_columns_from_type (const Type &type) { switch (type.storage()) { case NUM: case REAL: case STRING: case ARRAY: case OBJECT: case CHOICE: case TYPE_REFERENCE: case SEQUENCE: return 1; case RECORD: return 1; // FIXME: type.n_fields(); } return 0; } ItemListImpl::ItemListImpl() : m_table (NULL), m_model (NULL), m_hadjustment (NULL), m_vadjustment (NULL), m_n_cols (0), m_browse (true) {} ItemListImpl::~ItemListImpl() { if (m_table->parent()) { this->remove (*m_table); unref (m_table); m_table = NULL; } Model1 *oldmodel = m_model; m_model = NULL; if (oldmodel) unref (oldmodel); } void ItemListImpl::constructed () { if (!m_table) { m_table = Factory::create_item ("Table").interface<Table*>(); ref_sink (m_table); this->add (m_table); } if (!m_model) { Store1 &store = *Store1::create_memory_store (Type::lookup ("String")); for (uint i = 0; i < 20; i++) { Array row; String s; if (i == 10) s = string_printf ("* %u SMALL ITEM (watch scroll direction)", i); else s = string_printf ("|<br/>| <br/>| %u<br/>|<br/>|", i); row[0] = s; for (uint j = 1; j < 4; j++) row[j] = string_printf ("%u-%u", i + 1, j + 1); store.insert (-1, row); } model (store.object_url()); unref (ref_sink (store)); } } void ItemListImpl::hierarchy_changed (Item *old_toplevel) { Item::hierarchy_changed (old_toplevel); if (anchored()) queue_visual_update(); } Adjustment& ItemListImpl::hadjustment () const { if (!m_hadjustment) m_hadjustment = Adjustment::create (0, 0, 1, 0.01, 0.2); return *m_hadjustment; } Adjustment& ItemListImpl::vadjustment () const { if (!m_vadjustment) { m_vadjustment = Adjustment::create (0, 0, 1, 0.01, 0.2); m_vadjustment->sig_value_changed += slot ((Item&) *this, &Item::queue_visual_update); } return *m_vadjustment; } Adjustment* ItemListImpl::get_adjustment (AdjustmentSourceType adj_source, const String &name) { switch (adj_source) { case ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL: return &hadjustment(); case ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL: return &vadjustment(); default: return NULL; } } void ItemListImpl::model (const String &modelurl) { Deletable *obj = from_object_url (modelurl); Model1 *model = dynamic_cast<Model1*> (obj); Model1 *oldmodel = m_model; m_model = model; if (m_model) ref_sink (m_model); if (oldmodel) unref (oldmodel); if (!m_model) m_n_cols = 0; else m_n_cols = n_columns_from_type (m_model->type()); invalidate_model (true, true); } String ItemListImpl::model () const { return m_model ? m_model->object_url() : ""; } void ItemListImpl::invalidate_model (bool invalidate_heights, bool invalidate_widgets) { invalidate(); } void ItemListImpl::visual_update () { layout_list(); } void ItemListImpl::size_request (Requisition &requisition) { bool chspread = false, cvspread = false; if (has_allocatable_child()) { Item &child = get_child(); requisition = child.size_request (); requisition.height = 12 * 5; // FIXME: request single row height if (0) { chspread = child.hspread(); cvspread = child.vspread(); } } set_flag (HSPREAD_CONTAINER, chspread); set_flag (VSPREAD_CONTAINER, cvspread); } void ItemListImpl::size_allocate (Allocation area) { bool need_resize = allocation() != area; allocation (area); if (has_allocatable_child() && need_resize) layout_list(); } void ItemListImpl::cache_row (ListRow *lr) { m_row_cache.push_back (lr); lr->hbox->visible (false); } static uint dbg_cached = 0, dbg_refilled = 0, dbg_created = 0; ListRow* ItemListImpl::create_row (uint64 nthrow) { Array row = m_model->get (nthrow); ListRow *lr = new ListRow(); for (uint i = 0; i < row.count(); i++) { Item *item = ref_sink (&Factory::create_item ("Label")); lr->cols.push_back (item); } IFDEBUG (dbg_created++); lr->hbox = &ref_sink (&Factory::create_item ("HBox"))->interface<HBox>(); lr->hbox->spacing (m_table->col_spacing()); for (uint i = 0; i < lr->cols.size(); i++) lr->hbox->add (lr->cols[i]); m_table->add (lr->hbox); return lr; } void ItemListImpl::fill_row (ListRow *lr, uint64 nthrow) { Array row = m_model->get (nthrow); uint end = MIN (lr->cols.size(), row.count()); for (uint i = 0; i < end; i++) lr->cols[i]->set_property ("markup_text", row[i].string()); } ListRow* ItemListImpl::fetch_row (uint64 row) { bool filled = false; ListRow *lr; RowMap::iterator ri = m_row_map.find (row); if (ri != m_row_map.end()) { lr = ri->second; m_row_map.erase (ri); filled = true; IFDEBUG (dbg_cached++); } else if (m_row_cache.size()) { lr = m_row_cache.back(); m_row_cache.pop_back(); IFDEBUG (dbg_refilled++); } else /* create row */ lr = create_row (row); if (!filled) fill_row (lr, row); lr->hbox->visible (true); return lr; } void ItemListImpl::position_row (ListRow *lr, uint64 visible_slot) { /* List rows increase downwards, table rows increase upwards. * Table layout (table-row:visible-slot:list-row): * *:*: dummy children * etc * 6:2: row[i] * 5:2: row[i]-border * 4:1: row[j] * 3:1: row[j]-border * 2:0: row[k] * 1:0: row[k]-border * 0:*: final row-border */ uint64 tablerow = (visible_slot + 1) * 2; lr->hbox->vposition (tablerow); lr->hbox->vspan (1); } uint64 ItemListImpl::measure_row (ListRow *lr, uint64 *allocation_offset) { if (allocation_offset) { Allocation carea = lr->hbox->allocation(); *allocation_offset = carea.y; return carea.height; } else { Requisition requisition = lr->hbox->size_request(); return requisition.height; } } uint64 ItemListImpl::get_scroll_item (double *row_offsetp, double *pixel_offsetp) { /* scroll position interpretation: * the current slider position is interpreted as a fractional pointer * into the interval [0,count[. so the integer part of the scroll * position will always point at one particular item and the fractional * part is interpreted as an offset into the item's row. */ const double norm_value = 1.0 - m_vadjustment->nvalue(); /* 0..1 scroll position */ const double scroll_value = norm_value * m_model->count(); const int64 scroll_item = MIN (m_model->count() - 1, ifloor (scroll_value)); *row_offsetp = MIN (1.0, scroll_value - scroll_item); *pixel_offsetp = norm_value; return scroll_item; } bool ItemListImpl::need_pixel_scrolling () { /* Scrolling for large models works by interpreting the scroll adjustment * values as [row_index.row_fraction]. From this, a scroll position is * interpolated so that the top of the first row and the bottom of the * last row are aligned with top and bottom of the list view * respectively. * However, for models small enough, so that more scrollbar pixels per * row are available than the size of the smallest row, a "backward" * scrolling effect can be observed, resulting from the list top/bottom * alignment interpolation values progressing faster than row_fraction * increments. * To counteract this effect and for an overall smoother scrolling * behavior, we use pixel scrolling for smaller models, which requires * all rows, visible and invisible rows to be layed out. * In this context, this method is used to draw the distinction between * "large" and "small" models. */ double scroll_pixels_per_row = allocation().height / m_model->count(); double minimum_pixels_per_row = 1 + 3 + 1; /* outer border + minimum font size + inner border */ return scroll_pixels_per_row > minimum_pixels_per_row; } void ItemListImpl::layout_list () { double area_height = MAX (allocation().height, 1); if (!m_model || !m_table || m_model->count() < 1) return; const bool pixel_scrolling = need_pixel_scrolling(); double row_offset, pixel_offset; /* 0..1 */ const uint64 current_item = get_scroll_item (&row_offset, &pixel_offset); RowMap rc; uint64 r, rcmin = current_item, rcmax = current_item; double height_before = area_height, height_after = area_height; IFDEBUG (dbg_cached = dbg_refilled = dbg_created = 0); /* fill rows from scroll_item towards list end */ double accu_height = 0; for (r = current_item; r < uint64 (m_model->count()) && (accu_height <= height_before || pixel_scrolling); r++) { ListRow *lr = fetch_row (r); rc[r] = lr; if (r != current_item) // current may be partially offscreen accu_height += measure_row (lr); rcmax = MAX (rcmax, r); } double avheight = MAX (7, accu_height / MAX (r - current_item, 1)); /* fill rows from list start towards scroll_item */ uint64 rowsteps = CLAMP (iround (height_before / avheight), 1, 17); uint64 first = current_item; accu_height = 0; while (first > 0 && (accu_height <= height_after || pixel_scrolling)) { uint64 last = first; first -= MIN (first, rowsteps); for (r = first; r < last; r++) { ListRow *lr = fetch_row (r); rc[r] = lr; accu_height += measure_row (lr); rcmin = MIN (rcmin, r); } } /* layout visible rows */ if (rc.size()) for (r = rcmin; r <= rcmax; r++) position_row (rc.at (r), rcmax - r); /* clear unused rows */ m_row_map.swap (rc); for (RowMap::iterator ri = rc.begin(); ri != rc.end(); ri++) cache_row (ri->second); /* assign list row coordinates */ if (has_allocatable_child()) { Item &child = get_child(); Requisition requisition = child.size_request(); Allocation carea = allocation(); carea.width = requisition.width; carea.height = requisition.height; child.set_allocation (carea); } /* align scroll item */ if (current_item < uint64 (m_model->count()) && has_allocatable_child()) { const Allocation area = allocation(); Item &child = get_child(); Requisition requisition = child.size_request(); int64 pixel_diff; if (requisition.height <= area.height) pixel_diff = area.height - requisition.height; else if (pixel_scrolling) pixel_diff = - (1.0 - pixel_offset) * (requisition.height - area.height); else /* fractional row scrolling */ { ListRow *lr = m_row_map[current_item]; uint64 row_y, row_height = measure_row (lr, &row_y); // FIXME: add border int64 row_pixel = row_y - area.y + row_height * (1.0 - row_offset); int64 list_pixel = area.height * (1.0 - pixel_offset); pixel_diff = list_pixel - row_pixel; } /* shift rows */ Allocation carea = area; carea.width = requisition.width; carea.height = requisition.height; carea.y += pixel_diff; IFDEBUG (printout ("List: cached=%u refilled=%u created=%u current=%3lld row_offset=%f pixel_offset=%f diff=%lld ps=%d\n", dbg_cached, dbg_refilled, dbg_created, current_item, row_offset, pixel_offset, pixel_diff, pixel_scrolling)); child.set_allocation (carea); } } static const ItemFactory<ItemListImpl> item_list_factory ("Rapicorn::Factory::ItemList"); } // Rapicorn <commit_msg>listarea: cleanup list rows in destructor<commit_after>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include "listareaimpl.hh" //#define IFDEBUG(...) do { /*__VA_ARGS__*/ } while (0) #define IFDEBUG(...) __VA_ARGS__ namespace Rapicorn { const PropertyList& ItemList::list_properties() { static Property *properties[] = { MakeProperty (ItemList, browse, _("Browse Mode"), _("Browse selection mode"), "rw"), MakeProperty (ItemList, model, _("Model URL"), _("Resource locator for 1D list model"), "rw:M1"), }; static const PropertyList property_list (properties, Container::list_properties()); return property_list; } static uint n_columns_from_type (const Type &type) { switch (type.storage()) { case NUM: case REAL: case STRING: case ARRAY: case OBJECT: case CHOICE: case TYPE_REFERENCE: case SEQUENCE: return 1; case RECORD: return 1; // FIXME: type.n_fields(); } return 0; } ItemListImpl::ItemListImpl() : m_table (NULL), m_model (NULL), m_hadjustment (NULL), m_vadjustment (NULL), m_n_cols (0), m_browse (true) {} ItemListImpl::~ItemListImpl() { /* destroy table */ if (m_table->parent()) { this->remove (*m_table); unref (m_table); m_table = NULL; } /* remove model */ Model1 *oldmodel = m_model; m_model = NULL; if (oldmodel) unref (oldmodel); /* purge row map */ RowMap rc; // empty m_row_map.swap (rc); for (RowMap::iterator ri = rc.begin(); ri != rc.end(); ri++) cache_row (ri->second); /* destroy row cache */ while (m_row_cache.size()) { ListRow *lr = m_row_cache.back(); m_row_cache.pop_back(); for (uint i = 0; i < lr->cols.size(); i++) unref (lr->cols[i]); unref (lr->hbox); delete lr; } } void ItemListImpl::constructed () { if (!m_table) { m_table = Factory::create_item ("Table").interface<Table*>(); ref_sink (m_table); this->add (m_table); } if (!m_model) { Store1 &store = *Store1::create_memory_store (Type::lookup ("String")); for (uint i = 0; i < 20; i++) { Array row; String s; if (i == 10) s = string_printf ("* %u SMALL ITEM (watch scroll direction)", i); else s = string_printf ("|<br/>| <br/>| %u<br/>|<br/>|", i); row[0] = s; for (uint j = 1; j < 4; j++) row[j] = string_printf ("%u-%u", i + 1, j + 1); store.insert (-1, row); } model (store.object_url()); unref (ref_sink (store)); } } void ItemListImpl::hierarchy_changed (Item *old_toplevel) { Item::hierarchy_changed (old_toplevel); if (anchored()) queue_visual_update(); } Adjustment& ItemListImpl::hadjustment () const { if (!m_hadjustment) m_hadjustment = Adjustment::create (0, 0, 1, 0.01, 0.2); return *m_hadjustment; } Adjustment& ItemListImpl::vadjustment () const { if (!m_vadjustment) { m_vadjustment = Adjustment::create (0, 0, 1, 0.01, 0.2); m_vadjustment->sig_value_changed += slot ((Item&) *this, &Item::queue_visual_update); } return *m_vadjustment; } Adjustment* ItemListImpl::get_adjustment (AdjustmentSourceType adj_source, const String &name) { switch (adj_source) { case ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL: return &hadjustment(); case ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL: return &vadjustment(); default: return NULL; } } void ItemListImpl::model (const String &modelurl) { Deletable *obj = from_object_url (modelurl); Model1 *model = dynamic_cast<Model1*> (obj); Model1 *oldmodel = m_model; m_model = model; if (m_model) ref_sink (m_model); if (oldmodel) unref (oldmodel); if (!m_model) m_n_cols = 0; else m_n_cols = n_columns_from_type (m_model->type()); invalidate_model (true, true); } String ItemListImpl::model () const { return m_model ? m_model->object_url() : ""; } void ItemListImpl::invalidate_model (bool invalidate_heights, bool invalidate_widgets) { invalidate(); } void ItemListImpl::visual_update () { layout_list(); } void ItemListImpl::size_request (Requisition &requisition) { bool chspread = false, cvspread = false; if (has_allocatable_child()) { Item &child = get_child(); requisition = child.size_request (); requisition.height = 12 * 5; // FIXME: request single row height if (0) { chspread = child.hspread(); cvspread = child.vspread(); } } set_flag (HSPREAD_CONTAINER, chspread); set_flag (VSPREAD_CONTAINER, cvspread); } void ItemListImpl::size_allocate (Allocation area) { bool need_resize = allocation() != area; allocation (area); if (has_allocatable_child() && need_resize) layout_list(); } void ItemListImpl::cache_row (ListRow *lr) { m_row_cache.push_back (lr); lr->hbox->visible (false); } static uint dbg_cached = 0, dbg_refilled = 0, dbg_created = 0; ListRow* ItemListImpl::create_row (uint64 nthrow) { Array row = m_model->get (nthrow); ListRow *lr = new ListRow(); for (uint i = 0; i < row.count(); i++) { Item *item = ref_sink (&Factory::create_item ("Label")); lr->cols.push_back (item); } IFDEBUG (dbg_created++); lr->hbox = &ref_sink (&Factory::create_item ("HBox"))->interface<HBox>(); lr->hbox->spacing (m_table->col_spacing()); for (uint i = 0; i < lr->cols.size(); i++) lr->hbox->add (lr->cols[i]); m_table->add (lr->hbox); return lr; } void ItemListImpl::fill_row (ListRow *lr, uint64 nthrow) { Array row = m_model->get (nthrow); uint end = MIN (lr->cols.size(), row.count()); for (uint i = 0; i < end; i++) lr->cols[i]->set_property ("markup_text", row[i].string()); } ListRow* ItemListImpl::fetch_row (uint64 row) { bool filled = false; ListRow *lr; RowMap::iterator ri = m_row_map.find (row); if (ri != m_row_map.end()) { lr = ri->second; m_row_map.erase (ri); filled = true; IFDEBUG (dbg_cached++); } else if (m_row_cache.size()) { lr = m_row_cache.back(); m_row_cache.pop_back(); IFDEBUG (dbg_refilled++); } else /* create row */ lr = create_row (row); if (!filled) fill_row (lr, row); lr->hbox->visible (true); return lr; } void ItemListImpl::position_row (ListRow *lr, uint64 visible_slot) { /* List rows increase downwards, table rows increase upwards. * Table layout (table-row:visible-slot:list-row): * *:*: dummy children * etc * 6:2: row[i] * 5:2: row[i]-border * 4:1: row[j] * 3:1: row[j]-border * 2:0: row[k] * 1:0: row[k]-border * 0:*: final row-border */ uint64 tablerow = (visible_slot + 1) * 2; lr->hbox->vposition (tablerow); lr->hbox->vspan (1); } uint64 ItemListImpl::measure_row (ListRow *lr, uint64 *allocation_offset) { if (allocation_offset) { Allocation carea = lr->hbox->allocation(); *allocation_offset = carea.y; return carea.height; } else { Requisition requisition = lr->hbox->size_request(); return requisition.height; } } uint64 ItemListImpl::get_scroll_item (double *row_offsetp, double *pixel_offsetp) { /* scroll position interpretation: * the current slider position is interpreted as a fractional pointer * into the interval [0,count[. so the integer part of the scroll * position will always point at one particular item and the fractional * part is interpreted as an offset into the item's row. */ const double norm_value = 1.0 - m_vadjustment->nvalue(); /* 0..1 scroll position */ const double scroll_value = norm_value * m_model->count(); const int64 scroll_item = MIN (m_model->count() - 1, ifloor (scroll_value)); *row_offsetp = MIN (1.0, scroll_value - scroll_item); *pixel_offsetp = norm_value; return scroll_item; } bool ItemListImpl::need_pixel_scrolling () { /* Scrolling for large models works by interpreting the scroll adjustment * values as [row_index.row_fraction]. From this, a scroll position is * interpolated so that the top of the first row and the bottom of the * last row are aligned with top and bottom of the list view * respectively. * However, for models small enough, so that more scrollbar pixels per * row are available than the size of the smallest row, a "backward" * scrolling effect can be observed, resulting from the list top/bottom * alignment interpolation values progressing faster than row_fraction * increments. * To counteract this effect and for an overall smoother scrolling * behavior, we use pixel scrolling for smaller models, which requires * all rows, visible and invisible rows to be layed out. * In this context, this method is used to draw the distinction between * "large" and "small" models. */ double scroll_pixels_per_row = allocation().height / m_model->count(); double minimum_pixels_per_row = 1 + 3 + 1; /* outer border + minimum font size + inner border */ return scroll_pixels_per_row > minimum_pixels_per_row; } void ItemListImpl::layout_list () { double area_height = MAX (allocation().height, 1); if (!m_model || !m_table || m_model->count() < 1) return; const bool pixel_scrolling = need_pixel_scrolling(); double row_offset, pixel_offset; /* 0..1 */ const uint64 current_item = get_scroll_item (&row_offset, &pixel_offset); RowMap rc; uint64 r, rcmin = current_item, rcmax = current_item; double height_before = area_height, height_after = area_height; IFDEBUG (dbg_cached = dbg_refilled = dbg_created = 0); /* fill rows from scroll_item towards list end */ double accu_height = 0; for (r = current_item; r < uint64 (m_model->count()) && (accu_height <= height_before || pixel_scrolling); r++) { ListRow *lr = fetch_row (r); rc[r] = lr; if (r != current_item) // current may be partially offscreen accu_height += measure_row (lr); rcmax = MAX (rcmax, r); } double avheight = MAX (7, accu_height / MAX (r - current_item, 1)); /* fill rows from list start towards scroll_item */ uint64 rowsteps = CLAMP (iround (height_before / avheight), 1, 17); uint64 first = current_item; accu_height = 0; while (first > 0 && (accu_height <= height_after || pixel_scrolling)) { uint64 last = first; first -= MIN (first, rowsteps); for (r = first; r < last; r++) { ListRow *lr = fetch_row (r); rc[r] = lr; accu_height += measure_row (lr); rcmin = MIN (rcmin, r); } } /* layout visible rows */ if (rc.size()) for (r = rcmin; r <= rcmax; r++) position_row (rc.at (r), rcmax - r); /* clear unused rows */ m_row_map.swap (rc); for (RowMap::iterator ri = rc.begin(); ri != rc.end(); ri++) cache_row (ri->second); /* assign list row coordinates */ if (has_allocatable_child()) { Item &child = get_child(); Requisition requisition = child.size_request(); Allocation carea = allocation(); carea.width = requisition.width; carea.height = requisition.height; child.set_allocation (carea); } /* align scroll item */ if (current_item < uint64 (m_model->count()) && has_allocatable_child()) { const Allocation area = allocation(); Item &child = get_child(); Requisition requisition = child.size_request(); int64 pixel_diff; if (requisition.height <= area.height) pixel_diff = area.height - requisition.height; else if (pixel_scrolling) pixel_diff = - (1.0 - pixel_offset) * (requisition.height - area.height); else /* fractional row scrolling */ { ListRow *lr = m_row_map[current_item]; uint64 row_y, row_height = measure_row (lr, &row_y); // FIXME: add border int64 row_pixel = row_y - area.y + row_height * (1.0 - row_offset); int64 list_pixel = area.height * (1.0 - pixel_offset); pixel_diff = list_pixel - row_pixel; } /* shift rows */ Allocation carea = area; carea.width = requisition.width; carea.height = requisition.height; carea.y += pixel_diff; IFDEBUG (printout ("List: cached=%u refilled=%u created=%u current=%3lld row_offset=%f pixel_offset=%f diff=%lld ps=%d\n", dbg_cached, dbg_refilled, dbg_created, current_item, row_offset, pixel_offset, pixel_diff, pixel_scrolling)); child.set_allocation (carea); } } static const ItemFactory<ItemListImpl> item_list_factory ("Rapicorn::Factory::ItemList"); } // Rapicorn <|endoftext|>
<commit_before>#include <iostream> #include <ctime> #include <cstdlib> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include "opencv2/core/core.hpp" using namespace cv; //Mat CalculerContour(Mat& mat1); int main ( int argc,char **argv ) { /*Mat mat1 = imread("image.jpg", 1); char d[12] = {255,0,0,0,255,0,0,0,255,0,0,0}; Mat mat2(2,2,CV_8UC3,d); Mat res = CalculerContour(mat1); imwrite("img.jpg",res);*/ Mat img = imread("pic_init.jpg",0); Mat bin; Mat res; int i = 0; int j = 0; int k = 0; double col; int size_cont; int size_1; int size_2; int size_tot; int medv2; int debv1; int endv1; int b = 0; RNG rng(12345); if(!img.empty()) threshold(img,bin,0,255,THRESH_BINARY_INV+THRESH_OTSU); // Seuil via algo OTSU : convertit une image en une image binaire ("vrai" noir et blanc) else std::cout << "img is empty" << '\n'; imwrite("threshold_im.jpg",bin); std::vector<std::vector<Point> > contours; std::vector<Vec4i> hierarchy; std::vector<Point> cont_eq; std::vector<Point> cont_test; std::vector<Point> cont_eq_1; std::vector<Point> cont_eq_2; std::vector<int> vect_x_1; std::vector<int> vect_x_2; if(!bin.empty()) // findContours(res,contours,hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Recherche des contours des composantes connexes de l'image avec hiérarchie (donc plus long) findContours(bin,contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_TC89_L1); // Recherche des contours des composantes connexes de l'image else std::cout << "bin is empty" << '\n'; /* for(i=0;i>=0;i = hierarchy[i][0]) //Remplissage des contours avec hiérarchie (donc plus long) { Scalar color (rand()%255, rand()%255, rand()%255); drawContours(res,contours,i,color,CV_FILLED, 8, hierarchy); }*/ res = Mat::zeros(bin.size(), CV_8UC3); std::vector<std::vector<Point> > contours_filt; for(i=0; i<contours.size(); i++) { if (contours[i].size() > 100) { contours_filt.push_back(contours[i]); } } size_cont = contours_filt.size(); for(i=0; i<size_cont; i++) { if(b == 0) { for(j=0; j<contours_filt[i].size(); j++) { vect_x_1.push_back(contours_filt[i][j].x); std::sort(vect_x_1.begin(),vect_x_1.end()); } for(k=i+1;k<size_cont;k++) { if(b==0) { for(j=0; j<contours_filt[k].size(); j++) { vect_x_2.push_back(contours_filt[k][j].x); std::sort(vect_x_2.begin(),vect_x_2.end()); } medv2 = vect_x_2[vect_x_2.size()/2]; debv1 = vect_x_1[0]; endv1 = vect_x_1[vect_x_1.size()-1]; std::cout << "i : " << i << '\n'; std::cout << "k : " << k << '\n'; std::cout << "medv2 : " << medv2 << '\n'; std::cout << "debv1 : " << debv1 << '\n'; std::cout << "endv1 : " << endv1 << '\n'; if(medv2 > debv1 && medv2 < endv1) { contours_filt[k].swap(contours_filt[size_cont-2]); contours_filt[i].swap(contours_filt[size_cont-1]); b = 1; } } } } } cont_eq_1 = contours_filt[size_cont-2]; cont_eq_2 = contours_filt[size_cont-1]; size_1 = cont_eq_1.size(); size_2 = cont_eq_2.size(); size_tot = size_1+size_2; for(i=0;i<size_1;i++) { cont_eq.push_back(cont_eq_1.back()); cont_eq_1.pop_back(); } for(i=0;i<size_2;i++) { cont_eq.push_back(cont_eq_2.back()); cont_eq_2.pop_back(); } contours_filt.pop_back(); contours_filt.pop_back(); contours_filt.push_back(cont_eq); std::cout << contours_filt.size() << '\n'; for(i=0; i<contours_filt.size(); i++) // Remplissage des contours { //Rect r = boundingRect(contours[i]); // Rectangle englobant une composante connexe (fonctionnement bizarre) Scalar color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)); //std::cout << contours[i] << '\n'; //std::cout << i << '\n'; //col = rand()&255; std::cout << "couleur : " << color[0]<< " " << color[1]<< " " << color[2]<< '\n'; drawContours(res,contours_filt,i,color,CV_FILLED, 8); } // cvtColor(img,res,CV_BGR2GRAY); /*Canny(img,res,100,200,3); imwrite("threshold_im.jpg",res); RNG rng(12345); findContours(res,contours,hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0,0)); // Recherche des contours des composantes connexes de l'image Mat drawing = Mat::zeros(res.size(), CV_8UC3); for(i=0; i<contours.size(); i++) // Remplissage des contours { Scalar color = Scalar(rand()&255, rand()&255, rand()&255); drawContours(drawing,contours,i,color,2,8,hierarchy,0,Point() ); } */ imwrite("connected_comp.jpg", res); } /* Mat CalculerContour(Mat& mat1) { unsigned char * input = (unsigned char *)(mat1.data); int x_min = 9999; int x_max = -1; int y_min = 9999; int y_max = -1; int b,g,r; for (int i = 0 ; i < mat1.rows ; i++) { //960 for (int j = 0 ; j < 3*mat1.cols ; j = j + 3) { //1280 b = (int)input[3*mat1.cols*i+j]; g = (int)input[3*mat1.cols*i+j+1]; r = (int)input[3*mat1.cols*i+j+2]; if ((b < 90) && (r < 90) && (g < 90)) { x_min = ((x_min > j/3)? j/3 : x_min) ; x_max = ((x_max < j/3)? j/3 : x_max) ; y_min = ((y_min > i)? i : y_min) ; y_max = ((y_max < i)? i : y_max) ; } } } // std::cout << mat1 << '\n'; std::cout << "x_min :" << x_min << " x_max :" << x_max << " y_min : " << y_min << " y_max : " << y_max << '\n'; for (int i = y_min ; i < y_max ; i++) { // 960 for (int j = x_min ; j < 3*x_max ; j = j + 3) { // 1280 input[3*mat1.cols*i+j] = 0; input[3*mat1.cols*i+j+1] = 0; input[3*mat1.cols*i+j+2] = 255; } } Mat ret(Size(1280,960),CV_8UC3, input); return (ret); } */ <commit_msg>C6 : Added : rectangular envelope all around each symbol. Added : One picture extracted for each symbol based on the envelope and on the binary picture.<commit_after>#include <iostream> #include <ctime> #include <cstdlib> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include "opencv2/core/core.hpp" using namespace cv; //Mat CalculerContour(Mat& mat1); int main ( int argc,char **argv ) { /*Mat mat1 = imread("image.jpg", 1); char d[12] = {255,0,0,0,255,0,0,0,255,0,0,0}; Mat mat2(2,2,CV_8UC3,d); Mat res = CalculerContour(mat1); imwrite("img.jpg",res);*/ Mat img = imread("pic_init.jpg",0); Mat bin; Mat bin2; Mat res; Mat rect; Mat subImage; int i = 0; int j = 0; int k = 0; double col; int size_cont; int size_1; int size_2; int size_tot; int medv2; int debv1; int endv1; int b = 0; string name_img = "env_rect_symb_.jpg"; string tmp_str; std::ostringstream convert; Point pt1; Point pt2; std::vector<std::vector<Point> > contours; std::vector<Vec4i> hierarchy; std::vector<Point> cont_eq; std::vector<Point> cont_test; std::vector<Point> cont_eq_1; std::vector<Point> cont_eq_2; std::vector<int> vect_x_1; std::vector<int> vect_x_2; RNG rng(1); if(!img.empty()) threshold(img,bin,0,255,THRESH_BINARY_INV+THRESH_OTSU); // Seuil via algo OTSU : convertit une image en une image binaire ("vrai" noir et blanc) else std::cout << "img is empty" << '\n'; imwrite("threshold_im.jpg",bin); bin2 = bin.clone(); if(!bin.empty()) // findContours(res,contours,hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Recherche des contours des composantes connexes de l'image avec hiérarchie (donc plus long) findContours(bin,contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_TC89_L1); // Recherche des contours des composantes connexes de l'image else std::cout << "bin is empty" << '\n'; /* for(i=0;i>=0;i = hierarchy[i][0]) //Remplissage des contours avec hiérarchie (donc plus long) { Scalar color (rand()%255, rand()%255, rand()%255); drawContours(res,contours,i,color,CV_FILLED, 8, hierarchy); }*/ res = Mat::zeros(bin.size(), CV_8UC3); rect = Mat::zeros(bin.size(), CV_8UC3); std::vector<std::vector<Point> > contours_filt; for(i=0; i<contours.size(); i++) { if (contours[i].size() > 100) { contours_filt.push_back(contours[i]); } } size_cont = contours_filt.size(); for(i=0; i<size_cont; i++) { if(b == 0) { for(j=0; j<contours_filt[i].size(); j++) { vect_x_1.push_back(contours_filt[i][j].x); std::sort(vect_x_1.begin(),vect_x_1.end()); } for(k=i+1;k<size_cont;k++) { if(b==0) { for(j=0; j<contours_filt[k].size(); j++) { vect_x_2.push_back(contours_filt[k][j].x); std::sort(vect_x_2.begin(),vect_x_2.end()); } medv2 = vect_x_2[vect_x_2.size()/2]; debv1 = vect_x_1[0]; endv1 = vect_x_1[vect_x_1.size()-1]; /* std::cout << "i : " << i << '\n'; std::cout << "k : " << k << '\n'; std::cout << "medv2 : " << medv2 << '\n'; std::cout << "debv1 : " << debv1 << '\n'; std::cout << "endv1 : " << endv1 << '\n'; */ if(medv2 > debv1 && medv2 < endv1) { contours_filt[k].swap(contours_filt[size_cont-2]); contours_filt[i].swap(contours_filt[size_cont-1]); b = 1; } } } } } cont_eq_1 = contours_filt[size_cont-2]; cont_eq_2 = contours_filt[size_cont-1]; size_1 = cont_eq_1.size(); size_2 = cont_eq_2.size(); size_tot = size_1+size_2; for(i=0;i<size_1;i++) { cont_eq.push_back(cont_eq_1.back()); cont_eq_1.pop_back(); } for(i=0;i<size_2;i++) { cont_eq.push_back(cont_eq_2.back()); cont_eq_2.pop_back(); } contours_filt.pop_back(); contours_filt.pop_back(); contours_filt.push_back(cont_eq); // std::cout << contours_filt.size() << '\n'; for(i=0; i<contours_filt.size(); i++) // Remplissage des contours { Scalar color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)); drawContours(res,contours_filt,i,color,CV_FILLED, 8); drawContours(rect,contours_filt,i,color,CV_FILLED, 8); pt1 = boundingRect(contours_filt[i]).tl(); pt2 = boundingRect(contours_filt[i]).br(); rectangle(rect,pt1,pt2,color,2,8,0); // Rectangle englobant une composante connexe (fonctionne) convert.str(""); convert << i; tmp_str = convert.str(); name_img.replace(name_img.begin()+13,name_img.begin()+14,tmp_str); std::cout << name_img << '\n'; subImage = Mat(bin2,Rect(pt1,pt2)); imwrite (name_img, subImage); //std::cout << contours[i] << '\n'; //std::cout << i << '\n'; //col = rand()&255; // std::cout << "couleur : " << color[0]<< " " << color[1]<< " " << color[2]<< '\n'; } // cvtColor(img,res,CV_BGR2GRAY); /*Canny(img,res,100,200,3); imwrite("threshold_im.jpg",res); RNG rng(12345); findContours(res,contours,hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0,0)); // Recherche des contours des composantes connexes de l'image Mat drawing = Mat::zeros(res.size(), CV_8UC3); for(i=0; i<contours.size(); i++) // Remplissage des contours { Scalar color = Scalar(rand()&255, rand()&255, rand()&255); drawContours(drawing,contours,i,color,2,8,hierarchy,0,Point() ); } */ imwrite("connected_comp.jpg", res); imwrite("connected_comp_rect.jpg", rect); } /* Mat CalculerContour(Mat& mat1) { unsigned char * input = (unsigned char *)(mat1.data); int x_min = 9999; int x_max = -1; int y_min = 9999; int y_max = -1; int b,g,r; for (int i = 0 ; i < mat1.rows ; i++) { //960 for (int j = 0 ; j < 3*mat1.cols ; j = j + 3) { //1280 b = (int)input[3*mat1.cols*i+j]; g = (int)input[3*mat1.cols*i+j+1]; r = (int)input[3*mat1.cols*i+j+2]; if ((b < 90) && (r < 90) && (g < 90)) { x_min = ((x_min > j/3)? j/3 : x_min) ; x_max = ((x_max < j/3)? j/3 : x_max) ; y_min = ((y_min > i)? i : y_min) ; y_max = ((y_max < i)? i : y_max) ; } } } // std::cout << mat1 << '\n'; std::cout << "x_min :" << x_min << " x_max :" << x_max << " y_min : " << y_min << " y_max : " << y_max << '\n'; for (int i = y_min ; i < y_max ; i++) { // 960 for (int j = x_min ; j < 3*x_max ; j = j + 3) { // 1280 input[3*mat1.cols*i+j] = 0; input[3*mat1.cols*i+j+1] = 0; input[3*mat1.cols*i+j+2] = 255; } } Mat ret(Size(1280,960),CV_8UC3, input); return (ret); } */ <|endoftext|>
<commit_before>// @(#)root/tmva $Id$ // Author: Matt Jachowski /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : TActivationTanh * * Web : http://tmva.sourceforge.net * * * * Description: * * Tanh activation function (sigmoid normalized in [-1,1] for an ANN. * * * * Authors (alphabetical): * * Matt Jachowski <jachowski@stanford.edu> - Stanford University, USA * * * * Copyright (c) 2005: * * CERN, Switzerland * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ /*! \class TMVA::TActivationTanh \ingroup TMVA Tanh activation function for ANN. This really simple implementation uses TFormula and should probably be replaced with something more efficient later. */ #include "TMVA/TActivationTanh.h" #include "TMVA/TActivation.h" #include "TFormula.h" #include "TMath.h" #include "TString.h" #include <iostream> ClassImp(TMVA::TActivationTanh); //////////////////////////////////////////////////////////////////////////////// /// constructor for tanh sigmoid (normalized in [-1,1]) TMVA::TActivationTanh::TActivationTanh() { fFAST=kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// destructor TMVA::TActivationTanh::~TActivationTanh() { } //////////////////////////////////////////////////////////////////////////////// /// a fast tanh approximation Double_t TMVA::TActivationTanh::fast_tanh(Double_t arg){ if (arg > 4.97) return 1; if (arg < -4.97) return -1; float arg2 = arg * arg; float a = arg * (135135.0f + arg2 * (17325.0f + arg2 * (378.0f + arg2))); float b = 135135.0f + arg2 * (62370.0f + arg2 * (3150.0f + arg2 * 28.0f)); return a/b; } //////////////////////////////////////////////////////////////////////////////// /// evaluate the tanh Double_t TMVA::TActivationTanh::Eval(Double_t arg) { return fFAST ? fast_tanh(arg) : TMath::TanH(arg); } //////////////////////////////////////////////////////////////////////////////// /// evaluate the derivative Double_t TMVA::TActivationTanh::EvalDerivative(Double_t arg) { Double_t tmp=Eval(arg); return ( 1-tmp*tmp); } //////////////////////////////////////////////////////////////////////////////// /// get expressions for the tanh and its derivative /// whatever that may be good for ... TString TMVA::TActivationTanh::GetExpression() { TString expr = "tanh(x)\t\t (1-tanh()^2)"; return expr; } //////////////////////////////////////////////////////////////////////////////// /// writes the sigmoid activation function source code void TMVA::TActivationTanh::MakeFunction( std::ostream& fout, const TString& fncName ) { if (fFAST) { fout << "double " << fncName << "(double x) const {" << std::endl; fout << " if (x > 4.97) return 1;" << std::endl; fout << " if (x < -4.97) return -1;" << std::endl; fout << " float x2 = x * x;" << std::endl; fout << " float a = x * (135135.0f + x2 * (17325.0f + x2 * (378.0f + x2)));" << std::endl; fout << " float b = 135135.0f + x2 * (62370.0f + x2 * (3150.0f + x2 * 28.0f));" << std::endl; fout << " return a / b;" << std::endl; fout << "}" << std::endl; } else { fout << "double " << fncName << "(double x) const {" << std::endl; fout << " // hyperbolic tan" << std::endl; fout << " return tanh(x);" << std::endl; fout << "}" << std::endl; } } <commit_msg>review with Kim<commit_after>// @(#)root/tmva $Id$ // Author: Matt Jachowski /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : TActivationTanh * * Web : http://tmva.sourceforge.net * * * * Description: * * Tanh activation function (sigmoid normalized in [-1,1] for an ANN. * * * * Authors (alphabetical): * * Matt Jachowski <jachowski@stanford.edu> - Stanford University, USA * * * * Copyright (c) 2005: * * CERN, Switzerland * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ /*! \class TMVA::TActivationTanh \ingroup TMVA Tanh activation function for ANN. This really simple implementation uses TFormula and should probably be replaced with something more efficient later. */ #include "TMVA/TActivationTanh.h" #include "TMVA/TActivation.h" #include "TFormula.h" #include "TMath.h" #include "TString.h" #include <iostream> ClassImp(TMVA::TActivationTanh); //////////////////////////////////////////////////////////////////////////////// /// constructor for tanh sigmoid (normalized in [-1,1]) TMVA::TActivationTanh::TActivationTanh() { fFAST=kTRUE; } //////////////////////////////////////////////////////////////////////////////// /// destructor TMVA::TActivationTanh::~TActivationTanh() { } //////////////////////////////////////////////////////////////////////////////// /// a fast tanh approximation Double_t TMVA::TActivationTanh::fast_tanh(Double_t arg){ if (arg > 4.97) return 1; if (arg < -4.97) return -1; float arg2 = arg * arg; float a = arg * (135135.0f + arg2 * (17325.0f + arg2 * (378.0f + arg2))); float b = 135135.0f + arg2 * (62370.0f + arg2 * (3150.0f + arg2 * 28.0f)); return a/b; } //////////////////////////////////////////////////////////////////////////////// /// evaluate the tanh Double_t TMVA::TActivationTanh::Eval(Double_t arg) { return fFAST ? fast_tanh(arg) : TMath::TanH(arg); } //////////////////////////////////////////////////////////////////////////////// /// evaluate the derivative Double_t TMVA::TActivationTanh::EvalDerivative(Double_t arg) { Double_t tmp=Eval(arg); return ( 1-tmp*tmp); } //////////////////////////////////////////////////////////////////////////////// /// get expressions for the tanh and its derivative /// whatever that may be good for ... TString TMVA::TActivationTanh::GetExpression() { TString expr = "tanh(x)\t\t (1-tanh()^2)"; return expr; } //////////////////////////////////////////////////////////////////////////////// /// writes the sigmoid activation function source code void TMVA::TActivationTanh::MakeFunction( std::ostream& fout, const TString& fncName ) { if (fFAST) { fout << "double " << fncName << "(double x) const {" << std::endl; fout << " // fast hyperbolic tan approximation" << std::endl; fout << " if (x > 4.97) return 1;" << std::endl; fout << " if (x < -4.97) return -1;" << std::endl; fout << " float x2 = x * x;" << std::endl; fout << " float a = x * (135135.0f + x2 * (17325.0f + x2 * (378.0f + x2)));" << std::endl; fout << " float b = 135135.0f + x2 * (62370.0f + x2 * (3150.0f + x2 * 28.0f));" << std::endl; fout << " return a / b;" << std::endl; fout << "}" << std::endl; } else { fout << "double " << fncName << "(double x) const {" << std::endl; fout << " // hyperbolic tan" << std::endl; fout << " return tanh(x);" << std::endl; fout << "}" << std::endl; } } <|endoftext|>
<commit_before>/* Copyright (c) 2016, 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 <atomic> #include <QJSEngine> #include <QJSValue> #include <QFile> #include <QDir> #include <QTextStream> #include <TWebApplication> #include <TJSContext> #include <TReactComponent> #include "tsystemglobal.h" TReactComponent::TReactComponent(const QString &script) : context(new TJSContext()), jsValue(new QJSValue()), scriptPath(), loadedTime() { init(); load(script); } // TReactComponent::TReactComponent(const QStringList &scripts) // : context(new TJSContext()), jsValue(new QJSValue()) // { // init(); // for (auto &s : scripts) { // load(s); // } // } TReactComponent::~TReactComponent() { delete jsValue; delete context; } void TReactComponent::init() { load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "react.min.js"); load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "react-dom-server.min.js"); } QString TReactComponent::filePath() const { return scriptPath; } bool TReactComponent::load(const QString &scriptFile) { bool ok; if (QFileInfo(scriptFile).suffix().compare("jsx", Qt::CaseInsensitive) == 0) { // Loads JSX file QString program = compileJsxFile(scriptFile); QJSValue res = context->evaluate(program, scriptFile); ok = !res.isError(); } else { ok = context->load(scriptFile); } if (ok) { loadedTime = QDateTime::currentDateTime(); scriptPath = scriptFile; } else { loadedTime = QDateTime(); scriptPath = QString(); } return ok; } QString TReactComponent::renderToString(const QString &component) { QString comp = component.trimmed(); if (!comp.startsWith("<")) { comp.prepend('<'); } if (!comp.endsWith("/>")) { comp.append("/>"); } QString func = QLatin1String("ReactDOMServer.renderToString(") + compileJsx(comp) + QLatin1String(");"); return context->evaluate(func).toString(); } QString TReactComponent::compileJsx(const QString &jsx) { static TJSContext js; static std::atomic<bool> once(false); static QMutex mutex; if (!once.load()) { QMutexLocker locker(&mutex); if (!once.load()) { js.load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "JSXTransformer.js"); once = true; } } QJSValue jscode = js.call("JSXTransformer.transform", QJSValue(jsx)); //tSystemDebug("code:%s", qPrintable(jscode.property("code").toString())); return jscode.property("code").toString(); } QString TReactComponent::compileJsxFile(const QString &fileName) { QFile script(fileName); if (!script.open(QIODevice::ReadOnly)) { // open error tSystemError("TReactComponent open error: %s", qPrintable(fileName)); return false; } QTextStream stream(&script); QString contents = stream.readAll(); script.close(); return compileJsx(contents); } <commit_msg>fix compilation error on OSX.<commit_after>/* Copyright (c) 2016, 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 <atomic> #include <QJSEngine> #include <QJSValue> #include <QFile> #include <QDir> #include <QTextStream> #include <TWebApplication> #include <TJSContext> #include <TReactComponent> #include "tsystemglobal.h" TReactComponent::TReactComponent(const QString &script) : context(new TJSContext()), jsValue(new QJSValue()), scriptPath(), loadedTime() { init(); load(script); } // TReactComponent::TReactComponent(const QStringList &scripts) // : context(new TJSContext()), jsValue(new QJSValue()) // { // init(); // for (auto &s : scripts) { // load(s); // } // } TReactComponent::~TReactComponent() { delete jsValue; delete context; } void TReactComponent::init() { load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "react.min.js"); load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "react-dom-server.min.js"); } QString TReactComponent::filePath() const { return scriptPath; } bool TReactComponent::load(const QString &scriptFile) { bool ok; if (QFileInfo(scriptFile).suffix().compare("jsx", Qt::CaseInsensitive) == 0) { // Loads JSX file QString program = compileJsxFile(scriptFile); QJSValue res = context->evaluate(program, scriptFile); ok = !res.isError(); } else { ok = context->load(scriptFile); } if (ok) { loadedTime = QDateTime::currentDateTime(); scriptPath = scriptFile; } else { loadedTime = QDateTime(); scriptPath = QString(); } return ok; } QString TReactComponent::renderToString(const QString &component) { QString comp = component.trimmed(); if (!comp.startsWith("<")) { comp.prepend('<'); } if (!comp.endsWith("/>")) { comp.append("/>"); } QString func = QLatin1String("ReactDOMServer.renderToString(") + compileJsx(comp) + QLatin1String(");"); return context->evaluate(func).toString(); } QString TReactComponent::compileJsx(const QString &jsx) { static TJSContext js; static std::atomic<bool> once(false); static QMutex mutex; if (!once.load()) { QMutexLocker locker(&mutex); if (!once.load()) { js.load(Tf::app()->webRootPath()+ "script" + QDir::separator() + "JSXTransformer.js"); once = true; } } QJSValue jscode = js.call("JSXTransformer.transform", QJSValue(jsx)); //tSystemDebug("code:%s", qPrintable(jscode.property("code").toString())); return jscode.property("code").toString(); } QString TReactComponent::compileJsxFile(const QString &fileName) { QFile script(fileName); if (!script.open(QIODevice::ReadOnly)) { // open error tSystemError("TReactComponent open error: %s", qPrintable(fileName)); return QString(); } QTextStream stream(&script); QString contents = stream.readAll(); script.close(); return compileJsx(contents); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "tcp_base.h" #include <arpa/inet.h> // for htonl, htons #include <netdb.h> // for addrinfo, freeaddrinfo, getaddrinfo #include <netinet/in.h> // for sockaddr_in, INADDR_ANY, IPPROTO_TCP #include <netinet/tcp.h> // for TCP_NODELAY #include <string.h> // for strerror, memset #include <sys/errno.h> // for __error, errno #include <sys/fcntl.h> // for fcntl, F_GETFL, F_SETFL, O_NONBLOCK #include <sys/socket.h> // for setsockopt, SOL_SOCKET, SO_NOSIGPIPE #include <sysexits.h> // for EX_CONFIG, EX_IOERR #include "io_utils.h" // for close #include "log.h" // for Log, L_ERR, L_OBJ, L_CRIT, L_DEBUG #include "manager.h" // for sig_exit #include "utils.h" // for ignored_errorno BaseTCP::BaseTCP(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref* ev_loop_, unsigned int ev_flags_, int port_, const std::string& description_, int tries_, int flags_) : Worker(manager_, ev_loop_, ev_flags_), port(port_), flags(flags_), description(description_) { bind(tries_); L_OBJ(this, "CREATED BASE TCP!"); } BaseTCP::~BaseTCP() { destroyer(); io::close(sock); sock = -1; L_OBJ(this, "DELETED BASE TCP!"); } void BaseTCP::destroy_impl() { destroyer(); } void BaseTCP::destroyer() { L_CALL(this, "BaseTCP::destroyer()"); if (sock == -1) { return; } ::shutdown(sock, SHUT_RDWR); } void BaseTCP::shutdown_impl(time_t asap, time_t now) { L_CALL(this, "BaseTCP::shutdown_impl(%d, %d)", (int)asap, (int)now); Worker::shutdown_impl(asap, now); destroy(); if (now) { detach(); } } void BaseTCP::bind(int tries) { struct sockaddr_in addr; int tcp_backlog = XAPIAND_TCP_BACKLOG; int optval = 1; if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { L_CRIT(nullptr, "ERROR: %s socket: [%d] %s", description.c_str(), errno, strerror(errno)); sig_exit(-EX_IOERR); } // use setsockopt() to allow multiple listeners connected to the same address if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_REUSEADDR (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } #ifdef SO_NOSIGPIPE if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_NOSIGPIPE (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } #endif if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_KEEPALIVE (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } // struct linger ling = {0, 0}; // if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) { // L_ERR(nullptr, "ERROR: %s setsockopt SO_LINGER (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); // } if (flags & CONN_TCP_DEFER_ACCEPT) { // Activate TCP_DEFER_ACCEPT (dataready's SO_ACCEPTFILTER) for HTTP connections only. // We want the HTTP server to wakeup accepting connections that already have some data // to read; this is not the case for binary servers where the server is the one first // sending data. #ifdef SO_ACCEPTFILTER struct accept_filter_arg af = {"dataready", ""}; if (setsockopt(sock, SOL_SOCKET, SO_ACCEPTFILTER, &af, sizeof(af)) < 0) { L_ERR(nullptr, "ERROR: setsockopt SO_ACCEPTFILTER (sock=%d): [%d] %s", sock, errno, strerror(errno)); } #endif #ifdef TCP_DEFER_ACCEPT int optval = 1; if (setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt TCP_DEFER_ACCEPT (sock=%d): [%d] %s", sock, errno, strerror(errno)); } #endif } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); for (int i = 0; i < tries; ++i, ++port) { addr.sin_port = htons(port); if (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (!ignored_errorno(errno, true, true)) { if (i == tries - 1) break; L_DEBUG(nullptr, "ERROR: %s bind error (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); continue; } } if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (sock=%d): [%d] %s", sock, errno, strerror(errno)); } check_backlog(tcp_backlog); listen(sock, tcp_backlog); return; } L_CRIT(nullptr, "ERROR: %s bind error (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); io::close(sock); sig_exit(-EX_CONFIG); } int BaseTCP::accept() { int client_sock; int optval = 1; struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); if ((client_sock = ::accept(sock, (struct sockaddr *)&addr, &addrlen)) < 0) { if (!ignored_errorno(errno, true, true)) { L_ERR(nullptr, "ERROR: accept error (sock=%d): [%d] %s", sock, errno, strerror(errno)); } return -1; } #ifdef SO_NOSIGPIPE if (setsockopt(client_sock, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt SO_NOSIGPIPE (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } #endif // if (setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) { // L_ERR(nullptr, "ERROR: setsockopt SO_KEEPALIVE (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); // } // struct linger ling = {0, 0}; // if (setsockopt(client_sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) { // L_ERR(nullptr, "ERROR: setsockopt SO_LINGER (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); // } if (flags & CONN_TCP_NODELAY) { if (setsockopt(client_sock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt TCP_NODELAY (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } } if (fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } return client_sock; } void BaseTCP::check_backlog(int) { #if defined(NET_CORE_SOMAXCONN) int name[3] = {CTL_NET, NET_CORE, NET_CORE_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { L_ERR(nullptr, "ERROR: sysctl: [%d] %s", errno, strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { L_ERR(nullptr, "WARNING: The TCP backlog setting of %d cannot be enforced because " "net.core.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #elif defined(KIPC_SOMAXCONN) int name[3] = {CTL_KERN, KERN_IPC, KIPC_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { L_ERR(nullptr, "ERROR: sysctl: [%d] %s", errno, strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { L_ERR(nullptr, "WARNING: The TCP backlog setting of %d cannot be enforced because " "kern.ipc.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #endif } int BaseTCP::connect(int sock_, const std::string& hostname, const std::string& servname) { struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; hints.ai_protocol = 0; struct addrinfo *result; if (getaddrinfo(hostname.c_str(), servname.c_str(), &hints, &result) < 0) { L_ERR(nullptr, "Couldn't resolve host %s:%s", hostname.c_str(), servname.c_str()); io::close(sock_); return -1; } if (::connect(sock_, result->ai_addr, result->ai_addrlen) < 0) { if (!ignored_errorno(errno, true, true)) { L_ERR(nullptr, "ERROR: connect error to %s:%s (sock=%d): [%d] %s", hostname.c_str(), servname.c_str(), sock_, errno, strerror(errno)); freeaddrinfo(result); io::close(sock_); return -1; } } freeaddrinfo(result); if (fcntl(sock_, F_SETFL, fcntl(sock_, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (sock=%d): [%d] %s", sock_, errno, strerror(errno)); } return sock_; } <commit_msg>Print more verbose error about dataready access filter<commit_after>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "tcp_base.h" #include <arpa/inet.h> // for htonl, htons #include <netdb.h> // for addrinfo, freeaddrinfo, getaddrinfo #include <netinet/in.h> // for sockaddr_in, INADDR_ANY, IPPROTO_TCP #include <netinet/tcp.h> // for TCP_NODELAY #include <string.h> // for strerror, memset #include <sys/errno.h> // for __error, errno #include <sys/fcntl.h> // for fcntl, F_GETFL, F_SETFL, O_NONBLOCK #include <sys/socket.h> // for setsockopt, SOL_SOCKET, SO_NOSIGPIPE #include <sysexits.h> // for EX_CONFIG, EX_IOERR #include "io_utils.h" // for close #include "log.h" // for Log, L_ERR, L_OBJ, L_CRIT, L_DEBUG #include "manager.h" // for sig_exit #include "utils.h" // for ignored_errorno BaseTCP::BaseTCP(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref* ev_loop_, unsigned int ev_flags_, int port_, const std::string& description_, int tries_, int flags_) : Worker(manager_, ev_loop_, ev_flags_), port(port_), flags(flags_), description(description_) { bind(tries_); L_OBJ(this, "CREATED BASE TCP!"); } BaseTCP::~BaseTCP() { destroyer(); io::close(sock); sock = -1; L_OBJ(this, "DELETED BASE TCP!"); } void BaseTCP::destroy_impl() { destroyer(); } void BaseTCP::destroyer() { L_CALL(this, "BaseTCP::destroyer()"); if (sock == -1) { return; } ::shutdown(sock, SHUT_RDWR); } void BaseTCP::shutdown_impl(time_t asap, time_t now) { L_CALL(this, "BaseTCP::shutdown_impl(%d, %d)", (int)asap, (int)now); Worker::shutdown_impl(asap, now); destroy(); if (now) { detach(); } } void BaseTCP::bind(int tries) { struct sockaddr_in addr; int tcp_backlog = XAPIAND_TCP_BACKLOG; int optval = 1; if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { L_CRIT(nullptr, "ERROR: %s socket: [%d] %s", description.c_str(), errno, strerror(errno)); sig_exit(-EX_IOERR); } // use setsockopt() to allow multiple listeners connected to the same address if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_REUSEADDR (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } #ifdef SO_NOSIGPIPE if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_NOSIGPIPE (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } #endif if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: %s setsockopt SO_KEEPALIVE (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); } // struct linger ling = {0, 0}; // if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) { // L_ERR(nullptr, "ERROR: %s setsockopt SO_LINGER (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); // } if (flags & CONN_TCP_DEFER_ACCEPT) { // Activate TCP_DEFER_ACCEPT (dataready's SO_ACCEPTFILTER) for HTTP connections only. // We want the HTTP server to wakeup accepting connections that already have some data // to read; this is not the case for binary servers where the server is the one first // sending data. #ifdef SO_ACCEPTFILTER struct accept_filter_arg af = {"dataready", ""}; if (setsockopt(sock, SOL_SOCKET, SO_ACCEPTFILTER, &af, sizeof(af)) < 0) { L_ERR(nullptr, "ERROR: Failed to enable the 'dataready' Accept Filter: setsockopt SO_ACCEPTFILTER (sock=%d): [%d] %s", sock, errno, strerror(errno)); } #endif #ifdef TCP_DEFER_ACCEPT int optval = 1; if (setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt TCP_DEFER_ACCEPT (sock=%d): [%d] %s", sock, errno, strerror(errno)); } #endif } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); for (int i = 0; i < tries; ++i, ++port) { addr.sin_port = htons(port); if (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (!ignored_errorno(errno, true, true)) { if (i == tries - 1) break; L_DEBUG(nullptr, "ERROR: %s bind error (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); continue; } } if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (sock=%d): [%d] %s", sock, errno, strerror(errno)); } check_backlog(tcp_backlog); listen(sock, tcp_backlog); return; } L_CRIT(nullptr, "ERROR: %s bind error (sock=%d): [%d] %s", description.c_str(), sock, errno, strerror(errno)); io::close(sock); sig_exit(-EX_CONFIG); } int BaseTCP::accept() { int client_sock; int optval = 1; struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); if ((client_sock = ::accept(sock, (struct sockaddr *)&addr, &addrlen)) < 0) { if (!ignored_errorno(errno, true, true)) { L_ERR(nullptr, "ERROR: accept error (sock=%d): [%d] %s", sock, errno, strerror(errno)); } return -1; } #ifdef SO_NOSIGPIPE if (setsockopt(client_sock, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt SO_NOSIGPIPE (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } #endif // if (setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) { // L_ERR(nullptr, "ERROR: setsockopt SO_KEEPALIVE (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); // } // struct linger ling = {0, 0}; // if (setsockopt(client_sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) { // L_ERR(nullptr, "ERROR: setsockopt SO_LINGER (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); // } if (flags & CONN_TCP_NODELAY) { if (setsockopt(client_sock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval)) < 0) { L_ERR(nullptr, "ERROR: setsockopt TCP_NODELAY (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } } if (fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (client_sock=%d): [%d] %s", client_sock, errno, strerror(errno)); } return client_sock; } void BaseTCP::check_backlog(int) { #if defined(NET_CORE_SOMAXCONN) int name[3] = {CTL_NET, NET_CORE, NET_CORE_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { L_ERR(nullptr, "ERROR: sysctl: [%d] %s", errno, strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { L_ERR(nullptr, "WARNING: The TCP backlog setting of %d cannot be enforced because " "net.core.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #elif defined(KIPC_SOMAXCONN) int name[3] = {CTL_KERN, KERN_IPC, KIPC_SOMAXCONN}; int somaxconn; size_t somaxconn_len = sizeof(somaxconn); if (sysctl(name, 3, &somaxconn, &somaxconn_len, 0, 0) < 0) { L_ERR(nullptr, "ERROR: sysctl: [%d] %s", errno, strerror(errno)); return; } if (somaxconn > 0 && somaxconn < tcp_backlog) { L_ERR(nullptr, "WARNING: The TCP backlog setting of %d cannot be enforced because " "kern.ipc.somaxconn" " is set to the lower value of %d.\n", tcp_backlog, somaxconn); } #endif } int BaseTCP::connect(int sock_, const std::string& hostname, const std::string& servname) { struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV; hints.ai_protocol = 0; struct addrinfo *result; if (getaddrinfo(hostname.c_str(), servname.c_str(), &hints, &result) < 0) { L_ERR(nullptr, "Couldn't resolve host %s:%s", hostname.c_str(), servname.c_str()); io::close(sock_); return -1; } if (::connect(sock_, result->ai_addr, result->ai_addrlen) < 0) { if (!ignored_errorno(errno, true, true)) { L_ERR(nullptr, "ERROR: connect error to %s:%s (sock=%d): [%d] %s", hostname.c_str(), servname.c_str(), sock_, errno, strerror(errno)); freeaddrinfo(result); io::close(sock_); return -1; } } freeaddrinfo(result); if (fcntl(sock_, F_SETFL, fcntl(sock_, F_GETFL, 0) | O_NONBLOCK) < 0) { L_ERR(nullptr, "ERROR: fcntl O_NONBLOCK (sock=%d): [%d] %s", sock_, errno, strerror(errno)); } return sock_; } <|endoftext|>
<commit_before>#include <sirius.h> using namespace sirius; void init_wf(K_point* kp__, Wave_functions& phi__, int num_bands__, int num_mag_dims__) { std::vector<double> tmp(0xFFFF); for (int i = 0; i < 0xFFFF; i++) { tmp[i] = utils::random<double>(); } phi__.pw_coeffs(0).prime().zero(); //#pragma omp parallel for schedule(static) for (int i = 0; i < num_bands__; i++) { for (int igk_loc = 0; igk_loc < kp__->num_gkvec_loc(); igk_loc++) { /* global index of G+k vector */ int igk = kp__->idxgk(igk_loc); if (igk == 0) { phi__.pw_coeffs(0).prime(igk_loc, i) = 1.0; } if (igk == i + 1) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.5; } if (igk == i + 2) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.25; } if (igk == i + 3) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.125; } phi__.pw_coeffs(0).prime(igk_loc, i) += tmp[(igk + i) & 0xFFFF] * 1e-5; } } if (num_mag_dims__ == 3) { /* make pure spinor up- and dn- wave functions */ phi__.copy_from(device_t::CPU, num_bands__, phi__, 0, 0, 1, num_bands__); } } void test_davidson(cmd_args const& args__) { auto pu = get_device_t(args__.value<std::string>("device", "CPU")); auto pw_cutoff = args__.value<double>("pw_cutoff", 30); auto gk_cutoff = args__.value<double>("gk_cutoff", 10); auto N = args__.value<int>("N", 1); auto mpi_grid = args__.value<std::vector<int>>("mpi_grid", {1, 1}); auto solver = args__.value<std::string>("solver", "lapack"); utils::timer t1("test_davidson|setup"); /* create simulation context */ Simulation_context ctx( "{" " \"parameters\" : {" " \"electronic_structure_method\" : \"pseudopotential\"" " }," " \"control\" : {" " \"verification\" : 0" " }" "}"); /* add a new atom type to the unit cell */ auto& atype = ctx.unit_cell().add_atom_type("Cu"); /* set pseudo charge */ atype.zn(11); /* set radial grid */ atype.set_radial_grid(radial_grid_t::lin_exp, 1000, 0.0, 100.0, 6); /* cutoff at ~1 a.u. */ int icut = atype.radial_grid().index_of(1.0); double rcut = atype.radial_grid(icut); /* create beta radial function */ std::vector<double> beta(icut + 1); std::vector<double> beta1(icut + 1); for (int l = 0; l <= 2; l++) { for (int i = 0; i <= icut; i++) { double x = atype.radial_grid(i); beta[i] = utils::confined_polynomial(x, rcut, l, l + 1, 0); beta1[i] = utils::confined_polynomial(x, rcut, l, l + 2, 0); } /* add radial function for l */ atype.add_beta_radial_function(l, beta); atype.add_beta_radial_function(l, beta1); } /* set local part of potential */ std::vector<double> vloc(atype.radial_grid().num_points()); for (int i = 0; i < atype.radial_grid().num_points(); i++) { //double x = atype.radial_grid(i); vloc[i] = 0.0; //-atype.zn() / (std::exp(-x * (x + 1)) + x); } atype.local_potential(vloc); /* set Dion matrix */ int nbf = atype.num_beta_radial_functions(); matrix<double> dion(nbf, nbf); dion.zero(); //for (int i = 0; i < nbf; i++) { // dion(i, i) = -10.0; //} atype.d_mtrx_ion(dion); /* set atomic density */ std::vector<double> arho(atype.radial_grid().num_points()); for (int i = 0; i < atype.radial_grid().num_points(); i++) { double x = atype.radial_grid(i); arho[i] = 2 * atype.zn() * std::exp(-x * x) * x; } atype.ps_total_charge_density(arho); /* lattice constant */ double a{5}; /* set lattice vectors */ ctx.unit_cell().set_lattice_vectors({{a * N, 0, 0}, {0, a * N, 0}, {0, 0, a * N}}); /* add atoms */ double p = 1.0 / N; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { ctx.unit_cell().add_atom("Cu", {i * p, j * p, k * p}); } } } /* initialize the context */ ctx.set_verbosity(1); ctx.pw_cutoff(pw_cutoff); ctx.gk_cutoff(gk_cutoff); ctx.set_processing_unit(pu); ctx.set_mpi_grid_dims(mpi_grid); ctx.gen_evp_solver_name(solver); ctx.std_evp_solver_name(solver); t1.stop(); ctx.set_verbosity(1); ctx.iterative_solver_tolerance(1e-12); //ctx.set_iterative_solver_type("exact"); ctx.initialize(); Density rho(ctx); rho.initial_density(); rho.zero(); Potential pot(ctx); pot.generate(rho); pot.zero(); for (int r = 0; r < 2; r++) { double vk[] = {0.1, 0.1, 0.1}; K_point kp(ctx, vk, 1.0); kp.initialize(); std::cout << "num_gkvec=" << kp.num_gkvec() << "\n"; for (int i = 0; i < ctx.num_bands(); i++) { kp.band_occupancy(i, 0, 2); } init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); Hamiltonian H(ctx, pot); H.prepare(); Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //for (int i = 0; i < ctx.num_bands(); i++) { // std::cout << "energy[" << i << "]=" << kp.band_energy(i, 0) << "\n"; //} std::vector<double> ekin(kp.num_gkvec()); for (int i = 0; i < kp.num_gkvec(); i++) { ekin[i] = 0.5 * kp.gkvec().gkvec_cart<index_domain_t::global>(i).length2(); } std::sort(ekin.begin(), ekin.end()); for (int i = 0; i < ctx.num_bands(); i++) { printf("%20.16f %20.16f %20.16e\n", ekin[i], kp.band_energy(i, 0), std::abs(ekin[i] - kp.band_energy(i, 0))); } } //ctx.set_iterative_solver_type("davidson"); //Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); //Hamiltonian0 h0(ctx, pot); //auto hk = h0(kp); //// init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); //auto eval = davidson<double_complex>(hk, kp.spinor_wave_functions(), 0, 4, 40, 1e-12, 0, 1e-7, [](int i, int ispn){return 1.0;}, false); //std::vector<double> ekin(kp.num_gkvec()); //for (int i = 0; i < kp.num_gkvec(); i++) { // ekin[i] = 0.5 * kp.gkvec().gkvec_cart<index_domain_t::global>(i).length2(); //} //std::sort(ekin.begin(), ekin.end()); //for (int i = 0; i < ctx.num_bands(); i++) { // printf("%20.16f %20.16f %20.16e\n", ekin[i], eval[i], std::abs(ekin[i] - eval[i])); //} //} //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); // for (int i = 0; i < ctx.num_bands(); i++) { // kp.band_occupancy(i, 0, 2); // } // init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); // Hamiltonian H(ctx, pot); // H.prepare(); // Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //} //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); // for (int i = 0; i < ctx.num_bands(); i++) { // kp.band_occupancy(i, 0, 2); // } // init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); // Hamiltonian H(ctx, pot); // H.prepare(); // Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //} } int main(int argn, char** argv) { cmd_args args(argn, argv, {{"device=", "(string) CPU or GPU"}, {"pw_cutoff=", "(double) plane-wave cutoff for density and potential"}, {"gk_cutoff=", "(double) plane-wave cutoff for wave-functions"}, {"N=", "(int) cell multiplicity"}, {"mpi_grid=", "(int[2]) dimensions of the MPI grid for band diagonalization"}, {"solver=", "eigen-value solver"} }); if (args.exist("help")) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); return 0; } sirius::initialize(1); test_davidson(args); int rank = Communicator::world().rank(); sirius::finalize(); if (!rank) { utils::timer::print(); utils::timer::print_tree(); } } <commit_msg>update test of davidson solver<commit_after>#include <sirius.h> using namespace sirius; void init_wf(K_point* kp__, Wave_functions& phi__, int num_bands__, int num_mag_dims__) { std::vector<double> tmp(0xFFFF); for (int i = 0; i < 0xFFFF; i++) { tmp[i] = utils::random<double>(); } phi__.pw_coeffs(0).prime().zero(); //#pragma omp parallel for schedule(static) for (int i = 0; i < num_bands__; i++) { for (int igk_loc = 0; igk_loc < kp__->num_gkvec_loc(); igk_loc++) { /* global index of G+k vector */ int igk = kp__->idxgk(igk_loc); if (igk == 0) { phi__.pw_coeffs(0).prime(igk_loc, i) = 1.0; } if (igk == i + 1) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.5; } if (igk == i + 2) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.25; } if (igk == i + 3) { phi__.pw_coeffs(0).prime(igk_loc, i) = 0.125; } phi__.pw_coeffs(0).prime(igk_loc, i) += tmp[(igk + i) & 0xFFFF] * 1e-5; } } if (num_mag_dims__ == 3) { /* make pure spinor up- and dn- wave functions */ phi__.copy_from(device_t::CPU, num_bands__, phi__, 0, 0, 1, num_bands__); } } void test_davidson(cmd_args const& args__) { auto pu = get_device_t(args__.value<std::string>("device", "CPU")); auto pw_cutoff = args__.value<double>("pw_cutoff", 30); auto gk_cutoff = args__.value<double>("gk_cutoff", 10); auto N = args__.value<int>("N", 1); auto mpi_grid = args__.value<std::vector<int>>("mpi_grid", {1, 1}); auto solver = args__.value<std::string>("solver", "lapack"); utils::timer t1("test_davidson|setup"); /* create simulation context */ Simulation_context ctx( "{" " \"parameters\" : {" " \"electronic_structure_method\" : \"pseudopotential\"" " }," " \"control\" : {" " \"verification\" : 0" " }" "}"); /* add a new atom type to the unit cell */ auto& atype = ctx.unit_cell().add_atom_type("Cu"); /* set pseudo charge */ atype.zn(11); /* set radial grid */ atype.set_radial_grid(radial_grid_t::lin_exp, 1000, 0.0, 100.0, 6); /* cutoff at ~1 a.u. */ int icut = atype.radial_grid().index_of(1.0); double rcut = atype.radial_grid(icut); /* create beta radial function */ std::vector<double> beta(icut + 1); std::vector<double> beta1(icut + 1); for (int l = 0; l <= 2; l++) { for (int i = 0; i <= icut; i++) { double x = atype.radial_grid(i); beta[i] = utils::confined_polynomial(x, rcut, l, l + 1, 0); beta1[i] = utils::confined_polynomial(x, rcut, l, l + 2, 0); } /* add radial function for l */ atype.add_beta_radial_function(l, beta); atype.add_beta_radial_function(l, beta1); } /* set local part of potential */ std::vector<double> vloc(atype.radial_grid().num_points()); for (int i = 0; i < atype.radial_grid().num_points(); i++) { //double x = atype.radial_grid(i); vloc[i] = 0.0; //-atype.zn() / (std::exp(-x * (x + 1)) + x); } atype.local_potential(vloc); /* set Dion matrix */ int nbf = atype.num_beta_radial_functions(); matrix<double> dion(nbf, nbf); dion.zero(); //for (int i = 0; i < nbf; i++) { // dion(i, i) = -10.0; //} atype.d_mtrx_ion(dion); /* set atomic density */ std::vector<double> arho(atype.radial_grid().num_points()); for (int i = 0; i < atype.radial_grid().num_points(); i++) { double x = atype.radial_grid(i); arho[i] = 2 * atype.zn() * std::exp(-x * x) * x; } atype.ps_total_charge_density(arho); /* lattice constant */ double a{5}; /* set lattice vectors */ ctx.unit_cell().set_lattice_vectors({{a * N, 0, 0}, {0, a * N, 0}, {0, 0, a * N}}); /* add atoms */ double p = 1.0 / N; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { ctx.unit_cell().add_atom("Cu", {i * p, j * p, k * p}); } } } /* initialize the context */ ctx.set_verbosity(1); ctx.pw_cutoff(pw_cutoff); ctx.gk_cutoff(gk_cutoff); ctx.set_processing_unit(pu); ctx.set_mpi_grid_dims(mpi_grid); ctx.gen_evp_solver_name(solver); ctx.std_evp_solver_name(solver); t1.stop(); ctx.set_verbosity(1); ctx.iterative_solver_tolerance(1e-12); //ctx.set_iterative_solver_type("exact"); ctx.initialize(); Density rho(ctx); rho.initial_density(); rho.zero(); Potential pot(ctx); pot.generate(rho); pot.zero(); for (int r = 0; r < 2; r++) { double vk[] = {0.1, 0.1, 0.1}; K_point kp(ctx, vk, 1.0); kp.initialize(); std::cout << "num_gkvec=" << kp.num_gkvec() << "\n"; for (int i = 0; i < ctx.num_bands(); i++) { kp.band_occupancy(i, 0, 2); } init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); Hamiltonian H(ctx, pot); H.prepare(); Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //for (int i = 0; i < ctx.num_bands(); i++) { // std::cout << "energy[" << i << "]=" << kp.band_energy(i, 0) << "\n"; //} std::vector<double> ekin(kp.num_gkvec()); for (int i = 0; i < kp.num_gkvec(); i++) { ekin[i] = 0.5 * kp.gkvec().gkvec_cart<index_domain_t::global>(i).length2(); } std::sort(ekin.begin(), ekin.end()); if (Communicator::world().rank() == 0) { double max_diff = 0; for (int i = 0; i < ctx.num_bands(); i++) { max_diff = std::max(max_diff, std::abs(ekin[i] - kp.band_energy(i, 0))); //printf("%20.16f %20.16f %20.16e\n", ekin[i], kp.band_energy(i, 0), std::abs(ekin[i] - kp.band_energy(i, 0))); } printf("maximum eigen-value difference: %20.16e\n", max_diff); } } //ctx.set_iterative_solver_type("davidson"); //Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); //Hamiltonian0 h0(ctx, pot); //auto hk = h0(kp); //// init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); //auto eval = davidson<double_complex>(hk, kp.spinor_wave_functions(), 0, 4, 40, 1e-12, 0, 1e-7, [](int i, int ispn){return 1.0;}, false); //std::vector<double> ekin(kp.num_gkvec()); //for (int i = 0; i < kp.num_gkvec(); i++) { // ekin[i] = 0.5 * kp.gkvec().gkvec_cart<index_domain_t::global>(i).length2(); //} //std::sort(ekin.begin(), ekin.end()); //for (int i = 0; i < ctx.num_bands(); i++) { // printf("%20.16f %20.16f %20.16e\n", ekin[i], eval[i], std::abs(ekin[i] - eval[i])); //} //} //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); // for (int i = 0; i < ctx.num_bands(); i++) { // kp.band_occupancy(i, 0, 2); // } // init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); // Hamiltonian H(ctx, pot); // H.prepare(); // Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //} //for (int i = 0; i < 1; i++) { // double vk[] = {0.1 * i, 0.1 * i, 0.1 * i}; // K_point kp(ctx, vk, 1.0); // kp.initialize(); // for (int i = 0; i < ctx.num_bands(); i++) { // kp.band_occupancy(i, 0, 2); // } // init_wf(&kp, kp.spinor_wave_functions(), ctx.num_bands(), 0); // Hamiltonian H(ctx, pot); // H.prepare(); // Band(ctx).solve_pseudo_potential<double_complex>(kp, H); //} } int main(int argn, char** argv) { cmd_args args(argn, argv, {{"device=", "(string) CPU or GPU"}, {"pw_cutoff=", "(double) plane-wave cutoff for density and potential"}, {"gk_cutoff=", "(double) plane-wave cutoff for wave-functions"}, {"N=", "(int) cell multiplicity"}, {"mpi_grid=", "(int[2]) dimensions of the MPI grid for band diagonalization"}, {"solver=", "eigen-value solver"} }); if (args.exist("help")) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); return 0; } sirius::initialize(1); test_davidson(args); int rank = Communicator::world().rank(); sirius::finalize(); if (!rank) { utils::timer::print(); utils::timer::print_tree(); } } <|endoftext|>
<commit_before><commit_msg>- Fixed deprecation warning about LoadPlugin().<commit_after><|endoftext|>