<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/dom/StyleSheetCollection.h"

#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleInvalidationAnalysis.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/StyleEngine.h"
#include "core/html/HTMLStyleElement.h"
#include "core/page/Settings.h"

namespace WebCore {

StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
    : m_treeScope(treeScope)
    , m_hadActiveLoadingStylesheet(false)
{
}

void StyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
    if (!node->inDocument())
        return;

    // Until the <body> exists, we have no choice but to compare document positions,
    // since styles outside of the body and head continue to be shunted into the head
    // (and thus can shift to end up before dynamically added DOM content that is also
    // outside the body).
    if (createdByParser && document()->body())
        m_styleSheetCandidateNodes.parserAdd(node);
    else
        m_styleSheetCandidateNodes.add(node);

    if (!isHTMLStyleElement(node))
        return;

    ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode();
    if (!isTreeScopeRoot(scopingNode))
        m_scopingNodesForStyleScoped.add(scopingNode);
}

void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
{
    m_styleSheetCandidateNodes.remove(node);

    if (!isTreeScopeRoot(scopingNode))
        m_scopingNodesForStyleScoped.remove(scopingNode);
}

StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
{
    unsigned newStylesheetCount = newStylesheets.size();
    unsigned oldStylesheetCount = oldStyleSheets.size();
    ASSERT(newStylesheetCount >= oldStylesheetCount);

    unsigned newIndex = 0;
    for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
        if (newIndex >= newStylesheetCount)
            return Reconstruct;
        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
            addedSheets.append(newStylesheets[newIndex]->contents());
            ++newIndex;
            if (newIndex == newStylesheetCount)
                return Reconstruct;
        }
        ++newIndex;
    }
    bool hasInsertions = !addedSheets.isEmpty();
    while (newIndex < newStylesheetCount) {
        addedSheets.append(newStylesheets[newIndex]->contents());
        ++newIndex;
    }
    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
    return hasInsertions ? Reset : Additive;
}

bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
{
    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
    bool hasActiveLoadingStylesheet = false;
    unsigned newStylesheetCount = newStyleSheets.size();
    for (unsigned i = 0; i < newStylesheetCount; ++i) {
        if (newStyleSheets[i]->isLoading())
            hasActiveLoadingStylesheet = true;
    }
    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
        m_hadActiveLoadingStylesheet = false;
        return true;
    }
    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
    return false;
}

void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
{
    styleResolverUpdateType = Reconstruct;
    requiresFullStyleRecalc = true;

    if (activeLoadingStyleSheetLoaded(newStyleSheets))
        return;

    if (updateMode != AnalyzedStyleUpdate)
        return;
    if (!document()->styleResolverIfExists())
        return;

    // Find out which stylesheets are new.
    Vector<StyleSheetContents*> addedSheets;
    if (oldStyleSheets.size() <= newStyleSheets.size()) {
        styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, addedSheets);
    } else {
        StyleResolverUpdateType updateType = compareStyleSheets(newStyleSheets, oldStyleSheets, addedSheets);
        styleResolverUpdateType = updateType != Additive ? updateType : Reset;
    }

    // FIXME: If styleResolverUpdateType is still Reconstruct, we could return early here
    // as destroying the StyleResolver will recalc the whole document anyway?

    // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
    if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
        return;
    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
    if (invalidationAnalysis.dirtiesAllStyle())
        return;
    invalidationAnalysis.invalidateStyle(*document());
    requiresFullStyleRecalc = false;
}

void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
{
    // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner.
    if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
        for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
            styleResolver->resetAuthorStyle(toContainerNode(*it));
    }
    if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
        for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
            styleResolver->resetAuthorStyle(toContainerNode(*it));
    }
    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode()));
}

static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
{
    for (unsigned i = 0; i < sheets.size(); ++i) {
        if (sheets[i]->contents()->usesRemUnits())
            return true;
    }
    return false;
}

void StyleSheetCollection::updateUsesRemUnits()
{
    m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
}

}
<commit_msg>Initialize StyleSheetCollection::m_usesRemUnit.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/dom/StyleSheetCollection.h"

#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleInvalidationAnalysis.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/StyleEngine.h"
#include "core/html/HTMLStyleElement.h"
#include "core/page/Settings.h"

namespace WebCore {

StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
    : m_treeScope(treeScope)
    , m_hadActiveLoadingStylesheet(false)
    , m_usesRemUnits(false)
{
}

void StyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
    if (!node->inDocument())
        return;

    // Until the <body> exists, we have no choice but to compare document positions,
    // since styles outside of the body and head continue to be shunted into the head
    // (and thus can shift to end up before dynamically added DOM content that is also
    // outside the body).
    if (createdByParser && document()->body())
        m_styleSheetCandidateNodes.parserAdd(node);
    else
        m_styleSheetCandidateNodes.add(node);

    if (!isHTMLStyleElement(node))
        return;

    ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode();
    if (!isTreeScopeRoot(scopingNode))
        m_scopingNodesForStyleScoped.add(scopingNode);
}

void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
{
    m_styleSheetCandidateNodes.remove(node);

    if (!isTreeScopeRoot(scopingNode))
        m_scopingNodesForStyleScoped.remove(scopingNode);
}

StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
{
    unsigned newStylesheetCount = newStylesheets.size();
    unsigned oldStylesheetCount = oldStyleSheets.size();
    ASSERT(newStylesheetCount >= oldStylesheetCount);

    unsigned newIndex = 0;
    for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
        if (newIndex >= newStylesheetCount)
            return Reconstruct;
        while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
            addedSheets.append(newStylesheets[newIndex]->contents());
            ++newIndex;
            if (newIndex == newStylesheetCount)
                return Reconstruct;
        }
        ++newIndex;
    }
    bool hasInsertions = !addedSheets.isEmpty();
    while (newIndex < newStylesheetCount) {
        addedSheets.append(newStylesheets[newIndex]->contents());
        ++newIndex;
    }
    // If all new sheets were added at the end of the list we can just add them to existing StyleResolver.
    // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly.
    return hasInsertions ? Reset : Additive;
}

bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets)
{
    // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
    bool hasActiveLoadingStylesheet = false;
    unsigned newStylesheetCount = newStyleSheets.size();
    for (unsigned i = 0; i < newStylesheetCount; ++i) {
        if (newStyleSheets[i]->isLoading())
            hasActiveLoadingStylesheet = true;
    }
    if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
        m_hadActiveLoadingStylesheet = false;
        return true;
    }
    m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
    return false;
}

void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
{
    styleResolverUpdateType = Reconstruct;
    requiresFullStyleRecalc = true;

    if (activeLoadingStyleSheetLoaded(newStyleSheets))
        return;

    if (updateMode != AnalyzedStyleUpdate)
        return;
    if (!document()->styleResolverIfExists())
        return;

    // Find out which stylesheets are new.
    Vector<StyleSheetContents*> addedSheets;
    if (oldStyleSheets.size() <= newStyleSheets.size()) {
        styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, addedSheets);
    } else {
        StyleResolverUpdateType updateType = compareStyleSheets(newStyleSheets, oldStyleSheets, addedSheets);
        styleResolverUpdateType = updateType != Additive ? updateType : Reset;
    }

    // FIXME: If styleResolverUpdateType is still Reconstruct, we could return early here
    // as destroying the StyleResolver will recalc the whole document anyway?

    // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
    if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
        return;
    StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
    if (invalidationAnalysis.dirtiesAllStyle())
        return;
    invalidationAnalysis.invalidateStyle(*document());
    requiresFullStyleRecalc = false;
}

void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
{
    // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner.
    if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) {
        for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it)
            styleResolver->resetAuthorStyle(toContainerNode(*it));
    }
    if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) {
        for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
            styleResolver->resetAuthorStyle(toContainerNode(*it));
    }
    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode()));
}

static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
{
    for (unsigned i = 0; i < sheets.size(); ++i) {
        if (sheets[i]->contents()->usesRemUnits())
            return true;
    }
    return false;
}

void StyleSheetCollection::updateUsesRemUnits()
{
    m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
}

}
<|endoftext|>


<commit_before><commit_msg>Fix linking bug for PLAYING/READY startstop cycle<commit_after><|endoftext|>


<commit_before>/*    Copyright (c) 2010-2012, Delft University of Technology
 *    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 Delft University of Technology nor the names of its contributors
 *        may be used to endorse or promote products derived from this software without specific
 *        prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *    OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      120720    A. Ronse          First creation of the unit test.
 *      120724    K. Kumar          Addition of extensive comments and tests for
 *                                  updateAndGetAcceleration functions.
 *      120821    K. Kumar          Rewrote tests to make use of updated DerivedAccelerationModel
 *                                  class, AnotherDerivedAccelerationModel class, and new TestBody
 *                                  class.
 *
 *    References
 *
 *    Notes:
 *      Test tolerance was set at 5.0e-15 (or 5.0e-7 for floats) instead of epsilon due to
 *      rounding errors in Eigen types with entries over a number of orders of magnitude,
 *      presumably causing the observed larger than epsilon relative differences between
 *      expected and computed values.
 *
 */

#define BOOST_TEST_MAIN

#include <vector>

#include <boost/assign/list_of.hpp>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

#include <Eigen/Core>

#include <TudatCore/Basics/testMacros.h>

#include "Tudat/Astrodynamics/BasicAstrodynamics/accelerationModel.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testAccelerationModels.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testBody.h"

namespace tudat
{
namespace unit_tests
{

using basic_astrodynamics::AccelerationModel;
using basic_astrodynamics::updateAndGetAcceleration;
using boost::assign::list_of;

BOOST_AUTO_TEST_SUITE( test_accelerationModel )

//! Test whether DerivedAccelerationModel (acceleration data type=Eigen::Vector3d) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived3dAccelerationModel )
{
    using basic_astrodynamics::AccelerationModel3dPointer;

    // Shortcuts.
    typedef TestBody< 3, double > TestBody3d;
    typedef boost::shared_ptr< TestBody3d > TestBody3dPointer;
    typedef DerivedAccelerationModel< > DerivedAccelerationModel3d;

    // Create body with initial state and time.
    TestBody3dPointer body = boost::make_shared< TestBody3d >(
                ( Eigen::VectorXd( 6 ) << 1.1, 2.2, 3.3, -0.1, 0.2, 0.3 ).finished( ), 2.0 );

    // Create acceleration model using DerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel3dPointer accelerationModel3d
            = boost::make_shared< DerivedAccelerationModel3d >(
                boost::bind( &TestBody3d::getCurrentPosition, body ),
                boost::bind( &TestBody3d::getCurrentTime, body ) );

    // Declare container of computed accelerations.
    std::vector< Eigen::Vector3d > computedAccelerations( 3 );

    // Get acceleration vector before members are updated.
    computedAccelerations.at( 0 ) = accelerationModel3d->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                -1.1, ( Eigen::VectorXd( 6 )
                        << -0.45, 10.63, -9.81, 0.11, 0.22, 0.33 ).finished( ) );

    // Update acceleration model members.
    accelerationModel3d->updateMembers( );

    // Get acceleration vector, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModel3d->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                4.6, ( Eigen::VectorXd( 6 )
                       << -87.685, 101.44, -1.38, -0.12, 0.23, -0.34 ).finished( ) );

    // Update and get acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModel3d );

    // Set expected accelerations.
    const std::vector< Eigen::Vector3d > expectedAccelerations
            = list_of( Eigen::Vector3d( 1.1, 2.2, 3.3 ) / ( 2.0 * 2.0 ) )
            ( Eigen::Vector3d( -0.45, 10.63, -9.81 ) / ( -1.1 * -1.1 ) )
            ( Eigen::Vector3d( -87.685, 101.44, -1.38 ) / ( 4.6 * 4.6 ) );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        TUDAT_CHECK_MATRIX_BASE( computedAccelerations.at( i ), expectedAccelerations.at( i ) )
                BOOST_CHECK_CLOSE_FRACTION( computedAccelerations.at( i ).coeff( row, col ),
                                   expectedAccelerations.at( i ).coeff( row, col ), 5.0e-15 );
    }
}

//! Test whether AnotherDerivedAccelerationModel (acceleration data type=Eigen::Vector2f) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived2fAccelerationModel )
{
    // NOTE: For this test, it is imperative that the float values are given with the "f"
    // suffix, to ensure that their precision is indeed of float-type.

    // Shortcuts.
    typedef TestBody< 2, float > TestBody2f;
    typedef boost::shared_ptr< TestBody2f > TestBody2fPointer;
    typedef AccelerationModel< Eigen::Vector2f > AccelerationModel2f;
    typedef boost::shared_ptr< AccelerationModel2f > AccelerationModel2fPointer;
    typedef AnotherDerivedAccelerationModel< Eigen::Vector2f, Eigen::Vector2f,
            Eigen::Vector2f, float > AnotherDerivedAccelerationModel2f;

    // Create body with initial state and time.
    TestBody2fPointer body = boost::make_shared< TestBody2f >(
                ( Eigen::VectorXf( 4 ) << -0.3f, 4.5f, 0.1f, 0.2f ).finished( ), -2.3f );

    // Create acceleration model using AnotherDerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel2fPointer accelerationModel2f
            = boost::make_shared< AnotherDerivedAccelerationModel2f >(
                boost::bind( &TestBody2f::getCurrentPosition, body ),
                boost::bind( &TestBody2f::getCurrentVelocity, body ),
                boost::bind( &TestBody2f::getCurrentTime, body ) );

    // Declare container of computed accelerations.
    std::vector< Eigen::Vector2f > computedAccelerations( 3 );

    // Get acceleration vector before members are updated.
    computedAccelerations.at( 0 ) = accelerationModel2f->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                0.33f, ( Eigen::VectorXf( 4 ) << 1.34f, 2.65f, -0.23f, 0.1f ).finished( ) );

    // Update acceleration model members.
    accelerationModel2f->updateMembers( );

    // Get acceleration vector, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModel2f->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                -10.3f, ( Eigen::VectorXf( 4 ) << -98.99f, 1.53f, 1.23f, -0.11f ).finished( ) );

    // Update and get acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModel2f );

    // Set expected accelerations.
    const std::vector< Eigen::Vector2f > expectedAccelerations
            = list_of( 0.5 * Eigen::Vector2f( -0.3f, 4.5f ) / ( 3.2 * ( -2.3f + 3.4 ) * -2.3f )
                       + Eigen::Vector2f( 0.1f, 0.2f ) / -2.3f )
            ( 0.5 * Eigen::Vector2f( 1.34f, 2.65f ) / ( 3.2 * ( 0.33f + 3.4 ) * 0.33f )
              + Eigen::Vector2f( -0.23f, 0.1f ) / 0.33f )
            ( 0.5 * Eigen::Vector2f( -98.99f, 1.53f ) / ( 3.2 * ( -10.3f + 3.4 ) * -10.3f )
              + Eigen::Vector2f( 1.23f, -0.11f ) / -10.3f );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        TUDAT_CHECK_MATRIX_BASE( computedAccelerations.at( i ), expectedAccelerations.at( i ) )
                BOOST_CHECK_CLOSE_FRACTION( computedAccelerations.at( i ).coeff( row, col ),
                                   expectedAccelerations.at( i ).coeff( row, col ), 5.0e-7 );
    }
}

//! Test whether DerivedAccelerationModel (acceleration data type=Eigen::Vector1i) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived1iAccelerationModel )
{
    // Shortcuts.
    typedef TestBody< 1, int > TestBody1i;
    typedef boost::shared_ptr< TestBody1i > TestBody1iPointer;
    typedef AccelerationModel< int > AccelerationModel1i;
    typedef boost::shared_ptr< AccelerationModel1i > AccelerationModel1iPointer;
    typedef DerivedAccelerationModel< int, int, int > DerivedAccelerationModel1i;

    // Create body with initial state and time.
    TestBody1iPointer body = boost::make_shared< TestBody1i >( Eigen::Vector2i( 20, 1 ), 2 );

    // Create acceleration model using DerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel1iPointer accelerationModeli1
            = boost::make_shared< DerivedAccelerationModel1i >(
                boost::bind( ( &TestBody1i::getCurrentPosition ), body ),
                boost::bind( ( &TestBody1i::getCurrentTime ), body ) );

    // Declare container of computed accelerations.
    std::vector< int > computedAccelerations( 3 );

    // Get scalar acceleration before members are updated.
    computedAccelerations.at( 0 ) = accelerationModeli1->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState( -3, Eigen::Vector2i( 90, 3 ) );

    // Update acceleration model members.
    accelerationModeli1->updateMembers( );

    // Get scalar acceleration, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModeli1->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState( 4, Eigen::Vector2i( 16, -4 ) );

    // Update and get scalar acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModeli1 );

    // Set expected accelerations.
    const std::vector< int > expectedAccelerations
            = list_of( 20 / ( 2 * 2 ) )( 90 / ( -3 * -3 ) )( 16 / ( 4 * 4 ) );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        BOOST_CHECK_EQUAL( computedAccelerations.at( i ), expectedAccelerations.at( i ) );
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat
<commit_msg>Fixed Boost::assign bug under MSVC in acceleration model unit test (issue #589).<commit_after>/*    Copyright (c) 2010-2012, Delft University of Technology
 *    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 Delft University of Technology nor the names of its contributors
 *        may be used to endorse or promote products derived from this software without specific
 *        prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *    OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      120720    A. Ronse          First creation of the unit test.
 *      120724    K. Kumar          Addition of extensive comments and tests for
 *                                  updateAndGetAcceleration functions.
 *      120821    K. Kumar          Rewrote tests to make use of updated DerivedAccelerationModel
 *                                  class, AnotherDerivedAccelerationModel class, and new TestBody
 *                                  class.
 *      121123    S. Billemont      Changed boost::assign usage to push_back(), to ensure
 *                                  compatibility with MSVC.
 *
 *    References
 *
 *    Notes:
 *      Test tolerance was set at 5.0e-15 (or 5.0e-7 for floats) instead of epsilon due to
 *      rounding errors in Eigen types with entries over a number of orders of magnitude,
 *      presumably causing the observed larger than epsilon relative differences between
 *      expected and computed values.
 *
 */

#define BOOST_TEST_MAIN

#include <vector>

#include <boost/assign/list_of.hpp>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

#include <Eigen/Core>

#include <TudatCore/Basics/testMacros.h>

#include "Tudat/Astrodynamics/BasicAstrodynamics/accelerationModel.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testAccelerationModels.h"
#include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testBody.h"

namespace tudat
{
namespace unit_tests
{

using basic_astrodynamics::AccelerationModel;
using basic_astrodynamics::updateAndGetAcceleration;
using boost::assign::list_of;

BOOST_AUTO_TEST_SUITE( test_accelerationModel )

//! Test whether DerivedAccelerationModel (acceleration data type=Eigen::Vector3d) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived3dAccelerationModel )
{
    using basic_astrodynamics::AccelerationModel3dPointer;

    // Shortcuts.
    typedef TestBody< 3, double > TestBody3d;
    typedef boost::shared_ptr< TestBody3d > TestBody3dPointer;
    typedef DerivedAccelerationModel< > DerivedAccelerationModel3d;

    // Create body with initial state and time.
    TestBody3dPointer body = boost::make_shared< TestBody3d >(
                ( Eigen::VectorXd( 6 ) << 1.1, 2.2, 3.3, -0.1, 0.2, 0.3 ).finished( ), 2.0 );

    // Create acceleration model using DerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel3dPointer accelerationModel3d
            = boost::make_shared< DerivedAccelerationModel3d >(
                boost::bind( &TestBody3d::getCurrentPosition, body ),
                boost::bind( &TestBody3d::getCurrentTime, body ) );

    // Declare container of computed accelerations.
    std::vector< Eigen::Vector3d > computedAccelerations( 3 );

    // Get acceleration vector before members are updated.
    computedAccelerations.at( 0 ) = accelerationModel3d->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                -1.1, ( Eigen::VectorXd( 6 )
                        << -0.45, 10.63, -9.81, 0.11, 0.22, 0.33 ).finished( ) );

    // Update acceleration model members.
    accelerationModel3d->updateMembers( );

    // Get acceleration vector, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModel3d->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                4.6, ( Eigen::VectorXd( 6 )
                       << -87.685, 101.44, -1.38, -0.12, 0.23, -0.34 ).finished( ) );

    // Update and get acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModel3d );

    // Set expected accelerations.
    std::vector< Eigen::Vector3d > expectedAccelerations;
    expectedAccelerations.push_back( Eigen::Vector3d(   1.1,     2.2,   3.3  ) / (  2.0 *  2.0 ) );
    expectedAccelerations.push_back( Eigen::Vector3d(  -0.45,   10.63, -9.81 ) / ( -1.1 * -1.1 ) );
    expectedAccelerations.push_back( Eigen::Vector3d( -87.685, 101.44, -1.38 ) / (  4.6 *  4.6 ) );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        TUDAT_CHECK_MATRIX_BASE( computedAccelerations.at( i ), expectedAccelerations.at( i ) )
                BOOST_CHECK_CLOSE_FRACTION( computedAccelerations.at( i ).coeff( row, col ),
                                   expectedAccelerations.at( i ).coeff( row, col ), 5.0e-15 );
    }
}

//! Test whether AnotherDerivedAccelerationModel (acceleration data type=Eigen::Vector2f) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived2fAccelerationModel )
{
    // NOTE: For this test, it is imperative that the float values are given with the "f"
    // suffix, to ensure that their precision is indeed of float-type.

    // Shortcuts.
    typedef TestBody< 2, float > TestBody2f;
    typedef boost::shared_ptr< TestBody2f > TestBody2fPointer;
    typedef AccelerationModel< Eigen::Vector2f > AccelerationModel2f;
    typedef boost::shared_ptr< AccelerationModel2f > AccelerationModel2fPointer;
    typedef AnotherDerivedAccelerationModel< Eigen::Vector2f, Eigen::Vector2f,
            Eigen::Vector2f, float > AnotherDerivedAccelerationModel2f;

    // Create body with initial state and time.
    TestBody2fPointer body = boost::make_shared< TestBody2f >(
                ( Eigen::VectorXf( 4 ) << -0.3f, 4.5f, 0.1f, 0.2f ).finished( ), -2.3f );

    // Create acceleration model using AnotherDerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel2fPointer accelerationModel2f
            = boost::make_shared< AnotherDerivedAccelerationModel2f >(
                boost::bind( &TestBody2f::getCurrentPosition, body ),
                boost::bind( &TestBody2f::getCurrentVelocity, body ),
                boost::bind( &TestBody2f::getCurrentTime, body ) );

    // Declare container of computed accelerations.
    std::vector< Eigen::Vector2f > computedAccelerations( 3 );

    // Get acceleration vector before members are updated.
    computedAccelerations.at( 0 ) = accelerationModel2f->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                0.33f, ( Eigen::VectorXf( 4 ) << 1.34f, 2.65f, -0.23f, 0.1f ).finished( ) );

    // Update acceleration model members.
    accelerationModel2f->updateMembers( );

    // Get acceleration vector, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModel2f->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState(
                -10.3f, ( Eigen::VectorXf( 4 ) << -98.99f, 1.53f, 1.23f, -0.11f ).finished( ) );

    // Update and get acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModel2f );

    // Set expected accelerations.
    std::vector< Eigen::Vector2f > expectedAccelerations;
    expectedAccelerations.push_back( 0.5 * Eigen::Vector2f( -0.3f, 4.5f )
                                     / ( 3.2 * ( -2.3f + 3.4 ) * -2.3f )
                                     + Eigen::Vector2f( 0.1f, 0.2f ) / -2.3f );
    expectedAccelerations.push_back( 0.5 * Eigen::Vector2f( 1.34f, 2.65f )
                                     / ( 3.2 * ( 0.33f + 3.4 ) * 0.33f )
                                     + Eigen::Vector2f( -0.23f, 0.1f ) / 0.33f );
    expectedAccelerations.push_back( 0.5 * Eigen::Vector2f( -98.99f, 1.53f )
                                     / ( 3.2 * ( -10.3f + 3.4 ) * -10.3f )
                                     + Eigen::Vector2f( 1.23f, -0.11f ) / -10.3f );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        TUDAT_CHECK_MATRIX_BASE( computedAccelerations.at( i ), expectedAccelerations.at( i ) )
                BOOST_CHECK_CLOSE_FRACTION( computedAccelerations.at( i ).coeff( row, col ),
                                   expectedAccelerations.at( i ).coeff( row, col ), 5.0e-7 );
    }
}

//! Test whether DerivedAccelerationModel (acceleration data type=Eigen::Vector1i) functions
//! correctly.
BOOST_AUTO_TEST_CASE( test_derived1iAccelerationModel )
{
    // Shortcuts.
    typedef TestBody< 1, int > TestBody1i;
    typedef boost::shared_ptr< TestBody1i > TestBody1iPointer;
    typedef AccelerationModel< int > AccelerationModel1i;
    typedef boost::shared_ptr< AccelerationModel1i > AccelerationModel1iPointer;
    typedef DerivedAccelerationModel< int, int, int > DerivedAccelerationModel1i;

    // Create body with initial state and time.
    TestBody1iPointer body = boost::make_shared< TestBody1i >( Eigen::Vector2i( 20, 1 ), 2 );

    // Create acceleration model using DerivedAccelerationModel class, and pass pointers to
    // functions in body.
    AccelerationModel1iPointer accelerationModeli1
            = boost::make_shared< DerivedAccelerationModel1i >(
                boost::bind( ( &TestBody1i::getCurrentPosition ), body ),
                boost::bind( ( &TestBody1i::getCurrentTime ), body ) );

    // Declare container of computed accelerations.
    std::vector< int > computedAccelerations( 3 );

    // Get scalar acceleration before members are updated.
    computedAccelerations.at( 0 ) = accelerationModeli1->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState( -3, Eigen::Vector2i( 90, 3 ) );

    // Update acceleration model members.
    accelerationModeli1->updateMembers( );

    // Get scalar acceleration, now after members have been updated.
    computedAccelerations.at( 1 ) = accelerationModeli1->getAcceleration( );

    // Update time and state.
    body->setCurrentTimeAndState( 4, Eigen::Vector2i( 16, -4 ) );

    // Update and get scalar acceleration with single function.
    computedAccelerations.at( 2 ) = updateAndGetAcceleration( accelerationModeli1 );

    // Set expected accelerations.
    const std::vector< int > expectedAccelerations
            = list_of( 20 / ( 2 * 2 ) )( 90 / ( -3 * -3 ) )( 16 / ( 4 * 4 ) );

    // Check that the acceleration vectors before and after the update match expected values.
    for ( unsigned int i = 0; i < computedAccelerations.size( ); i++ )
    {
        BOOST_CHECK_EQUAL( computedAccelerations.at( i ), expectedAccelerations.at( i ) );
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat
<|endoftext|>


<commit_before><commit_msg>Only call gtk_window_present on an alert dialog if the activation state of the window is changing to active.  The signal gets sent even when windows are going inactive (to make the frame light blue), but we only want to do anything if the window is trying to become active.<commit_after><|endoftext|>


<commit_before>#include "../include/sentry.h"
#include <iostream>
#include <cstdlib>
#include <wiringPi.h>

using namespace std;

int Sentry::setup(){
  int distance;
  string alarm;
  string distance;

  cout<<"Enter a Distance: ";
  getline(cin,distance);
  cout<<"Set Alarm? (y/n): ";
  getline(cin,alarm);
  _alarm = alarm == "y";
  cout<<"\nEmail (Leave Blank for No Email): ";
  getline(cin,_email);

  cout<<"\nArming in 10 seconds"<<endl;
  delay(10000);
  cout<<"Armed"<<endl;

  return stoi(distance);;
}

void Sentry::objectDetected(int distance){
  cout<<"An Object Has Been Detected Within " + to_string(distance)+" Inches"<<endl;
  if(_email.size()>0) sendEmail("An Object Has Been Detected Within " + to_string(distance)+" Inches");
  if(_alarm) alarm();
  delay(300000);
}

void Sentry::deviceMoved(){
  cout<<"The Device Has Been Moved"<<endl;
  if(_email.size()>0) sendEmail("The Device Has Been Moved");
  if(_alarm) alarm();
  delay(300000);
}

void Sentry::alarm(){
  for(int i=0;i<4;++i){
    cout << '\a';
    delay(250);
  }
}

void Sentry::sendEmail(std::string message){
  string command = "echo \""+ message +"\" | mail -s \"Sentry Bot Event\" " + _email;
  system(command.c_str());
}
<commit_msg>fixed stoi<commit_after>#include "../include/sentry.h"
#include <iostream>
#include <cstdlib>
#include <wiringPi.h>
#include <string>

using namespace std;

int Sentry::setup(){
  //int distance;
  string alarm;
  string distance;

  cout<<"Enter a Distance: ";
  getline(cin,distance);
  cout<<"Set Alarm? (y/n): ";
  getline(cin,alarm);
  _alarm = alarm == "y";
  cout<<"\nEmail (Leave Blank for No Email): ";
  getline(cin,_email);

  cout<<"\nArming in 10 seconds"<<endl;
  delay(10000);
  cout<<"Armed"<<endl;

  return stoi(distance);
}

void Sentry::objectDetected(int distance){
  cout<<"An Object Has Been Detected Within " + to_string(distance)+" Inches"<<endl;
  if(_email.size()>0) sendEmail("An Object Has Been Detected Within " + to_string(distance)+" Inches");
  if(_alarm) alarm();
  delay(300000);
}

void Sentry::deviceMoved(){
  cout<<"The Device Has Been Moved"<<endl;
  if(_email.size()>0) sendEmail("The Device Has Been Moved");
  if(_alarm) alarm();
  delay(300000);
}

void Sentry::alarm(){
  for(int i=0;i<4;++i){
    cout << '\a';
    delay(250);
  }
}

void Sentry::sendEmail(std::string message){
  string command = "echo \""+ message +"\" | mail -s \"Sentry Bot Event\" " + _email;
  system(command.c_str());
}
<|endoftext|>


<commit_before>/** \file    extract_referenced_author_records.cc
 *  \brief   Selects referenced author records from a collection of authority records.
 *  \author  Dr. Johannes Ruscheinski
 *
 *  Copyright (C) 2018, Library of the University of Tübingen
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <cctype>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "Url.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname
              << " title_records authority_records referenced_author_records [beacon_list1 beacon_list2 .. beacon_listN]\n";
    std::exit(EXIT_FAILURE);
}

void ExtractAuthorPPN(const MARC::Record &record, const std::string &tag, std::unordered_set<std::string> * const referenced_author_ppns) {
    for (const auto &field : record.getTagRange(tag)) {
        for (const auto &subfield : field.getSubfields()) {
            if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)"))
                referenced_author_ppns->emplace(subfield.value_.substr(__builtin_strlen("(DE-576)")));
        }
    }
}

void CollectAuthorPPNs(MARC::Reader * const title_reader, std::unordered_set<std::string> * const referenced_author_ppns) {
    while (const auto record = title_reader->read()) {
        ExtractAuthorPPN(record, "100", referenced_author_ppns);
        ExtractAuthorPPN(record, "400", referenced_author_ppns);
        ExtractAuthorPPN(record, "700", referenced_author_ppns);
    }

    LOG_INFO("extracted " + std::to_string(referenced_author_ppns->size()) + " referenced author PPN's.");
}

std::string NameFromURL(const std::string &url_string) {
    const Url url(url_string);
    std::string name(url.getAuthority());
    if (StringUtil::StartsWith(name, "www.", /* ignore_case = */true))
        name = name.substr(__builtin_strlen("www."));
    const auto last_dot_pos(name.rfind('.'));
    if (last_dot_pos != std::string::npos)
        name.resize(last_dot_pos);
    StringUtil::Map(&name, '.', ' ');

    // Convert the first letter of each "word" to uppercase:
    bool first_char_of_word(true);
    for (auto &ch : name) {
        if (first_char_of_word)
            ch = std::toupper(ch);
        first_char_of_word = ch == ' ';
    }

    return name;
}

void CollectBeaconLinks(const std::string &beacon_filename,
                        std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> * const gnd_numbers_to_beacon_links_map)
{
    const auto input(FileUtil::OpenInputFileOrDie(beacon_filename));
    std::string url_prefix, institution_name;
    while (not input->eof()) {
        std::string line;
        input->getline(&line);
        StringUtil::TrimWhite(&line);
        if (unlikely(line.empty()))
            continue;
        if (unlikely(line[0] == '#')) {
            if (StringUtil::StartsWith(line, "#TARGET:")) {
                line = StringUtil::TrimWhite(line.substr(__builtin_strlen("#TARGET:")));
                if (not StringUtil::EndsWith(line, "{ID}"))
                    LOG_ERROR("Bad TARGET line in \"" + beacon_filename + "\"!");
                url_prefix = line.substr(0, line.length() - __builtin_strlen("{ID}"));
                institution_name = NameFromURL(url_prefix);
            }
        } else { // Probably a GND number.
            auto gnd_number_and_beacon_links(gnd_numbers_to_beacon_links_map->find(line));
            if (gnd_number_and_beacon_links == gnd_numbers_to_beacon_links_map->end())
                (*gnd_numbers_to_beacon_links_map)[line] =
                    std::set<std::pair<std::string, std::string>>({ std::make_pair(institution_name, url_prefix + line) });
            else
                gnd_number_and_beacon_links->second.emplace(std::make_pair(institution_name, url_prefix + line));
        }
    }
}

void FilterAuthorityRecords(
    MARC::Reader * const authority_reader, MARC::Writer * const authority_writer,
    const std::unordered_set<std::string> &referenced_author_ppns,
    const std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> &gnd_numbers_to_beacon_links_map)
{
    unsigned count(0), gnd_tagged_count(0);
    while (auto record = authority_reader->read()) {
        if (referenced_author_ppns.find(record.getControlNumber()) != referenced_author_ppns.cend()) {
            std::string gnd_number;
            if (MARC::GetGNDCode(record, &gnd_number)) {
                const auto gnd_number_and_beacon_links(gnd_numbers_to_beacon_links_map.find(gnd_number));
                if (gnd_number_and_beacon_links != gnd_numbers_to_beacon_links_map.cend()) {
                    ++gnd_tagged_count;
                    for (const auto &beacon_link : gnd_number_and_beacon_links->second)
                        record.insertField("BEA", { { 'a', beacon_link.first }, { 'u', beacon_link.second } });
                }
            }

            authority_writer->write(record);
            ++count;
        }
    }

    LOG_INFO("identified " + std::to_string(count) + " referenced author records.");
    LOG_INFO("tagged " + std::to_string(gnd_tagged_count) + " author records with beacon links.");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    if (argc < 4)
        Usage();

    const std::string title_records_filename(argv[1]);
    const std::string authority_records_filename(argv[2]);
    const std::string referenced_author_records_filename(argv[3]);

    if (unlikely(title_records_filename == referenced_author_records_filename))
        LOG_ERROR("Title input file name equals authority output file name!");
    if (unlikely(authority_records_filename == referenced_author_records_filename))
        LOG_ERROR("Authority data input file name equals authority output file name!");

    auto title_reader(MARC::Reader::Factory(title_records_filename));
    auto authority_reader(MARC::Reader::Factory(authority_records_filename));
    auto authority_writer(MARC::Writer::Factory(referenced_author_records_filename));

    try {
        std::unordered_set<std::string> referenced_author_ppns;
        CollectAuthorPPNs(title_reader.get(), &referenced_author_ppns);

        std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> gnd_numbers_to_beacon_links_map;
        for (int arg_no(4); arg_no < argc; ++arg_no)
            CollectBeaconLinks(argv[arg_no], &gnd_numbers_to_beacon_links_map);

        FilterAuthorityRecords(authority_reader.get(), authority_writer.get(), referenced_author_ppns, gnd_numbers_to_beacon_links_map);
    } catch (const std::exception &x) {
        LOG_ERROR("caught exception: " + std::string(x.what()));
    }

    return EXIT_SUCCESS;
}
<commit_msg>Make Mario happier.<commit_after>/** \file    extract_referenced_author_records.cc
 *  \brief   Selects referenced author records from a collection of authority records.
 *  \author  Dr. Johannes Ruscheinski
 *
 *  Copyright (C) 2018, Library of the University of Tübingen
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <cctype>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "Url.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname
              << " title_records authority_records referenced_author_records [beacon_list1 beacon_list2 .. beacon_listN]\n";
    std::exit(EXIT_FAILURE);
}

void ExtractAuthorPPN(const MARC::Record &record, const std::string &tag, std::unordered_set<std::string> * const referenced_author_ppns) {
    for (const auto &field : record.getTagRange(tag)) {
        for (const auto &subfield : field.getSubfields()) {
            if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-576)"))
                referenced_author_ppns->emplace(subfield.value_.substr(__builtin_strlen("(DE-576)")));
        }
    }
}

void CollectAuthorPPNs(MARC::Reader * const title_reader, std::unordered_set<std::string> * const referenced_author_ppns) {
    while (const auto record = title_reader->read()) {
        ExtractAuthorPPN(record, "100", referenced_author_ppns);
        ExtractAuthorPPN(record, "400", referenced_author_ppns);
        ExtractAuthorPPN(record, "700", referenced_author_ppns);
    }

    LOG_INFO("extracted " + std::to_string(referenced_author_ppns->size()) + " referenced author PPN's.");
}

std::string NameFromURL(const std::string &url_string) {
    const Url url(url_string);
    std::string name(url.getAuthority());
    if (StringUtil::StartsWith(name, "www.", /* ignore_case = */true))
        name = name.substr(__builtin_strlen("www."));
    const auto last_dot_pos(name.rfind('.'));
    if (last_dot_pos != std::string::npos)
        name.resize(last_dot_pos);
    StringUtil::Map(&name, '.', ' ');

    // Convert the first letter of each "word" to uppercase:
    bool first_char_of_word(true);
    for (auto &ch : name) {
        if (first_char_of_word)
            ch = std::toupper(ch);
        first_char_of_word = ch == ' ' or ch == '-';
    }

    return name;
}

void CollectBeaconLinks(const std::string &beacon_filename,
                        std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> * const gnd_numbers_to_beacon_links_map)
{
    const auto input(FileUtil::OpenInputFileOrDie(beacon_filename));
    std::string url_prefix, institution_name;
    while (not input->eof()) {
        std::string line;
        input->getline(&line);
        StringUtil::TrimWhite(&line);
        if (unlikely(line.empty()))
            continue;
        if (unlikely(line[0] == '#')) {
            if (StringUtil::StartsWith(line, "#TARGET:")) {
                line = StringUtil::TrimWhite(line.substr(__builtin_strlen("#TARGET:")));
                if (not StringUtil::EndsWith(line, "{ID}"))
                    LOG_ERROR("Bad TARGET line in \"" + beacon_filename + "\"!");
                url_prefix = line.substr(0, line.length() - __builtin_strlen("{ID}"));
                institution_name = NameFromURL(url_prefix);
            }
        } else { // Probably a GND number.
            auto gnd_number_and_beacon_links(gnd_numbers_to_beacon_links_map->find(line));
            if (gnd_number_and_beacon_links == gnd_numbers_to_beacon_links_map->end())
                (*gnd_numbers_to_beacon_links_map)[line] =
                    std::set<std::pair<std::string, std::string>>({ std::make_pair(institution_name, url_prefix + line) });
            else
                gnd_number_and_beacon_links->second.emplace(std::make_pair(institution_name, url_prefix + line));
        }
    }
}

void FilterAuthorityRecords(
    MARC::Reader * const authority_reader, MARC::Writer * const authority_writer,
    const std::unordered_set<std::string> &referenced_author_ppns,
    const std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> &gnd_numbers_to_beacon_links_map)
{
    unsigned count(0), gnd_tagged_count(0);
    while (auto record = authority_reader->read()) {
        if (referenced_author_ppns.find(record.getControlNumber()) != referenced_author_ppns.cend()) {
            std::string gnd_number;
            if (MARC::GetGNDCode(record, &gnd_number)) {
                const auto gnd_number_and_beacon_links(gnd_numbers_to_beacon_links_map.find(gnd_number));
                if (gnd_number_and_beacon_links != gnd_numbers_to_beacon_links_map.cend()) {
                    ++gnd_tagged_count;
                    for (const auto &beacon_link : gnd_number_and_beacon_links->second)
                        record.insertField("BEA", { { 'a', beacon_link.first }, { 'u', beacon_link.second } });
                }
            }

            authority_writer->write(record);
            ++count;
        }
    }

    LOG_INFO("identified " + std::to_string(count) + " referenced author records.");
    LOG_INFO("tagged " + std::to_string(gnd_tagged_count) + " author records with beacon links.");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    if (argc < 4)
        Usage();

    const std::string title_records_filename(argv[1]);
    const std::string authority_records_filename(argv[2]);
    const std::string referenced_author_records_filename(argv[3]);

    if (unlikely(title_records_filename == referenced_author_records_filename))
        LOG_ERROR("Title input file name equals authority output file name!");
    if (unlikely(authority_records_filename == referenced_author_records_filename))
        LOG_ERROR("Authority data input file name equals authority output file name!");

    auto title_reader(MARC::Reader::Factory(title_records_filename));
    auto authority_reader(MARC::Reader::Factory(authority_records_filename));
    auto authority_writer(MARC::Writer::Factory(referenced_author_records_filename));

    try {
        std::unordered_set<std::string> referenced_author_ppns;
        CollectAuthorPPNs(title_reader.get(), &referenced_author_ppns);

        std::unordered_map<std::string, std::set<std::pair<std::string, std::string>>> gnd_numbers_to_beacon_links_map;
        for (int arg_no(4); arg_no < argc; ++arg_no)
            CollectBeaconLinks(argv[arg_no], &gnd_numbers_to_beacon_links_map);

        FilterAuthorityRecords(authority_reader.get(), authority_writer.get(), referenced_author_ppns, gnd_numbers_to_beacon_links_map);
    } catch (const std::exception &x) {
        LOG_ERROR("caught exception: " + std::string(x.what()));
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright ***********************************************************
//
// File ecmdJtagUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#define ecmdJtagUser_C
#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>
#include <ecmdSharedUtils.H>
#include <stdio.h>

#undef ecmdJtagUser_C
//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

uint32_t ecmdSendCmdUser(int argc, char * argv[]) {
  uint32_t rc = ECMD_SUCCESS;

  bool expectFlag = false;
  bool xstateFlag = false;
  ecmdLooperData looperdata;            ///< Store internal Looper data
  ecmdChipTarget target;                ///< Current target being operated on
  uint32_t instruction;                 ///< Instruction to send to chip
  uint32_t modifier;                    ///< Modifier to send to chip
  ecmdDataBuffer statusBuffer;          ///< Buffer to hold return status data
  bool validPosFound = false;           ///< Did the looper find something to run on?

  /************************************************************************/
  /* Parse Local FLAGS here!                                              */
  /************************************************************************/
  /* get format flag, if it's there */
  std::string format;
  char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-o");
  if (formatPtr == NULL) {
    format = "x";
  }
  else {
    format = formatPtr;
  }
  //Check verbose option
  bool verbose = ecmdParseOption(&argc, &argv, "-v");

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/

  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /************************************************************************/
  /* Parse Local ARGS here!                                               */
  /************************************************************************/
  if (argc < 3) {  //chip + instruction + modifier
    ecmdOutputError("sendcmd - Too few arguments specified; you need at least a chip, instruction, and modifier.\n");
    ecmdOutputError("sendcmd - Type 'sendcmd -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  //Setup the target that will be used to query the system config
  target.chipType = argv[0];
  target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
  target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD;
  target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED;

  // we need the instruction and modifier

  if (strlen(argv[1]) > 2) {
    ecmdOutputError("sendcmd - The instruction has to be <= 8 bits\n");
    return ECMD_INVALID_ARGS;
  } else if (!ecmdIsAllHex(argv[1])) {
    ecmdOutputError("sendcmd - Instruction data contained some non-hex characters\n");
    return ECMD_INVALID_ARGS;
  }
  ecmdGenB32FromHexRight(&instruction, argv[1], 32);

  if (strlen(argv[2]) > 6) {
    ecmdOutputError("sendcmd - The modifier has to be <= 24 bits\n");
    return ECMD_INVALID_ARGS;
  } else if (!ecmdIsAllHex(argv[2])) {
    ecmdOutputError("sendcmd - Modifier data contained some non-hex characters\n");
    return ECMD_INVALID_ARGS;
  }
  ecmdGenB32FromHexRight(&modifier, argv[2], 32);

  if (argc > 3) {
    ecmdOutputError("sendcmd - Too many arguments specified; you probably added an option that wasn't recognized.\n");
    ecmdOutputError("sendcmd - Type 'sendcmd -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/

  rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
  if (rc) return rc;
  char outstr[30];
  std::string printed;

  while ( ecmdConfigLooperNext(target, looperdata) ) {

    rc = sendCmd(target, instruction, modifier, statusBuffer);
    if (rc == ECMD_TARGET_NOT_CONFIGURED) {
      continue;
    }
    else if (rc) {
        printed = "sendcmd - Error occured performing sendcmd on ";
        printed += ecmdWriteTarget(target) + "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
    }
    else {
      validPosFound = true;
    }

    printed = ecmdWriteTarget(target) + "  ";
    std::string dataStr = ecmdWriteDataFormatted(statusBuffer, format);
    printed += dataStr;
    ecmdOutput( printed.c_str() );

    if ( verbose ) {

     ecmdChipData chipdata;
     rc = ecmdGetChipData (target, chipdata);

     if ( (!rc) && (chipdata.interfaceType == ECMD_INTERFACE_CFAM) ) {
      printed = "\n\t\tInstruction Status Register\n";
      printed += "\t\t---------------------------\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(0, 1) + " Attention Active" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(1, 1) + " Checkstop" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(2, 1) + " Special Attention" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(3, 1) + " Recoverable Error" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(4, 1) + " SCOM Attention" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(5, 1) + " CRC Miscompare on previous data scan-in" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(6, 1) + " Invalid Instruction" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(7, 1) + " PGOOD Indicator(set to '1' by flush, set to '0' by first JTAG instruction)" + "\n";
      char jtagInstrCnt[8];
      sprintf(jtagInstrCnt,"%X", strtoul((statusBuffer.genHexLeftStr(8, 4)).c_str(), NULL, 16));
      printed += "\t\t " + (std::string)jtagInstrCnt + " JTAG Instruction count(Incremented following Shift-IR) Bits(8:11). (Hex Left)" + "\n";

      printed += "\t\t " + statusBuffer.genHexRightStr(12, 1) + " Data scan occured after the last instruction" + "\n";
      char resvd[8];
      sprintf(resvd,"%X", strtoul((statusBuffer.genHexLeftStr(13, 3)).c_str(), NULL, 16));
      printed += "\t\t " + (std::string)resvd + " Reserved Bits(13:15). (Hex Left)" + "\n";

      char clockstr[14];
      sprintf(clockstr,"%0.4X", strtoul((statusBuffer.genHexLeftStr(16, 14)).c_str(), NULL, 16));
      printed += "\t      " + (std::string)clockstr + " Clock States(1 = running) Bits(16:29). (Hex Left)" + "\n";

      printed += "\t\t " + statusBuffer.genHexRightStr(30, 1) + " IEEE defined 0"  + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(31, 1) + " IEEE defined 1"  + "\n";
      ecmdOutput(printed.c_str());
    }
    else if (rc) {
      printed = "sendcmd - Error occured performing chipinfo query on ";
      printed += ecmdWriteTarget(target) + "\n";
      ecmdOutputError( printed.c_str() );
      return rc;
    }

   }
  }

  if (!validPosFound) {
    ecmdOutputError("Unable to find a valid chip to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}
<commit_msg>cleaned up some compiler warning messages BZ#418.<commit_after>// Copyright ***********************************************************
//
// File ecmdJtagUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#define ecmdJtagUser_C
#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>
#include <ecmdSharedUtils.H>
#include <stdio.h>

#undef ecmdJtagUser_C
//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

uint32_t ecmdSendCmdUser(int argc, char * argv[]) {
  uint32_t rc = ECMD_SUCCESS;

/*  bool expectFlag = false; */
/*  bool xstateFlag = false; */
  ecmdLooperData looperdata;            ///< Store internal Looper data
  ecmdChipTarget target;                ///< Current target being operated on
  uint32_t instruction;                 ///< Instruction to send to chip
  uint32_t modifier;                    ///< Modifier to send to chip
  ecmdDataBuffer statusBuffer;          ///< Buffer to hold return status data
  bool validPosFound = false;           ///< Did the looper find something to run on?

  /************************************************************************/
  /* Parse Local FLAGS here!                                              */
  /************************************************************************/
  /* get format flag, if it's there */
  std::string format;
  char * formatPtr = ecmdParseOptionWithArgs(&argc, &argv, "-o");
  if (formatPtr == NULL) {
    format = "x";
  }
  else {
    format = formatPtr;
  }
  //Check verbose option
  bool verbose = ecmdParseOption(&argc, &argv, "-v");

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/

  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /************************************************************************/
  /* Parse Local ARGS here!                                               */
  /************************************************************************/
  if (argc < 3) {  //chip + instruction + modifier
    ecmdOutputError("sendcmd - Too few arguments specified; you need at least a chip, instruction, and modifier.\n");
    ecmdOutputError("sendcmd - Type 'sendcmd -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  //Setup the target that will be used to query the system config
  target.chipType = argv[0];
  target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
  target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD;
  target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED;

  // we need the instruction and modifier

  if (strlen(argv[1]) > 2) {
    ecmdOutputError("sendcmd - The instruction has to be <= 8 bits\n");
    return ECMD_INVALID_ARGS;
  } else if (!ecmdIsAllHex(argv[1])) {
    ecmdOutputError("sendcmd - Instruction data contained some non-hex characters\n");
    return ECMD_INVALID_ARGS;
  }
  ecmdGenB32FromHexRight(&instruction, argv[1], 32);

  if (strlen(argv[2]) > 6) {
    ecmdOutputError("sendcmd - The modifier has to be <= 24 bits\n");
    return ECMD_INVALID_ARGS;
  } else if (!ecmdIsAllHex(argv[2])) {
    ecmdOutputError("sendcmd - Modifier data contained some non-hex characters\n");
    return ECMD_INVALID_ARGS;
  }
  ecmdGenB32FromHexRight(&modifier, argv[2], 32);

  if (argc > 3) {
    ecmdOutputError("sendcmd - Too many arguments specified; you probably added an option that wasn't recognized.\n");
    ecmdOutputError("sendcmd - Type 'sendcmd -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/

  rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
  if (rc) return rc;
/*  char outstr[30]; */
  std::string printed;

  while ( ecmdConfigLooperNext(target, looperdata) ) {

    rc = sendCmd(target, instruction, modifier, statusBuffer);
    if (rc == ECMD_TARGET_NOT_CONFIGURED) {
      continue;
    }
    else if (rc) {
        printed = "sendcmd - Error occured performing sendcmd on ";
        printed += ecmdWriteTarget(target) + "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
    }
    else {
      validPosFound = true;
    }

    printed = ecmdWriteTarget(target) + "  ";
    std::string dataStr = ecmdWriteDataFormatted(statusBuffer, format);
    printed += dataStr;
    ecmdOutput( printed.c_str() );

    if ( verbose ) {

     ecmdChipData chipdata;
     rc = ecmdGetChipData (target, chipdata);

     if ( (!rc) && (chipdata.interfaceType == ECMD_INTERFACE_CFAM) ) {
      printed = "\n\t\tInstruction Status Register\n";
      printed += "\t\t---------------------------\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(0, 1) + " Attention Active" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(1, 1) + " Checkstop" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(2, 1) + " Special Attention" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(3, 1) + " Recoverable Error" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(4, 1) + " SCOM Attention" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(5, 1) + " CRC Miscompare on previous data scan-in" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(6, 1) + " Invalid Instruction" + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(7, 1) + " PGOOD Indicator(set to '1' by flush, set to '0' by first JTAG instruction)" + "\n";
      char jtagInstrCnt[8];
      sprintf(jtagInstrCnt,"%X", strtoul((statusBuffer.genHexLeftStr(8, 4)).c_str(), NULL, 16));
      printed += "\t\t " + (std::string)jtagInstrCnt + " JTAG Instruction count(Incremented following Shift-IR) Bits(8:11). (Hex Left)" + "\n";

      printed += "\t\t " + statusBuffer.genHexRightStr(12, 1) + " Data scan occured after the last instruction" + "\n";
      char resvd[8];
      sprintf(resvd,"%X", strtoul((statusBuffer.genHexLeftStr(13, 3)).c_str(), NULL, 16));
      printed += "\t\t " + (std::string)resvd + " Reserved Bits(13:15). (Hex Left)" + "\n";

      char clockstr[14];
      sprintf(clockstr,"%04X", strtoul((statusBuffer.genHexLeftStr(16, 14)).c_str(), NULL, 16));
      printed += "\t      " + (std::string)clockstr + " Clock States(1 = running) Bits(16:29). (Hex Left)" + "\n";

      printed += "\t\t " + statusBuffer.genHexRightStr(30, 1) + " IEEE defined 0"  + "\n";
      printed += "\t\t " + statusBuffer.genHexRightStr(31, 1) + " IEEE defined 1"  + "\n";
      ecmdOutput(printed.c_str());
    }
    else if (rc) {
      printed = "sendcmd - Error occured performing chipinfo query on ";
      printed += ecmdWriteTarget(target) + "\n";
      ecmdOutputError( printed.c_str() );
      return rc;
    }

   }
  }

  if (!validPosFound) {
    ecmdOutputError("Unable to find a valid chip to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}
<|endoftext|>


<commit_before>//#define _GRIBCXX_DEBUG
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;

// 基本テンプレート
#pragma region MACRO
#define rep(i,n) for(int i=0; i<(int)n; ++i)
#define REP(i,x,n) for(int i=x; i<(int)n; ++i)
#define repi(i,n) for(int i=0; i<=(int)n; ++i)
#define REPI(i,x,n) for(int i=x; i<=(int)n; ++i)
#define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define mp make_pair
#pragma endregion

#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<string, int> psi;
typedef pair<int, string> pis;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<long long> vl;
typedef vector<long, long> vll;
#pragma endregion

// Effective std
#pragma region ESTD

template<typename C, typename T>
constexpr int count(C& c, T t) { return count(ALL(c), t); }

template<typename C, typename F>
constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); }

template<typename C, typename T, typename U>
constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); }

template<typename C, typename F, typename U>
constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); }

template<typename C>
constexpr void sort(C& c) { sort(ALL(c)); }

template<typename C, typename Pred>
constexpr void sort(C& c, Pred p) { sort(ALL(c), p); }

#pragma endregion

// グラフテンプレート
#pragma region GRAPH

typedef int Weight;
struct Edge {
  int src, dst;
  Weight weight;
  Edge(int src, int dst, Weight weight) :
    src(src), dst(dst), weight(weight) {}
};

bool operator < (const Edge &e, const Edge &f) {
  return e.weight != f.weight ? e.weight > f.weight :
    e.src != f.src ? e.src < f.src : e.dst < f.dst;
}

typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

#pragma endregion

// 定数
#pragma region CONST_VAL
#define PI (2*acos(0.0))
#define EPS (1e-9)
#define MOD (int)(1e9+7)
#pragma endregion

int main() {
  return 0;
}
<commit_msg>template.cpp<commit_after>//#define _GRIBCXX_DEBUG
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;

// 基本テンプレート
#pragma region MACRO
#define P(x) cout << (x) << endl
#define rep(i,n) for(int i=0; i<(int)n; ++i)
#define REP(i,x,n) for(int i=x; i<(int)n; ++i)
#define repi(i,n) for(int i=0; i<=(int)n; ++i)
#define REPI(i,x,n) for(int i=x; i<=(int)n; ++i)
#define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define mp make_pair
#pragma endregion

#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<string, int> psi;
typedef pair<int, string> pis;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<long> vl;
typedef vector<long long> vll;
#pragma endregion

// Effective std
#pragma region ESTD

template<typename C, typename T>
constexpr int count(C& c, T t) { return count(ALL(c), t); }

template<typename C, typename F>
constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); }

template<typename C, typename T, typename U>
constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); }

template<typename C, typename F, typename U>
constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); }

template<typename C>
constexpr void sort(C& c) { sort(ALL(c)); }

template<typename C, typename Pred>
constexpr void sort(C& c, Pred p) { sort(ALL(c), p); }

#pragma endregion

// グラフテンプレート
#pragma region GRAPH

typedef int Weight;
struct Edge {
  int src, dst;
  Weight weight;
  Edge(int src, int dst, Weight weight) :
    src(src), dst(dst), weight(weight) {}
};

bool operator < (const Edge &e, const Edge &f) {
  return e.weight != f.weight ? e.weight > f.weight :
    e.src != f.src ? e.src < f.src : e.dst < f.dst;
}

typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

#pragma endregion

// 定数
#pragma region CONST_VAL
#define PI (2*acos(0.0))
#define EPS (1e-9)
#define MOD (int)(1e9+7)
#pragma endregion

int main() {
  return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: QmitkTrackingDeviceWidget.cpp $
Language:  C++
Date:      $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $
Version:   $Revision: 1.12 $

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 "QmitkTrackingDeviceConfigurationWidget.h"
#include "mitkClaronTrackingDevice.h"
#include "mitkNDITrackingDevice.h"
#include "mitkSerialCommunication.h"
#include "qscrollbar.h"

const std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = "org.mitk.views.trackingdeviceconfigurationwidget";

QmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)
  : QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
  CreateConnections();

  //reset a few things
  ResetOutput();
  AddOutput("
NDI Polaris selected");
}

QmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()
{
}

void QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
  // create GUI widgets
  m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;
  m_Controls->setupUi(parent);
  }
}

void QmitkTrackingDeviceConfigurationWidget::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_Controls->m_trackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()) );
    connect( (QObject*)(m_Controls->m_testConnectionPolaris), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_testConnectionAurora), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_testConnectionMicronTracker), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_resetButton), SIGNAL(clicked()), this, SLOT(ResetByUser()) );
    connect( (QObject*)(m_Controls->m_finishedButton), SIGNAL(clicked()), this, SLOT(Finished()) );
  }
}

void QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()
{
  //show the correspondig widget
  m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_Controls->m_trackingDeviceChooser->currentIndex());

  //the new trackingdevice is not configurated yet
  m_TrackingDeviceConfigurated = false;

  //reset output
  ResetOutput();

  //print output
  if (m_Controls->m_trackingDeviceChooser->currentIndex()==0) AddOutput("
NDI Polaris selected");        //NDI Polaris
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==1) AddOutput("
NDI Aurora selected");    //NDI Aurora
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==2) AddOutput("
Microntracker selected"); //ClaronTechnology MicronTracker 2
}

void QmitkTrackingDeviceConfigurationWidget::EnableUserReset(bool enable)
{
  if (enable) m_Controls->m_resetButton->setVisible(true);
  else m_Controls->m_resetButton->setVisible(false);
}

void QmitkTrackingDeviceConfigurationWidget::TestConnection()
{
//#### Step 1: construct a tracking device:
mitk::TrackingDevice::Pointer testTrackingDevice = ConstructTrackingDevice();

//#### Step 2: test connection and start tracking, generate output
AddOutput("
testing connection
  ...");
if (testTrackingDevice->OpenConnection())
  {
  AddOutput(" OK");
  AddOutput("
testing tracking
  ...");
  if (testTrackingDevice->StartTracking())
    {
    AddOutput(" OK");
    if (!testTrackingDevice->StopTracking())AddOutput("
ERROR while stop tracking
");
    }
  else AddOutput(" ERROR!");
  if (!testTrackingDevice->CloseConnection())AddOutput("
ERROR while closing connection
");
  }
else AddOutput(" ERROR!");
}

void QmitkTrackingDeviceConfigurationWidget::Finished()
  {
  m_TrackingDevice = ConstructTrackingDevice();
  m_Controls->m_TrackingSystemWidget->setEnabled(false);
  m_Controls->m_trackingDeviceChooser->setEnabled(false);
  m_Controls->choose_tracking_device_label->setEnabled(false);
  m_Controls->configuration_finished_label->setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<meta name=\"qrichtext\" content=\"1\" />\n
Configuration finished
");
  emit TrackingDeviceConfigurationFinished();
  }

void QmitkTrackingDeviceConfigurationWidget::Reset()
  {
  m_TrackingDevice = NULL;
  m_Controls->m_TrackingSystemWidget->setEnabled(true);
  m_Controls->m_trackingDeviceChooser->setEnabled(true);
  m_Controls->choose_tracking_device_label->setEnabled(true);
  m_Controls->configuration_finished_label->setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<meta name=\"qrichtext\" content=\"1\" />\n
Press \"Finished\" to confirm configuration
");
  emit TrackingDeviceConfigurationReseted();
  }

void QmitkTrackingDeviceConfigurationWidget::ResetByUser()
  {
  Reset();
  }

//######################### internal help methods #######################################
void QmitkTrackingDeviceConfigurationWidget::ResetOutput()
  {
  m_output.str("");
  m_output <<"output:";
  m_Controls->m_outputTextAurora->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextMicronTracker->setHtml(QString(m_output.str().c_str()));
  }
void QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)
  {
  //print output
  m_output << s;
  m_Controls->m_outputTextAurora->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextMicronTracker->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->verticalScrollBar()->setValue(m_Controls->m_outputTextPolaris->verticalScrollBar()->maximum());
  m_Controls->m_outputTextAurora->verticalScrollBar()->setValue(m_Controls->m_outputTextAurora->verticalScrollBar()->maximum());
  m_Controls->m_outputTextMicronTracker->verticalScrollBar()->setValue(m_Controls->m_outputTextMicronTracker->verticalScrollBar()->maximum());
  repaint();
  }
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()
  {
  mitk::TrackingDevice::Pointer returnValue;
  //#### Step 1: configure tracking device:
  if (m_Controls->m_trackingDeviceChooser->currentIndex()==0)//NDI Polaris
      {
      if(m_Controls->m_radioPolaris5D->isChecked()) //5D Tracking
        {
        //not yet in the open source part so we'll only get NULL here.
        returnValue = ConfigureNDI5DTrackingDevice();
        }
      else //6D Tracking
        {
        returnValue = ConfigureNDI6DTrackingDevice();
        returnValue->SetType(mitk::NDIPolaris);
        }
      }
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==1)//NDI Aurora
        {
        returnValue = ConfigureNDI6DTrackingDevice();
        returnValue->SetType(mitk::NDIAurora);
        }
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==2)//ClaronTechnology MicronTracker 2
        {
        returnValue = mitk::ClaronTrackingDevice::New();
        }
  return returnValue;
  }

mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConfigureNDI5DTrackingDevice()
  {
  return NULL;
  }

mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConfigureNDI6DTrackingDevice()
  {
  mitk::NDITrackingDevice::Pointer tempTrackingDevice = mitk::NDITrackingDevice::New();
  switch (m_Controls->m_comPortSpinBoxPolaris->value()) //set the com port
    {                                                   //@mbi: Do anyone know how to do this in a better way? Please tell me... (Alfred)
    case 1: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM1); break;
    case 2: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM2); break;
    case 3: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM3); break;
    case 4: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM4); break;
    case 5: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM5); break;
    case 6: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM6); break;
    case 7: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM7); break;
    case 8: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM8); break;
    }

  mitk::TrackingDevice::Pointer returnValue = static_cast<mitk::TrackingDevice*>(tempTrackingDevice);
  return returnValue;
  }

<commit_msg>CHG (#2277): implemented missing method GetTrackingDevice().<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: QmitkTrackingDeviceWidget.cpp $
Language:  C++
Date:      $Date: 2009-05-12 19:14:45 +0200 (Di, 12 Mai 2009) $
Version:   $Revision: 1.12 $

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 "QmitkTrackingDeviceConfigurationWidget.h"
#include "mitkClaronTrackingDevice.h"
#include "mitkNDITrackingDevice.h"
#include "mitkSerialCommunication.h"
#include "qscrollbar.h"

const std::string QmitkTrackingDeviceConfigurationWidget::VIEW_ID = "org.mitk.views.trackingdeviceconfigurationwidget";

QmitkTrackingDeviceConfigurationWidget::QmitkTrackingDeviceConfigurationWidget(QWidget* parent, Qt::WindowFlags f)
  : QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
  CreateConnections();

  //reset a few things
  ResetOutput();
  AddOutput("
NDI Polaris selected");
}

QmitkTrackingDeviceConfigurationWidget::~QmitkTrackingDeviceConfigurationWidget()
{
}

void QmitkTrackingDeviceConfigurationWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
  // create GUI widgets
  m_Controls = new Ui::QmitkTrackingDeviceConfigurationWidgetControls;
  m_Controls->setupUi(parent);
  }
}

void QmitkTrackingDeviceConfigurationWidget::CreateConnections()
{
  if ( m_Controls )
  {
    connect( (QObject*)(m_Controls->m_trackingDeviceChooser), SIGNAL(currentIndexChanged(int)), this, SLOT(TrackingDeviceChanged()) );
    connect( (QObject*)(m_Controls->m_testConnectionPolaris), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_testConnectionAurora), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_testConnectionMicronTracker), SIGNAL(clicked()), this, SLOT(TestConnection()) );
    connect( (QObject*)(m_Controls->m_resetButton), SIGNAL(clicked()), this, SLOT(ResetByUser()) );
    connect( (QObject*)(m_Controls->m_finishedButton), SIGNAL(clicked()), this, SLOT(Finished()) );
  }
}

void QmitkTrackingDeviceConfigurationWidget::TrackingDeviceChanged()
{
  //show the correspondig widget
  m_Controls->m_TrackingSystemWidget->setCurrentIndex(m_Controls->m_trackingDeviceChooser->currentIndex());

  //the new trackingdevice is not configurated yet
  m_TrackingDeviceConfigurated = false;

  //reset output
  ResetOutput();

  //print output
  if (m_Controls->m_trackingDeviceChooser->currentIndex()==0) AddOutput("
NDI Polaris selected");        //NDI Polaris
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==1) AddOutput("
NDI Aurora selected");    //NDI Aurora
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==2) AddOutput("
Microntracker selected"); //ClaronTechnology MicronTracker 2
}

void QmitkTrackingDeviceConfigurationWidget::EnableUserReset(bool enable)
{
  if (enable) m_Controls->m_resetButton->setVisible(true);
  else m_Controls->m_resetButton->setVisible(false);
}

void QmitkTrackingDeviceConfigurationWidget::TestConnection()
{
//#### Step 1: construct a tracking device:
mitk::TrackingDevice::Pointer testTrackingDevice = ConstructTrackingDevice();

//#### Step 2: test connection and start tracking, generate output
AddOutput("
testing connection
  ...");
if (testTrackingDevice->OpenConnection())
  {
  AddOutput(" OK");
  AddOutput("
testing tracking
  ...");
  if (testTrackingDevice->StartTracking())
    {
    AddOutput(" OK");
    if (!testTrackingDevice->StopTracking())AddOutput("
ERROR while stop tracking
");
    }
  else AddOutput(" ERROR!");
  if (!testTrackingDevice->CloseConnection())AddOutput("
ERROR while closing connection
");
  }
else AddOutput(" ERROR!");
}

void QmitkTrackingDeviceConfigurationWidget::Finished()
  {
  m_TrackingDevice = ConstructTrackingDevice();
  m_Controls->m_TrackingSystemWidget->setEnabled(false);
  m_Controls->m_trackingDeviceChooser->setEnabled(false);
  m_Controls->choose_tracking_device_label->setEnabled(false);
  m_Controls->configuration_finished_label->setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<meta name=\"qrichtext\" content=\"1\" />\n
Configuration finished
");
  emit TrackingDeviceConfigurationFinished();
  }

void QmitkTrackingDeviceConfigurationWidget::Reset()
  {
  m_TrackingDevice = NULL;
  m_Controls->m_TrackingSystemWidget->setEnabled(true);
  m_Controls->m_trackingDeviceChooser->setEnabled(true);
  m_Controls->choose_tracking_device_label->setEnabled(true);
  m_Controls->configuration_finished_label->setText("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<meta name=\"qrichtext\" content=\"1\" />\n
Press \"Finished\" to confirm configuration
");
  emit TrackingDeviceConfigurationReseted();
  }

void QmitkTrackingDeviceConfigurationWidget::ResetByUser()
  {
  Reset();
  }

//######################### internal help methods #######################################
void QmitkTrackingDeviceConfigurationWidget::ResetOutput()
  {
  m_output.str("");
  m_output <<"output:";
  m_Controls->m_outputTextAurora->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextMicronTracker->setHtml(QString(m_output.str().c_str()));
  }
void QmitkTrackingDeviceConfigurationWidget::AddOutput(std::string s)
  {
  //print output
  m_output << s;
  m_Controls->m_outputTextAurora->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextMicronTracker->setHtml(QString(m_output.str().c_str()));
  m_Controls->m_outputTextPolaris->verticalScrollBar()->setValue(m_Controls->m_outputTextPolaris->verticalScrollBar()->maximum());
  m_Controls->m_outputTextAurora->verticalScrollBar()->setValue(m_Controls->m_outputTextAurora->verticalScrollBar()->maximum());
  m_Controls->m_outputTextMicronTracker->verticalScrollBar()->setValue(m_Controls->m_outputTextMicronTracker->verticalScrollBar()->maximum());
  repaint();
  }
mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConstructTrackingDevice()
  {
  mitk::TrackingDevice::Pointer returnValue;
  //#### Step 1: configure tracking device:
  if (m_Controls->m_trackingDeviceChooser->currentIndex()==0)//NDI Polaris
      {
      if(m_Controls->m_radioPolaris5D->isChecked()) //5D Tracking
        {
        //not yet in the open source part so we'll only get NULL here.
        returnValue = ConfigureNDI5DTrackingDevice();
        }
      else //6D Tracking
        {
        returnValue = ConfigureNDI6DTrackingDevice();
        returnValue->SetType(mitk::NDIPolaris);
        }
      }
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==1)//NDI Aurora
        {
        returnValue = ConfigureNDI6DTrackingDevice();
        returnValue->SetType(mitk::NDIAurora);
        }
  else if (m_Controls->m_trackingDeviceChooser->currentIndex()==2)//ClaronTechnology MicronTracker 2
        {
        returnValue = mitk::ClaronTrackingDevice::New();
        }
  return returnValue;
  }

mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConfigureNDI5DTrackingDevice()
  {
  return NULL;
  }

mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::ConfigureNDI6DTrackingDevice()
  {
  mitk::NDITrackingDevice::Pointer tempTrackingDevice = mitk::NDITrackingDevice::New();
  switch (m_Controls->m_comPortSpinBoxPolaris->value()) //set the com port
    {                                                   //@mbi: Do anyone know how to do this in a better way? Please tell me... (Alfred)
    case 1: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM1); break;
    case 2: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM2); break;
    case 3: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM3); break;
    case 4: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM4); break;
    case 5: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM5); break;
    case 6: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM6); break;
    case 7: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM7); break;
    case 8: tempTrackingDevice->SetPortNumber(mitk::SerialCommunication::COM8); break;
    }

  mitk::TrackingDevice::Pointer returnValue = static_cast<mitk::TrackingDevice*>(tempTrackingDevice);
  return returnValue;
  }

mitk::TrackingDevice::Pointer QmitkTrackingDeviceConfigurationWidget::GetTrackingDevice()
  {
  return this->m_TrackingDevice;
  }

<|endoftext|>