<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_SVG_RENDERER_HPP
#define MAPNIK_SVG_RENDERER_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/svg/output/svg_generator.hpp>
#include <mapnik/svg/output/svg_output_attributes.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/rule.hpp>              // for rule, symbolizers
#include <mapnik/box2d.hpp>     // for box2d
#include <mapnik/color.hpp>     // for color
#include <mapnik/view_transform.hpp>    // for view_transform
#include <mapnik/image_compositing.hpp>  // for composite_mode_e
#include <mapnik/pixel_position.hpp>
#include <mapnik/request.hpp>
#include <mapnik/renderer_common.hpp>
#include <mapnik/util/variant.hpp>
#include <memory>

// stl
#include <string>

// fwd declaration to avoid depedence on agg headers
namespace agg { struct trans_affine; }

// fwd declarations to speed up compile
namespace mapnik {
  class Map;
  class feature_impl;
  class feature_type_style;
  class label_collision_detector4;
  class layer;
  class marker;
  class proj_transform;
}

namespace mapnik
{
// parameterized with the type of output iterator it will use for output.
// output iterators add more flexibility than streams, because iterators
// can target many other output destinations besides streams.
template <typename OutputIterator>
class MAPNIK_DECL svg_renderer : public feature_style_processor<svg_renderer<OutputIterator> >,
                                 private mapnik::noncopyable
{
public:
    using processor_impl_type = svg_renderer<OutputIterator>;
    svg_renderer(Map const& m, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    svg_renderer(Map const& m, request const& req, attributes const& vars, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    ~svg_renderer();

    void start_map_processing(Map const& map);
    void end_map_processing(Map const& map);
    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);
    void end_layer_processing(layer const& lay);
    void start_style_processing(feature_type_style const& /*st*/) {}
    void end_style_processing(feature_type_style const& /*st*/) {}

    /*!
     * @brief Overloads that process each kind of symbolizer individually.
     */
    void process(point_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(raster_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(shield_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(text_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(building_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(markers_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(debug_symbolizer const& /*sym*/,
                 mapnik::feature_impl & /*feature*/,
                 proj_transform const& /*prj_trans*/) {}
    void process(group_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);

    // Overload that process the whole set of symbolizers of a rule.
    // return true, meaning that this renderer can process multiple symbolizers.
    bool process(rule::symbolizers const& syms,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);

    void painted(bool)
    {
        // nothing to do
    }

    inline eAttributeCollectionPolicy attribute_collection_policy() const
    {
        return DEFAULT;
    }

    inline double scale_factor() const
    {
        return common_.scale_factor_;
    }

    inline attributes const& variables() const
    {
        return common_.vars_;
    }

    inline OutputIterator& get_output_iterator()
    {
        return output_iterator_;
    }

    inline const OutputIterator& get_output_iterator() const
    {
        return output_iterator_;
    }

private:
    OutputIterator& output_iterator_;
    svg::path_output_attributes path_attributes_;
    svg::svg_generator<OutputIterator> generator_;
    bool painted_;
    renderer_common common_;

    // Visitor that makes the calls to process each symbolizer when stored in a variant.
    // This object follows the model of that found in feature_style_processor. It appears here, because
    // the logic that iterates over the set of symbolizer has been moved to an SVG renderer's internal
    // method.
    struct symbol_dispatch : public util::static_visitor<>
    {
        symbol_dispatch(svg_renderer<OutputIterator>& processor,
                        mapnik::feature_impl & feature,
                        proj_transform const& prj_trans)
            : processor_(processor),
              feature_(feature),
              prj_trans_(prj_trans) {}

        template <typename Symbolizer>
        void operator()(Symbolizer const& sym) const
        {
            processor_.process(sym, feature_, prj_trans_);
        }

        svg_renderer<OutputIterator>& processor_;
        mapnik::feature_impl & feature_;
        proj_transform const& prj_trans_;
    };
};
}

#endif // MAPNIK_SVG_RENDERER_HPP
<commit_msg>enable painted for svg_renderer<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_SVG_RENDERER_HPP
#define MAPNIK_SVG_RENDERER_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/svg/output/svg_generator.hpp>
#include <mapnik/svg/output/svg_output_attributes.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/rule.hpp>              // for rule, symbolizers
#include <mapnik/box2d.hpp>     // for box2d
#include <mapnik/color.hpp>     // for color
#include <mapnik/view_transform.hpp>    // for view_transform
#include <mapnik/image_compositing.hpp>  // for composite_mode_e
#include <mapnik/pixel_position.hpp>
#include <mapnik/request.hpp>
#include <mapnik/renderer_common.hpp>
#include <mapnik/util/variant.hpp>
#include <memory>

// stl
#include <string>

// fwd declaration to avoid depedence on agg headers
namespace agg { struct trans_affine; }

// fwd declarations to speed up compile
namespace mapnik {
  class Map;
  class feature_impl;
  class feature_type_style;
  class label_collision_detector4;
  class layer;
  class marker;
  class proj_transform;
}

namespace mapnik
{
// parameterized with the type of output iterator it will use for output.
// output iterators add more flexibility than streams, because iterators
// can target many other output destinations besides streams.
template <typename OutputIterator>
class MAPNIK_DECL svg_renderer : public feature_style_processor<svg_renderer<OutputIterator> >,
                                 private mapnik::noncopyable
{
public:
    using processor_impl_type = svg_renderer<OutputIterator>;
    svg_renderer(Map const& m, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    svg_renderer(Map const& m, request const& req, attributes const& vars, OutputIterator& output_iterator, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    ~svg_renderer();

    void start_map_processing(Map const& map);
    void end_map_processing(Map const& map);
    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);
    void end_layer_processing(layer const& lay);
    void start_style_processing(feature_type_style const& /*st*/) {}
    void end_style_processing(feature_type_style const& /*st*/) {}

    /*!
     * @brief Overloads that process each kind of symbolizer individually.
     */
    void process(point_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(raster_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(shield_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(text_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(building_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(markers_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(debug_symbolizer const& /*sym*/,
                 mapnik::feature_impl & /*feature*/,
                 proj_transform const& /*prj_trans*/) {}
    void process(group_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);

    // Overload that process the whole set of symbolizers of a rule.
    // return true, meaning that this renderer can process multiple symbolizers.
    bool process(rule::symbolizers const& syms,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);

    bool painted() const
    {
        return painted_;
    }

    void painted(bool painted)
    {
        painted_ = painted;
    }

    inline eAttributeCollectionPolicy attribute_collection_policy() const
    {
        return DEFAULT;
    }

    inline double scale_factor() const
    {
        return common_.scale_factor_;
    }

    inline attributes const& variables() const
    {
        return common_.vars_;
    }

    inline OutputIterator& get_output_iterator()
    {
        return output_iterator_;
    }

    inline const OutputIterator& get_output_iterator() const
    {
        return output_iterator_;
    }

private:
    OutputIterator& output_iterator_;
    svg::path_output_attributes path_attributes_;
    svg::svg_generator<OutputIterator> generator_;
    bool painted_;
    renderer_common common_;

    // Visitor that makes the calls to process each symbolizer when stored in a variant.
    // This object follows the model of that found in feature_style_processor. It appears here, because
    // the logic that iterates over the set of symbolizer has been moved to an SVG renderer's internal
    // method.
    struct symbol_dispatch : public util::static_visitor<>
    {
        symbol_dispatch(svg_renderer<OutputIterator>& processor,
                        mapnik::feature_impl & feature,
                        proj_transform const& prj_trans)
            : processor_(processor),
              feature_(feature),
              prj_trans_(prj_trans) {}

        template <typename Symbolizer>
        void operator()(Symbolizer const& sym) const
        {
            processor_.process(sym, feature_, prj_trans_);
        }

        svg_renderer<OutputIterator>& processor_;
        mapnik::feature_impl & feature_;
        proj_transform const& prj_trans_;
    };
};
}

#endif // MAPNIK_SVG_RENDERER_HPP
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %built_cling -fno-rtti 2>&1 | FileCheck %s
// Test Lookup::Named and Namespace, used in quick simple lookups.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"

#include "clang/AST/Decl.h"
#include "clang/AST/Tag.h"

#include <cstdio>

using namespace cling;
using namespace llvm;

.rawInput 1

enum class E {};
class C {};

namespace N {
enum class Inside_E {};
class C {};
}

.rawInput 0

clang::Sema& S = gCling->getSema();
const LookupHelper& lookup = gCling->getLookupHelper();
LookupHelper::DiagSetting diags = LookupHelper::WithDiagnostics;

const clang::TagDecl *tagdecl{nullptr};

tagdecl = utils::Lookup::Tag(&S, "E", nullptr);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "E"

tagdecl = utils::Lookup::Tag(&S, "C", nullptr);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "C"

const clang::NamedDecl *nameddecl{nullptr};

nameddecl = utils::Lookup::Named(&S, "N", nullptr);
nameddecl
//CHECK: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
decl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N"

const clang::DeclContext *context = dyn_cast<clang::DeclContext>(decl);
context
//CHECK: (const clang::DeclContext *) 0x{{[1-9a-f][0-9a-f]*$}}

decl = utils::Lookup::Tag(&S, "E", context);
decl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
decl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N::E"

decl = utils::Lookup::Tag(&S, "C", context);
decl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
decl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N::C"
<commit_msg>Fix tag lookup test<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %built_cling -fno-rtti 2>&1 | FileCheck %s
// Test Lookup::Named and Namespace, used in quick simple lookups.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"

#include "clang/AST/Decl.h"
#include "clang/AST/Tag.h"

#include <cstdio>

using namespace cling;
using namespace llvm;

.rawInput 1

enum class E {};
class C {};

namespace N {
enum class Inside_E {};
class Inside_C {};
}

.rawInput 0

clang::Sema& S = gCling->getSema();
const LookupHelper& lookup = gCling->getLookupHelper();
LookupHelper::DiagSetting diags = LookupHelper::WithDiagnostics;

const clang::TagDecl *tagdecl{nullptr};

tagdecl = utils::Lookup::Tag(&S, "E", nullptr);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "E"

tagdecl = utils::Lookup::Tag(&S, "C", nullptr);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "C"

const clang::NamedDecl *nameddecl{nullptr};

nameddecl = utils::Lookup::Named(&S, "N", nullptr);
nameddecl
//CHECK: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
nameddecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N"

const clang::DeclContext *context = dyn_cast<clang::DeclContext>(nameddecl);
context
//CHECK: (const clang::DeclContext *) 0x{{[1-9a-f][0-9a-f]*$}}

tagdecl = utils::Lookup::Tag(&S, "Inside_E", context);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N::Inside_E"

tagdecl = utils::Lookup::Tag(&S, "Inside_C", context);
tagdecl
//CHECK: (const clang::TagDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
tagdecl->getQualifiedNameAsString().c_str()
//CHECK-NEXT: ({{[^)]+}}) "N::Inside_C"
<|endoftext|>


<commit_before>#pragma once
#ifndef NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX
#define NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX

#include <queue>
#include <stack>

#include "nifty/graph/subgraph_mask.hxx"
#include "nifty/queue/changeable_priority_queue.hxx"

namespace nifty{
namespace graph{
namespace detail_graph{

    template<class T>
    struct LiFo : public std::stack<T>{
        using std::stack<T>::stack;
        const T & nextElement(){
            return this->top();
        }
    };
    template<class T>
    struct FiFo : public std::queue<T>{
        using std::queue<T>::queue;
        const T & nextElement(){
            return this->front();
        }
    };

    template<class GRAPH,class QUEUE>
    class SearchImpl{

    public:
        typedef GRAPH Graph;
        typedef typename Graph:: template NodeMap<int64_t>     PredecessorsMap;
        typedef typename Graph:: template NodeMap<int64_t>  DistanceMap;
    private:
        typedef QUEUE    Queue;
    public:
        SearchImpl(const Graph & g)
        :   g_(g),
            queue_(),
            predMap_(g),
            distMap_(g){
        }

        // run single source single target
        // no  callback no mask exposed
        void runSingleSourceSingleTarget(
            const int64_t source,
            const int64_t target = -1
        ){
            // subgraph mask
            DefaultSubgraphMask<Graph> subgraphMask;
            // visitor
            auto visitor = [&]
            (
                int64_t topNode,
                const DistanceMap     & distances,
                const PredecessorsMap & predecessors
            ){
                return topNode != target;
            };

            this->initializeMaps(&source, &source +1);
            runImpl(subgraphMask, visitor);
        }

        // run single source  ALL targets
        // no  callback no mask exposed
        void runSingleSource(
            const int64_t source
        ){

            // subgraph mask
            DefaultSubgraphMask<Graph> subgraphMask;
            this->initializeMaps(&source, &source +1);
            // visitor
            auto visitor = [](   int64_t topNode,
                const DistanceMap     & distances,
                const PredecessorsMap & predecessors
            ){
                return true;
            };
            runImpl(subgraphMask, visitor);
        }

        template<class SOURCE_ITER, class SUBGRAPH_MASK, class VISITOR>
        void run(
            SOURCE_ITER sourceBegin,
            SOURCE_ITER sourceEnd,
            const SUBGRAPH_MASK &  subgraphMask,
            VISITOR && visitor
        ){
            this->initializeMaps(sourceBegin, sourceEnd);
            this->runImpl(subgraphMask,visitor);
        }

        const DistanceMap & distances()const{
            return distMap_;
        }
        const PredecessorsMap predecessors()const{
            return predMap_;
        }
    private:

        template<
            class SUBGRAPH_MASK,
            class VISITOR
        >
        void runImpl(
            const SUBGRAPH_MASK &  subgraphMask,
            VISITOR && visitor
        ){

            while(!queue_.empty()){
                auto u = queue_.nextElement();
                queue_.pop();

                // exit on visitors demand
                if(!visitor(u, distMap_, predMap_)){
                    break;
                }

                // if node == gloal node
                //  break
                for(auto adj : g_.adjacency(u)){
                    const auto v = adj.node();
                    const auto e = adj.edge();
                    if(predMap_[v] == -1 &&  subgraphMask.useNode(v) && subgraphMask.useEdge(e)){
                        predMap_[v] = u;
                        distMap_[v] = distMap_[u] + 1;
                        queue_.push(v);
                    }
                }
            }

        }

        template<class SOURCE_ITER>
        void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){
            while(!queue_.empty())
                queue_.pop();
            for(auto node : g_.nodes()){
                predMap_[node] = -1;
            }

            for( ; sourceBegin!=sourceEnd; ++sourceBegin){
                auto n = *sourceBegin;
                distMap_[n] = 0;
                predMap_[n] = n;
                queue_.push(n);
            }
        }

        const GRAPH & g_;
        Queue queue_;
        PredecessorsMap predMap_;
        DistanceMap     distMap_;
    };

} // namespace nifty::graph::detail_graph
} // namespace nifty::graph
} // namespace nifty

#endif  // NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX
<commit_msg>touch<commit_after>#pragma once
#ifndef NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX
#define NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX

#include <queue>
#include <stack>

#include "nifty/graph/subgraph_mask.hxx"
#include "nifty/queue/changeable_priority_queue.hxx"

namespace nifty{
namespace graph{
namespace detail_graph{

    template<class T>
    struct LiFo : public std::stack<T>{
        using std::stack<T>::stack;
        const T & nextElement(){
            return this->top();
        }
    };
    template<class T>
    struct FiFo : public std::queue<T>{
        using std::queue<T>::queue;
        const T & nextElement(){
            return this->front();
        }
    };

    template<class GRAPH,class QUEUE>
    class SearchImpl{

    public:
        typedef GRAPH Graph;
        typedef typename Graph:: template NodeMap<int64_t>     PredecessorsMap;
        typedef typename Graph:: template NodeMap<int64_t>  DistanceMap;
    private:
        typedef QUEUE    Queue;
    public:
        SearchImpl(const Graph & g)
        :   g_(g),
            queue_(),
            predMap_(g),
            distMap_(g){
        }

        // run single source single target
        // no  callback no mask exposed
        void runSingleSourceSingleTarget(
            const int64_t source,
            const int64_t target = -1
        ){
            // subgraph mask
            DefaultSubgraphMask<Graph> subgraphMask;
            // visitor
            auto visitor = [&]
            (
                int64_t topNode,
                const DistanceMap     & distances,
                const PredecessorsMap & predecessors
            ){
                return topNode != target;
            };

            this->initializeMaps(&source, &source +1);
            runImpl(subgraphMask, visitor);
        }

        // run single source  ALL targets
        // no  callback no mask exposed
        void runSingleSource(
            const int64_t source
        ){

            // subgraph mask
            DefaultSubgraphMask<Graph> subgraphMask;
            this->initializeMaps(&source, &source +1);
            // visitor
            auto visitor = [](   int64_t topNode,
                const DistanceMap     & distances,
                const PredecessorsMap & predecessors
            ){
                return true;
            };
            runImpl(subgraphMask, visitor);
        }

        template<class SOURCE_ITER, class SUBGRAPH_MASK, class VISITOR>
        void run(
            SOURCE_ITER sourceBegin,
            SOURCE_ITER sourceEnd,
            const SUBGRAPH_MASK &  subgraphMask,
            VISITOR && visitor
        ){
            this->initializeMaps(sourceBegin, sourceEnd);
            this->runImpl(subgraphMask,visitor);
        }

        const DistanceMap & distances()const{
            return distMap_;
        }
        const PredecessorsMap predecessors()const{
            return predMap_;
        }
    private:

        template<
            class SUBGRAPH_MASK,
            class VISITOR
        >
        void runImpl(
            const SUBGRAPH_MASK &  subgraphMask,
            VISITOR && visitor
        ){

            while(!queue_.empty()){
                auto u = queue_.nextElement();
                queue_.pop();

                // exit on visitors demand
                if(!visitor(u, distMap_, predMap_)){
                    break;
                }

                // if node == gloal node
                //  break
                for(auto adj : g_.adjacency(u)){
                    const auto v = adj.node();
                    const auto e = adj.edge();
                    if(predMap_[v] == -1 &&  subgraphMask.useNode(v) && subgraphMask.useEdge(e)){
                        predMap_[v] = u;
                        distMap_[v] = distMap_[u] + 1;
                        queue_.push(v);
                    }
                }
            }

        }

        template<class SOURCE_ITER>
        void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){
            while(!queue_.empty())
                queue_.pop();
            for(auto node : g_.nodes()){
                predMap_[node] = -1;
            }

            for( ; sourceBegin!=sourceEnd; ++sourceBegin){
                auto n = *sourceBegin;
                distMap_[n] = 0;
                predMap_[n] = n;
                queue_.push(n);
            }
        }

        const GRAPH & g_;
        Queue queue_;
        PredecessorsMap predMap_;
        DistanceMap     distMap_;
    };

} // namespace nifty::graph::detail_graph
} // namespace nifty::graph
} // namespace nifty

#endif  // NIFTY_GRAPH_DETAIL_SEARCH_IMPL_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xpool.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17:07:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "xtable.hxx"
#include "xattr.hxx"
#include "xpool.hxx"
#include "svdattr.hxx"
#include "svxids.hrc"

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif

XOutdevItemPool::XOutdevItemPool(
    SfxItemPool* _pMaster,
    sal_uInt16 nAttrStart,
    sal_uInt16 nAttrEnd,
    sal_Bool bLoadRefCounts)
:   SfxItemPool(String("XOutdevItemPool", gsl_getSystemTextEncoding()), nAttrStart, nAttrEnd, 0L, 0L, bLoadRefCounts)
{
    // prepare some defaults
    const XubString aNullStr;
    const Bitmap aNullBmp;
    const XPolygon aNullPol;
    const Color aNullLineCol(RGB_Color(COL_BLACK));
    const Color aNullFillCol(RGB_Color(COL_DEFAULT_SHAPE_FILLING));  // "Blue 8"
    const Color aNullShadowCol(RGB_Color(COL_LIGHTGRAY));
    const XDash aNullDash;
    const XGradient aNullGrad(aNullLineCol, RGB_Color(COL_WHITE));
    const XHatch aNullHatch(aNullLineCol);

    // get master pointer, evtl. add myself to the end of the pools
    if(!_pMaster)
    {
        _pMaster = this;
    }
    else
    {
        SfxItemPool* pParent = _pMaster;

        while(pParent->GetSecondaryPool())
        {
            pParent = pParent->GetSecondaryPool();
        }

        pParent->SetSecondaryPool(this);
    }

    // prepare PoolDefaults
    mppLocalPoolDefaults = new SfxPoolItem*[GetLastWhich() - GetFirstWhich() + 1];

    mppLocalPoolDefaults[XATTR_LINESTYLE          -XATTR_START] = new XLineStyleItem;
    mppLocalPoolDefaults[XATTR_LINEDASH           -XATTR_START] = new XLineDashItem(this,aNullDash);
    mppLocalPoolDefaults[XATTR_LINEWIDTH          -XATTR_START] = new XLineWidthItem;
    mppLocalPoolDefaults[XATTR_LINECOLOR          -XATTR_START] = new XLineColorItem(aNullStr,aNullLineCol);
    mppLocalPoolDefaults[XATTR_LINESTART          -XATTR_START] = new XLineStartItem(this,aNullPol);
    mppLocalPoolDefaults[XATTR_LINEEND            -XATTR_START] = new XLineEndItem  (this,aNullPol);
    mppLocalPoolDefaults[XATTR_LINESTARTWIDTH     -XATTR_START] = new XLineStartWidthItem;
    mppLocalPoolDefaults[XATTR_LINEENDWIDTH       -XATTR_START] = new XLineEndWidthItem;
    mppLocalPoolDefaults[XATTR_LINESTARTCENTER    -XATTR_START] = new XLineStartCenterItem;
    mppLocalPoolDefaults[XATTR_LINEENDCENTER      -XATTR_START] = new XLineEndCenterItem;
    mppLocalPoolDefaults[XATTR_LINETRANSPARENCE   -XATTR_START] = new XLineTransparenceItem;
    mppLocalPoolDefaults[XATTR_LINEJOINT            -XATTR_START] = new XLineJointItem;
    mppLocalPoolDefaults[XATTR_FILLSTYLE                -XATTR_START] = new XFillStyleItem;
    mppLocalPoolDefaults[XATTR_FILLCOLOR                -XATTR_START] = new XFillColorItem   (aNullStr,aNullFillCol);
    mppLocalPoolDefaults[XATTR_FILLGRADIENT         -XATTR_START] = new XFillGradientItem(this,aNullGrad);
    mppLocalPoolDefaults[XATTR_FILLHATCH                -XATTR_START] = new XFillHatchItem   (this,aNullHatch);
    mppLocalPoolDefaults[XATTR_FILLBITMAP               -XATTR_START] = new XFillBitmapItem  (this,aNullBmp);
    mppLocalPoolDefaults[XATTR_FILLTRANSPARENCE     -XATTR_START] = new XFillTransparenceItem;
    mppLocalPoolDefaults[XATTR_GRADIENTSTEPCOUNT        -XATTR_START] = new XGradientStepCountItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILE         -XATTR_START] = new XFillBmpTileItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POS          -XATTR_START] = new XFillBmpPosItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEX            -XATTR_START] = new XFillBmpSizeXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEY            -XATTR_START] = new XFillBmpSizeYItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZELOG      -XATTR_START] = new XFillBmpSizeLogItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETX  -XATTR_START] = new XFillBmpTileOffsetXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETY  -XATTR_START] = new XFillBmpTileOffsetYItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_STRETCH      -XATTR_START] = new XFillBmpStretchItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETX       -XATTR_START] = new XFillBmpPosOffsetXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETY       -XATTR_START] = new XFillBmpPosOffsetYItem;
    mppLocalPoolDefaults[XATTR_FILLFLOATTRANSPARENCE    -XATTR_START] = new XFillFloatTransparenceItem( this, aNullGrad, FALSE );
    mppLocalPoolDefaults[XATTR_SECONDARYFILLCOLOR       -XATTR_START] = new XSecondaryFillColorItem(aNullStr, aNullFillCol);
    mppLocalPoolDefaults[XATTR_FILLBACKGROUND           -XATTR_START] = new XFillBackgroundItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTYLE       -XATTR_START] = new XFormTextStyleItem;
    mppLocalPoolDefaults[XATTR_FORMTXTADJUST      -XATTR_START] = new XFormTextAdjustItem;
    mppLocalPoolDefaults[XATTR_FORMTXTDISTANCE    -XATTR_START] = new XFormTextDistanceItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTART       -XATTR_START] = new XFormTextStartItem;
    mppLocalPoolDefaults[XATTR_FORMTXTMIRROR      -XATTR_START] = new XFormTextMirrorItem;
    mppLocalPoolDefaults[XATTR_FORMTXTOUTLINE     -XATTR_START] = new XFormTextOutlineItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHADOW      -XATTR_START] = new XFormTextShadowItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWCOLOR   -XATTR_START] = new XFormTextShadowColorItem(aNullStr,aNullShadowCol);
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWXVAL    -XATTR_START] = new XFormTextShadowXValItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWYVAL    -XATTR_START] = new XFormTextShadowYValItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTDFORM     -XATTR_START] = new XFormTextStdFormItem;
    mppLocalPoolDefaults[XATTR_FORMTXTHIDEFORM    -XATTR_START] = new XFormTextHideFormItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWTRANSP  -XATTR_START] = new XFormTextShadowTranspItem;

    // create SetItems
    SfxItemSet* pSet=new SfxItemSet(*_pMaster, XATTR_LINE_FIRST, XATTR_LINE_LAST);
    mppLocalPoolDefaults[XATTRSET_LINE - XATTR_START] = new XLineAttrSetItem(pSet);
    pSet=new SfxItemSet(*_pMaster, XATTR_FILL_FIRST, XATTR_FILL_LAST);
    mppLocalPoolDefaults[XATTRSET_FILL - XATTR_START] = new XFillAttrSetItem(pSet);

    // create ItemInfos
    mpLocalItemInfos = new SfxItemInfo[GetLastWhich() - GetFirstWhich() + 1];
    for(sal_uInt16 i(GetFirstWhich()); i <= GetLastWhich(); i++)
    {
        mpLocalItemInfos[i - XATTR_START]._nSID = 0;
        mpLocalItemInfos[i - XATTR_START]._nFlags = SFX_ITEM_POOLABLE;
    }

    mpLocalItemInfos[XATTR_LINESTYLE        -XATTR_START]._nSID = SID_ATTR_LINE_STYLE;
    mpLocalItemInfos[XATTR_LINEDASH         -XATTR_START]._nSID = SID_ATTR_LINE_DASH;
    mpLocalItemInfos[XATTR_LINEWIDTH        -XATTR_START]._nSID = SID_ATTR_LINE_WIDTH;
    mpLocalItemInfos[XATTR_LINECOLOR        -XATTR_START]._nSID = SID_ATTR_LINE_COLOR;
    mpLocalItemInfos[XATTR_LINESTART        -XATTR_START]._nSID = SID_ATTR_LINE_START;
    mpLocalItemInfos[XATTR_LINEEND          -XATTR_START]._nSID = SID_ATTR_LINE_END;
    mpLocalItemInfos[XATTR_LINESTARTWIDTH   -XATTR_START]._nSID = SID_ATTR_LINE_STARTWIDTH;
    mpLocalItemInfos[XATTR_LINEENDWIDTH     -XATTR_START]._nSID = SID_ATTR_LINE_ENDWIDTH;
    mpLocalItemInfos[XATTR_LINESTARTCENTER  -XATTR_START]._nSID = SID_ATTR_LINE_STARTCENTER;
    mpLocalItemInfos[XATTR_LINEENDCENTER    -XATTR_START]._nSID = SID_ATTR_LINE_ENDCENTER;
    mpLocalItemInfos[XATTR_FILLSTYLE        -XATTR_START]._nSID = SID_ATTR_FILL_STYLE;
    mpLocalItemInfos[XATTR_FILLCOLOR        -XATTR_START]._nSID = SID_ATTR_FILL_COLOR;
    mpLocalItemInfos[XATTR_FILLGRADIENT     -XATTR_START]._nSID = SID_ATTR_FILL_GRADIENT;
    mpLocalItemInfos[XATTR_FILLHATCH        -XATTR_START]._nSID = SID_ATTR_FILL_HATCH;
    mpLocalItemInfos[XATTR_FILLBITMAP       -XATTR_START]._nSID = SID_ATTR_FILL_BITMAP;
    mpLocalItemInfos[XATTR_FORMTXTSTYLE     -XATTR_START]._nSID = SID_FORMTEXT_STYLE;
    mpLocalItemInfos[XATTR_FORMTXTADJUST    -XATTR_START]._nSID = SID_FORMTEXT_ADJUST;
    mpLocalItemInfos[XATTR_FORMTXTDISTANCE  -XATTR_START]._nSID = SID_FORMTEXT_DISTANCE;
    mpLocalItemInfos[XATTR_FORMTXTSTART     -XATTR_START]._nSID = SID_FORMTEXT_START;
    mpLocalItemInfos[XATTR_FORMTXTMIRROR    -XATTR_START]._nSID = SID_FORMTEXT_MIRROR;
    mpLocalItemInfos[XATTR_FORMTXTOUTLINE   -XATTR_START]._nSID = SID_FORMTEXT_OUTLINE;
    mpLocalItemInfos[XATTR_FORMTXTSHADOW    -XATTR_START]._nSID = SID_FORMTEXT_SHADOW;
    mpLocalItemInfos[XATTR_FORMTXTSHDWCOLOR -XATTR_START]._nSID = SID_FORMTEXT_SHDWCOLOR;
    mpLocalItemInfos[XATTR_FORMTXTSHDWXVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWXVAL;
    mpLocalItemInfos[XATTR_FORMTXTSHDWYVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWYVAL;
    mpLocalItemInfos[XATTR_FORMTXTSTDFORM   -XATTR_START]._nSID = SID_FORMTEXT_STDFORM;
    mpLocalItemInfos[XATTR_FORMTXTHIDEFORM  -XATTR_START]._nSID = SID_FORMTEXT_HIDEFORM;

    // if it's my own creation level, set Defaults and ItemInfos
    if(XATTR_START == GetFirstWhich() && XATTR_END == GetLastWhich())
    {
        SetDefaults(mppLocalPoolDefaults);
        SetItemInfos(mpLocalItemInfos);
    }
}

/*************************************************************************
|*
|* copy ctor, sorgt dafuer, dass die static defaults gecloned werden
|*            (Parameter 2 = TRUE)
|*
\************************************************************************/

XOutdevItemPool::XOutdevItemPool(const XOutdevItemPool& rPool)
:   SfxItemPool(rPool, TRUE),
    mppLocalPoolDefaults(0L),
    mpLocalItemInfos(0L)
{
}

/*************************************************************************
|*
|* Clone()
|*
\************************************************************************/

SfxItemPool* XOutdevItemPool::Clone() const
{
    return new XOutdevItemPool(*this);
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

XOutdevItemPool::~XOutdevItemPool()
{
    Delete();

    // remove own static defaults
    if(mppLocalPoolDefaults)
    {
        SfxPoolItem** ppDefaultItem = mppLocalPoolDefaults;
        for(sal_uInt16 i(GetLastWhich() - GetFirstWhich() + 1); i; --i, ++ppDefaultItem)
        {
            if ( *ppDefaultItem ) //Teile schon von abgel. Klasse abgeraeumt!
            {
                SetRefCount( **ppDefaultItem, 0 );
                delete *ppDefaultItem;
            }
        }

        delete[] mppLocalPoolDefaults;
    }

    if(mpLocalItemInfos)
    {
        delete[] mpLocalItemInfos;
    }
}

// eof
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.114); FILE MERGED 2006/09/01 17:47:47 kaib 1.11.114.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xpool.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 06:25:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include "xtable.hxx"
#include "xattr.hxx"
#include "xpool.hxx"
#include "svdattr.hxx"
#include "svxids.hrc"

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif

XOutdevItemPool::XOutdevItemPool(
    SfxItemPool* _pMaster,
    sal_uInt16 nAttrStart,
    sal_uInt16 nAttrEnd,
    sal_Bool bLoadRefCounts)
:   SfxItemPool(String("XOutdevItemPool", gsl_getSystemTextEncoding()), nAttrStart, nAttrEnd, 0L, 0L, bLoadRefCounts)
{
    // prepare some defaults
    const XubString aNullStr;
    const Bitmap aNullBmp;
    const XPolygon aNullPol;
    const Color aNullLineCol(RGB_Color(COL_BLACK));
    const Color aNullFillCol(RGB_Color(COL_DEFAULT_SHAPE_FILLING));  // "Blue 8"
    const Color aNullShadowCol(RGB_Color(COL_LIGHTGRAY));
    const XDash aNullDash;
    const XGradient aNullGrad(aNullLineCol, RGB_Color(COL_WHITE));
    const XHatch aNullHatch(aNullLineCol);

    // get master pointer, evtl. add myself to the end of the pools
    if(!_pMaster)
    {
        _pMaster = this;
    }
    else
    {
        SfxItemPool* pParent = _pMaster;

        while(pParent->GetSecondaryPool())
        {
            pParent = pParent->GetSecondaryPool();
        }

        pParent->SetSecondaryPool(this);
    }

    // prepare PoolDefaults
    mppLocalPoolDefaults = new SfxPoolItem*[GetLastWhich() - GetFirstWhich() + 1];

    mppLocalPoolDefaults[XATTR_LINESTYLE          -XATTR_START] = new XLineStyleItem;
    mppLocalPoolDefaults[XATTR_LINEDASH           -XATTR_START] = new XLineDashItem(this,aNullDash);
    mppLocalPoolDefaults[XATTR_LINEWIDTH          -XATTR_START] = new XLineWidthItem;
    mppLocalPoolDefaults[XATTR_LINECOLOR          -XATTR_START] = new XLineColorItem(aNullStr,aNullLineCol);
    mppLocalPoolDefaults[XATTR_LINESTART          -XATTR_START] = new XLineStartItem(this,aNullPol);
    mppLocalPoolDefaults[XATTR_LINEEND            -XATTR_START] = new XLineEndItem  (this,aNullPol);
    mppLocalPoolDefaults[XATTR_LINESTARTWIDTH     -XATTR_START] = new XLineStartWidthItem;
    mppLocalPoolDefaults[XATTR_LINEENDWIDTH       -XATTR_START] = new XLineEndWidthItem;
    mppLocalPoolDefaults[XATTR_LINESTARTCENTER    -XATTR_START] = new XLineStartCenterItem;
    mppLocalPoolDefaults[XATTR_LINEENDCENTER      -XATTR_START] = new XLineEndCenterItem;
    mppLocalPoolDefaults[XATTR_LINETRANSPARENCE   -XATTR_START] = new XLineTransparenceItem;
    mppLocalPoolDefaults[XATTR_LINEJOINT            -XATTR_START] = new XLineJointItem;
    mppLocalPoolDefaults[XATTR_FILLSTYLE                -XATTR_START] = new XFillStyleItem;
    mppLocalPoolDefaults[XATTR_FILLCOLOR                -XATTR_START] = new XFillColorItem   (aNullStr,aNullFillCol);
    mppLocalPoolDefaults[XATTR_FILLGRADIENT         -XATTR_START] = new XFillGradientItem(this,aNullGrad);
    mppLocalPoolDefaults[XATTR_FILLHATCH                -XATTR_START] = new XFillHatchItem   (this,aNullHatch);
    mppLocalPoolDefaults[XATTR_FILLBITMAP               -XATTR_START] = new XFillBitmapItem  (this,aNullBmp);
    mppLocalPoolDefaults[XATTR_FILLTRANSPARENCE     -XATTR_START] = new XFillTransparenceItem;
    mppLocalPoolDefaults[XATTR_GRADIENTSTEPCOUNT        -XATTR_START] = new XGradientStepCountItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILE         -XATTR_START] = new XFillBmpTileItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POS          -XATTR_START] = new XFillBmpPosItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEX            -XATTR_START] = new XFillBmpSizeXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZEY            -XATTR_START] = new XFillBmpSizeYItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_SIZELOG      -XATTR_START] = new XFillBmpSizeLogItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETX  -XATTR_START] = new XFillBmpTileOffsetXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_TILEOFFSETY  -XATTR_START] = new XFillBmpTileOffsetYItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_STRETCH      -XATTR_START] = new XFillBmpStretchItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETX       -XATTR_START] = new XFillBmpPosOffsetXItem;
    mppLocalPoolDefaults[XATTR_FILLBMP_POSOFFSETY       -XATTR_START] = new XFillBmpPosOffsetYItem;
    mppLocalPoolDefaults[XATTR_FILLFLOATTRANSPARENCE    -XATTR_START] = new XFillFloatTransparenceItem( this, aNullGrad, FALSE );
    mppLocalPoolDefaults[XATTR_SECONDARYFILLCOLOR       -XATTR_START] = new XSecondaryFillColorItem(aNullStr, aNullFillCol);
    mppLocalPoolDefaults[XATTR_FILLBACKGROUND           -XATTR_START] = new XFillBackgroundItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTYLE       -XATTR_START] = new XFormTextStyleItem;
    mppLocalPoolDefaults[XATTR_FORMTXTADJUST      -XATTR_START] = new XFormTextAdjustItem;
    mppLocalPoolDefaults[XATTR_FORMTXTDISTANCE    -XATTR_START] = new XFormTextDistanceItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTART       -XATTR_START] = new XFormTextStartItem;
    mppLocalPoolDefaults[XATTR_FORMTXTMIRROR      -XATTR_START] = new XFormTextMirrorItem;
    mppLocalPoolDefaults[XATTR_FORMTXTOUTLINE     -XATTR_START] = new XFormTextOutlineItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHADOW      -XATTR_START] = new XFormTextShadowItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWCOLOR   -XATTR_START] = new XFormTextShadowColorItem(aNullStr,aNullShadowCol);
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWXVAL    -XATTR_START] = new XFormTextShadowXValItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWYVAL    -XATTR_START] = new XFormTextShadowYValItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSTDFORM     -XATTR_START] = new XFormTextStdFormItem;
    mppLocalPoolDefaults[XATTR_FORMTXTHIDEFORM    -XATTR_START] = new XFormTextHideFormItem;
    mppLocalPoolDefaults[XATTR_FORMTXTSHDWTRANSP  -XATTR_START] = new XFormTextShadowTranspItem;

    // create SetItems
    SfxItemSet* pSet=new SfxItemSet(*_pMaster, XATTR_LINE_FIRST, XATTR_LINE_LAST);
    mppLocalPoolDefaults[XATTRSET_LINE - XATTR_START] = new XLineAttrSetItem(pSet);
    pSet=new SfxItemSet(*_pMaster, XATTR_FILL_FIRST, XATTR_FILL_LAST);
    mppLocalPoolDefaults[XATTRSET_FILL - XATTR_START] = new XFillAttrSetItem(pSet);

    // create ItemInfos
    mpLocalItemInfos = new SfxItemInfo[GetLastWhich() - GetFirstWhich() + 1];
    for(sal_uInt16 i(GetFirstWhich()); i <= GetLastWhich(); i++)
    {
        mpLocalItemInfos[i - XATTR_START]._nSID = 0;
        mpLocalItemInfos[i - XATTR_START]._nFlags = SFX_ITEM_POOLABLE;
    }

    mpLocalItemInfos[XATTR_LINESTYLE        -XATTR_START]._nSID = SID_ATTR_LINE_STYLE;
    mpLocalItemInfos[XATTR_LINEDASH         -XATTR_START]._nSID = SID_ATTR_LINE_DASH;
    mpLocalItemInfos[XATTR_LINEWIDTH        -XATTR_START]._nSID = SID_ATTR_LINE_WIDTH;
    mpLocalItemInfos[XATTR_LINECOLOR        -XATTR_START]._nSID = SID_ATTR_LINE_COLOR;
    mpLocalItemInfos[XATTR_LINESTART        -XATTR_START]._nSID = SID_ATTR_LINE_START;
    mpLocalItemInfos[XATTR_LINEEND          -XATTR_START]._nSID = SID_ATTR_LINE_END;
    mpLocalItemInfos[XATTR_LINESTARTWIDTH   -XATTR_START]._nSID = SID_ATTR_LINE_STARTWIDTH;
    mpLocalItemInfos[XATTR_LINEENDWIDTH     -XATTR_START]._nSID = SID_ATTR_LINE_ENDWIDTH;
    mpLocalItemInfos[XATTR_LINESTARTCENTER  -XATTR_START]._nSID = SID_ATTR_LINE_STARTCENTER;
    mpLocalItemInfos[XATTR_LINEENDCENTER    -XATTR_START]._nSID = SID_ATTR_LINE_ENDCENTER;
    mpLocalItemInfos[XATTR_FILLSTYLE        -XATTR_START]._nSID = SID_ATTR_FILL_STYLE;
    mpLocalItemInfos[XATTR_FILLCOLOR        -XATTR_START]._nSID = SID_ATTR_FILL_COLOR;
    mpLocalItemInfos[XATTR_FILLGRADIENT     -XATTR_START]._nSID = SID_ATTR_FILL_GRADIENT;
    mpLocalItemInfos[XATTR_FILLHATCH        -XATTR_START]._nSID = SID_ATTR_FILL_HATCH;
    mpLocalItemInfos[XATTR_FILLBITMAP       -XATTR_START]._nSID = SID_ATTR_FILL_BITMAP;
    mpLocalItemInfos[XATTR_FORMTXTSTYLE     -XATTR_START]._nSID = SID_FORMTEXT_STYLE;
    mpLocalItemInfos[XATTR_FORMTXTADJUST    -XATTR_START]._nSID = SID_FORMTEXT_ADJUST;
    mpLocalItemInfos[XATTR_FORMTXTDISTANCE  -XATTR_START]._nSID = SID_FORMTEXT_DISTANCE;
    mpLocalItemInfos[XATTR_FORMTXTSTART     -XATTR_START]._nSID = SID_FORMTEXT_START;
    mpLocalItemInfos[XATTR_FORMTXTMIRROR    -XATTR_START]._nSID = SID_FORMTEXT_MIRROR;
    mpLocalItemInfos[XATTR_FORMTXTOUTLINE   -XATTR_START]._nSID = SID_FORMTEXT_OUTLINE;
    mpLocalItemInfos[XATTR_FORMTXTSHADOW    -XATTR_START]._nSID = SID_FORMTEXT_SHADOW;
    mpLocalItemInfos[XATTR_FORMTXTSHDWCOLOR -XATTR_START]._nSID = SID_FORMTEXT_SHDWCOLOR;
    mpLocalItemInfos[XATTR_FORMTXTSHDWXVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWXVAL;
    mpLocalItemInfos[XATTR_FORMTXTSHDWYVAL  -XATTR_START]._nSID = SID_FORMTEXT_SHDWYVAL;
    mpLocalItemInfos[XATTR_FORMTXTSTDFORM   -XATTR_START]._nSID = SID_FORMTEXT_STDFORM;
    mpLocalItemInfos[XATTR_FORMTXTHIDEFORM  -XATTR_START]._nSID = SID_FORMTEXT_HIDEFORM;

    // if it's my own creation level, set Defaults and ItemInfos
    if(XATTR_START == GetFirstWhich() && XATTR_END == GetLastWhich())
    {
        SetDefaults(mppLocalPoolDefaults);
        SetItemInfos(mpLocalItemInfos);
    }
}

/*************************************************************************
|*
|* copy ctor, sorgt dafuer, dass die static defaults gecloned werden
|*            (Parameter 2 = TRUE)
|*
\************************************************************************/

XOutdevItemPool::XOutdevItemPool(const XOutdevItemPool& rPool)
:   SfxItemPool(rPool, TRUE),
    mppLocalPoolDefaults(0L),
    mpLocalItemInfos(0L)
{
}

/*************************************************************************
|*
|* Clone()
|*
\************************************************************************/

SfxItemPool* XOutdevItemPool::Clone() const
{
    return new XOutdevItemPool(*this);
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

XOutdevItemPool::~XOutdevItemPool()
{
    Delete();

    // remove own static defaults
    if(mppLocalPoolDefaults)
    {
        SfxPoolItem** ppDefaultItem = mppLocalPoolDefaults;
        for(sal_uInt16 i(GetLastWhich() - GetFirstWhich() + 1); i; --i, ++ppDefaultItem)
        {
            if ( *ppDefaultItem ) //Teile schon von abgel. Klasse abgeraeumt!
            {
                SetRefCount( **ppDefaultItem, 0 );
                delete *ppDefaultItem;
            }
        }

        delete[] mppLocalPoolDefaults;
    }

    if(mpLocalItemInfos)
    {
        delete[] mpLocalItemInfos;
    }
}

// eof
<|endoftext|>


<commit_before>//#define VERBOSEARGS

{
  // set job and simulation variables as :
  // root run.C  --run <x> --event <y> --process <proc> --minhard <min> --maxhard <max> --minpt <minpt>

  int nrun = 0;
  int nevent = 0;
  int seed = 0;

  char sseed[1024];
  char srun[1024];
  char sevent[1024];
  char sprocess[1024];
  char sminpthard[1024];
  char smaxpthard[1024];
  char sminptgammapi0[1024];
  char squench[1024];
  char sqhat[1024];

  sprintf(srun,"");
  sprintf(sevent,"");
  sprintf(sprocess,"");
  sprintf(sminpthard,"");
  sprintf(smaxpthard,"");
  sprintf(sminptgammapi0,"");
  sprintf(squench,"");
  sprintf(sqhat,"");

  for (int i=0; i< gApplication->Argc();i++){
#ifdef VERBOSEARGS
    printf("Arg  %d:  %s\n",i,gApplication->Argv(i));
#endif
    if (!(strcmp(gApplication->Argv(i),"--run")))
      nrun = atoi(gApplication->Argv(i+1));
    sprintf(srun,"%d",nrun);
    if (!(strcmp(gApplication->Argv(i),"--event")))
      nevent = atoi(gApplication->Argv(i+1));
    sprintf(sevent,"%d",nevent);

    if (!(strcmp(gApplication->Argv(i),"--process")))
      sprintf(sprocess, gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--minhard")))
      sprintf(sminpthard,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--maxhard")))
      sprintf(smaxpthard,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--minpt")))
      sprintf(sminptgammapi0,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--quench")))
      sprintf(squench,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--qhat")))
      sprintf(sqhat,gApplication->Argv(i+1));

  }

  seed = nrun * 100000 + nevent;
  sprintf(sseed,"%d",seed);

  if (seed==0) {
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stderr,"!!!!  WARNING! Seeding variable for MC is 0          !!!!\n");
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  } else {
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stdout,"!!!  MC Seed is %d \n",seed);
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  }

  // set the seed environment variable
  gSystem->Setenv("CONFIG_SEED",sseed);
  gSystem->Setenv("DC_RUN",srun);
  gSystem->Setenv("DC_EVENT",sevent);
  gSystem->Setenv("DC_RUN_TYPE",sprocess);//"kPyGammaJetPHOS");
  gSystem->Setenv("PTHARDMIN",sminpthard);//"20");
  gSystem->Setenv("PTHARDMAX",smaxpthard);//"30");

  gSystem->Setenv("PTGAMMAPI0MIN",sminptgammapi0);//"1");
  gSystem->Setenv("QUENCHING",squench);
  gSystem->Setenv("QHAT",sqhat);

  gSystem->Setenv("ECMS","14000");
  gSystem->Setenv("ALIMDC_RAWDB1","./mdc1");
  gSystem->Setenv("ALIMDC_RAWDB2","./mdc2");
  gSystem->Setenv("ALIMDC_TAGDB","./mdc1/tag");
  gSystem->Setenv("ALIMDC_RUNDB","./mdc1/meta");
  cout<< "SIMRUN:: Run " << gSystem->Getenv("DC_RUN") << " Event " << gSystem->Getenv("DC_EVENT")
	  << " Process "    << gSystem->Getenv("DC_RUN_TYPE")
	  << " minpthard " << gSystem->Getenv("PTHARDMIN")
	  << " maxpthard " << gSystem->Getenv("PTHARDMAX")
	  << " minpt "     << gSystem->Getenv("PTGAMMAPI0MIN")
	  << endl;
  //gSystem->Exec("cp $ROOTSYS/etc/system.rootrc .rootrc");
  cout<<">>>>> SIMULATION <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q sim.C > sim.log 2>&1");
  cout<<">>>>> SIMULATION QA <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q simqa.C > simqa.log 2>&1");
  cout<<">>>>> RECONSTRUCTION <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q rec.C > rec.log 2>&1");
  cout<<">>>>> RECONSTRUCTION QA <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q recqa.C > recqa.log 2>&1");
  cout<<">>>>> TAG <<<<<"<<endl;
  if( gSystem->Getenv("ALIEN_JDL_OUTPUTDIR"))
    gSystem->Exec("aliroot -b -q tag.C > tag.log 2>&1");
  cout<<">>>>> CHECK ESD <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q CheckESD.C > check.log 2>&1");

}
<commit_msg>Replace QADataMakerSteer by QAManager deriving from CDBManager<commit_after>//#define VERBOSEARGS

{
  // set job and simulation variables as :
  // root run.C  --run <x> --event <y> --process <proc> --minhard <min> --maxhard <max> --minpt <minpt>

  int nrun = 0;
  int nevent = 0;
  int seed = 0;

  char sseed[1024];
  char srun[1024];
  char sevent[1024];
  char sprocess[1024];
  char sminpthard[1024];
  char smaxpthard[1024];
  char sminptgammapi0[1024];
  char squench[1024];
  char sqhat[1024];

  sprintf(srun,"");
  sprintf(sevent,"");
  sprintf(sprocess,"");
  sprintf(sminpthard,"");
  sprintf(smaxpthard,"");
  sprintf(sminptgammapi0,"");
  sprintf(squench,"");
  sprintf(sqhat,"");

  for (int i=0; i< gApplication->Argc();i++){
#ifdef VERBOSEARGS
    printf("Arg  %d:  %s\n",i,gApplication->Argv(i));
#endif
    if (!(strcmp(gApplication->Argv(i),"--run")))
      nrun = atoi(gApplication->Argv(i+1));
    sprintf(srun,"%d",nrun);
    if (!(strcmp(gApplication->Argv(i),"--event")))
      nevent = atoi(gApplication->Argv(i+1));
    sprintf(sevent,"%d",nevent);

    if (!(strcmp(gApplication->Argv(i),"--process")))
      sprintf(sprocess, gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--minhard")))
      sprintf(sminpthard,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--maxhard")))
      sprintf(smaxpthard,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--minpt")))
      sprintf(sminptgammapi0,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--quench")))
      sprintf(squench,gApplication->Argv(i+1));

    if (!(strcmp(gApplication->Argv(i),"--qhat")))
      sprintf(sqhat,gApplication->Argv(i+1));

  }

  seed = nrun * 100000 + nevent;
  sprintf(sseed,"%d",seed);

  if (seed==0) {
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stderr,"!!!!  WARNING! Seeding variable for MC is 0          !!!!\n");
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  } else {
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stdout,"!!!  MC Seed is %d \n",seed);
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  }

  // set the seed environment variable
  gSystem->Setenv("CONFIG_SEED",sseed);
  gSystem->Setenv("DC_RUN",srun);
  gSystem->Setenv("DC_EVENT",sevent);
  gSystem->Setenv("DC_RUN_TYPE",sprocess);//"kPyGammaJetPHOS");
  gSystem->Setenv("PTHARDMIN",sminpthard);//"20");
  gSystem->Setenv("PTHARDMAX",smaxpthard);//"30");

  gSystem->Setenv("PTGAMMAPI0MIN",sminptgammapi0);//"1");
  gSystem->Setenv("QUENCHING",squench);
  gSystem->Setenv("QHAT",sqhat);

  gSystem->Setenv("ECMS","14000");
  gSystem->Setenv("ALIMDC_RAWDB1","./mdc1");
  gSystem->Setenv("ALIMDC_RAWDB2","./mdc2");
  gSystem->Setenv("ALIMDC_TAGDB","./mdc1/tag");
  gSystem->Setenv("ALIMDC_RUNDB","./mdc1/meta");
  cout<< "SIMRUN:: Run " << gSystem->Getenv("DC_RUN") << " Event " << gSystem->Getenv("DC_EVENT")
	  << " Process "    << gSystem->Getenv("DC_RUN_TYPE")
	  << " minpthard " << gSystem->Getenv("PTHARDMIN")
	  << " maxpthard " << gSystem->Getenv("PTHARDMAX")
	  << " minpt "     << gSystem->Getenv("PTGAMMAPI0MIN")
	  << endl;
  //gSystem->Exec("cp $ROOTSYS/etc/system.rootrc .rootrc");
  cout<<">>>>> SIMULATION <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q sim.C > sim.log 2>&1");
  cout<<">>>>> SIMULATION QA <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q simqa.C > simqa.log 2>&1");
  cout<<">>>>> RECONSTRUCTION <<<<<"<<endl;
  gSystem->Exec("rm galice.root");
  gSystem->Exec("Aliroot -b -q rec.C > rec.log 2>&1");
  cout<<">>>>> RECONSTRUCTION QA <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q recqa.C > recqa.log 2>&1");
  cout<<">>>>> TAG <<<<<"<<endl;
  if( gSystem->Getenv("ALIEN_JDL_OUTPUTDIR"))
    gSystem->Exec("aliroot -b -q tag.C > tag.log 2>&1");
  cout<<">>>>> CHECK ESD <<<<<"<<endl;
  gSystem->Exec("aliroot -b -q CheckESD.C > check.log 2>&1");

}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/data.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <string>
#include <vector>
#include <testHelpers.hpp>

#include <af/device.h>

using std::string;
using std::vector;

template<typename T>
void testFunction()
{
    af_info();

    af_array outArray = 0;
    dim_t dims[] = {32, 32};
    ASSERT_EQ(AF_SUCCESS, af_randu(&outArray, 2, dims, (af_dtype) af::dtype_traits<T>::af_type));
    // cleanup
    if(outArray != 0) ASSERT_EQ(AF_SUCCESS, af_release_array(outArray));
}

void backendTest()
{
    int backends = af::getAvailableBackends();

    bool cpu    = backends & AF_BACKEND_CPU;
    bool cuda   = backends & AF_BACKEND_CUDA;
    bool opencl = backends & AF_BACKEND_OPENCL;

    if(cpu) {
        printf("\nRunning CPU Backend...\n");
        af::setBackend(AF_BACKEND_CPU);
        testFunction<float>();
    }

    if(cuda) {
        printf("\nRunning CUDA Backend...\n");
        af::setBackend(AF_BACKEND_CUDA);
        testFunction<float>();
    }

    if(opencl) {
        printf("\nRunning OpenCL Backend...\n");
        af::setBackend(AF_BACKEND_OPENCL);
        testFunction<float>();
    }
}

TEST(BACKEND_TEST, Basic)
{
    backendTest();
}
<commit_msg>Cleanup/improve backend test<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/data.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <string>
#include <vector>
#include <testHelpers.hpp>

#include <af/device.h>

using std::string;
using std::vector;

template<typename T>
void testFunction()
{
    af_info();

    af_array outArray = 0;
    dim_t dims[] = {32, 32};
    ASSERT_EQ(AF_SUCCESS, af_randu(&outArray, 2, dims, (af_dtype) af::dtype_traits<T>::af_type));
    // cleanup
    if(outArray != 0) ASSERT_EQ(AF_SUCCESS, af_release_array(outArray));
}

void backendTest()
{
    int backends = af::getAvailableBackends();

    ASSERT_NE(backends, 0);

    bool cpu    = backends & AF_BACKEND_CPU;
    bool cuda   = backends & AF_BACKEND_CUDA;
    bool opencl = backends & AF_BACKEND_OPENCL;

    printf("\nRunning Default Backend...\n");
    testFunction<float>();

    if(cpu) {
        printf("\nRunning CPU Backend...\n");
        af::setBackend(AF_BACKEND_CPU);
        testFunction<float>();
    }

    if(cuda) {
        printf("\nRunning CUDA Backend...\n");
        af::setBackend(AF_BACKEND_CUDA);
        testFunction<float>();
    }

    if(opencl) {
        printf("\nRunning OpenCL Backend...\n");
        af::setBackend(AF_BACKEND_OPENCL);
        testFunction<float>();
    }
}

TEST(BACKEND_TEST, Basic)
{
    backendTest();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: virtualmachine.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-06-17 09:20:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if !defined INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX
#define INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX

#include "rtl/ref.hxx"
#include "salhelper/simplereferenceobject.hxx"

#ifdef SOLAR_JAVA
#include "jni.h"
#else
struct JNIEnv;
struct JavaVM;
typedef int jint;
typedef void * jobject;
#endif

namespace jvmaccess {

/** An encapsulating wrapper around a Java virtual machine.
 */
class VirtualMachine: public salhelper::SimpleReferenceObject
{
public:
    /** A helper to attach a thread to a Java virtual machine.

        @descr
        Upon construction of a guard the current thread is attached to the
        virtual machine, and upon destruction of the guard the thread is
        detached again.  For any one thread, multiple instances of this class
        may be used in a stack-like fashion (care is taken to only really
        detach the thread from the virtual machine upon destruction of the guard
        at the bottom of the stack).
     */
    class AttachGuard
    {
    public:
        /** An exception indicating failure to create an AttachGuard.
         */
        class CreationException
        {
        public:
            CreationException();

            CreationException(CreationException const &);

            virtual ~CreationException();

            CreationException & operator =(CreationException const &);
        };

        /** Attach the current thread to a virtual machine.

            @param rMachine
            The virtual machine to attach to.  Must not be a null reference.

            @exception CreationException
            Thrown in case attaching fails (due to a JNI problem).
         */
        explicit AttachGuard(rtl::Reference< VirtualMachine > const & rMachine);

        /** Detach the current thread from the virtual machine again.
         */
        ~AttachGuard();

        /** Get a JNI environment pointer for the current thread.

            @return
            A valid JNI environment pointer.  Will never be null.
         */
        inline JNIEnv * getEnvironment() const { return m_pEnvironment; }

    private:
        AttachGuard(AttachGuard &); // not implemented
        void operator =(AttachGuard); // not implemented

        rtl::Reference< VirtualMachine > m_xMachine;
        JNIEnv * m_pEnvironment;
        bool m_bDetach;
    };

    /** Create a wrapper around a Java virtual machine.

        @param pVm
        A JNI pointer to virtual machine.  Must not be null.

        @param nVersion
        The JNI version of the virtual machine pointed to by pVm.  Must be at
        least JNI_VERSION_1_2.  This parameter should be of type jint, not int,
        but at least on some platforms the definition of jint changed from
        JDK 1.3 (long) to JDK 1.4 (int), so that the mangled C++ name of the
        constructor would depend on the JDK version used at compile time.

        @param bDestroy
        Whether to destroy the virtual machine when destructing the wrapper
        (i.e., whether the wrapper owns the virtual machine pointed to by pVm).

        @param pMainThreadEnv
        A valid JNI environment pointer for the current thread; must not be
        null.  The current thread must be "initially attached" to the virtual
        machine while this constructor is being called (i.e., it must be the
        thread that has called JNI_CreateJavaVM in case the virtual machine has
        been started via the JNI Invocation API, and it must not already have
        called DetachCurrentThread; or it must be executing native code called
        from a "primordial" virtual machine).  This environment pointer is used
        to obtain a reference to the thread's current context class loader
        (java.lang.Thread.getCurrentClassLoader).  If later a native thread is
        attached to the virtual machine, that thread's context class loader
        would be null, so the AttachGuard first of all sets it to the saved
        value.  In a nutshell, this means that all native threads attached to
        the virtual machine use the context class loader of the "initial Java
        thread."
     */
    VirtualMachine(JavaVM * pVm, int nVersion, bool bDestroy,
                   JNIEnv * pMainThreadEnv);

private:
    VirtualMachine(VirtualMachine &); // not implemented
    void operator =(VirtualMachine); // not implemented

    virtual ~VirtualMachine();

    void acquireInitialContextClassLoader(JNIEnv * pEnv);

    void releaseInitialContextClassLoader() const;

    JNIEnv * attachThread(bool * pAttached) const;

    void detachThread() const;

    JavaVM * m_pVm;
    jint m_nVersion;
    bool m_bDestroy;
    jobject m_aInitialContextClassLoader;

    friend class AttachGuard; // to access attachThread, detachThread
};

}

#endif // INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.8); FILE MERGED 2005/09/05 14:40:56 rt 1.5.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: virtualmachine.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:22:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#if !defined INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX
#define INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX

#include "rtl/ref.hxx"
#include "salhelper/simplereferenceobject.hxx"

#ifdef SOLAR_JAVA
#include "jni.h"
#else
struct JNIEnv;
struct JavaVM;
typedef int jint;
typedef void * jobject;
#endif

namespace jvmaccess {

/** An encapsulating wrapper around a Java virtual machine.
 */
class VirtualMachine: public salhelper::SimpleReferenceObject
{
public:
    /** A helper to attach a thread to a Java virtual machine.

        @descr
        Upon construction of a guard the current thread is attached to the
        virtual machine, and upon destruction of the guard the thread is
        detached again.  For any one thread, multiple instances of this class
        may be used in a stack-like fashion (care is taken to only really
        detach the thread from the virtual machine upon destruction of the guard
        at the bottom of the stack).
     */
    class AttachGuard
    {
    public:
        /** An exception indicating failure to create an AttachGuard.
         */
        class CreationException
        {
        public:
            CreationException();

            CreationException(CreationException const &);

            virtual ~CreationException();

            CreationException & operator =(CreationException const &);
        };

        /** Attach the current thread to a virtual machine.

            @param rMachine
            The virtual machine to attach to.  Must not be a null reference.

            @exception CreationException
            Thrown in case attaching fails (due to a JNI problem).
         */
        explicit AttachGuard(rtl::Reference< VirtualMachine > const & rMachine);

        /** Detach the current thread from the virtual machine again.
         */
        ~AttachGuard();

        /** Get a JNI environment pointer for the current thread.

            @return
            A valid JNI environment pointer.  Will never be null.
         */
        inline JNIEnv * getEnvironment() const { return m_pEnvironment; }

    private:
        AttachGuard(AttachGuard &); // not implemented
        void operator =(AttachGuard); // not implemented

        rtl::Reference< VirtualMachine > m_xMachine;
        JNIEnv * m_pEnvironment;
        bool m_bDetach;
    };

    /** Create a wrapper around a Java virtual machine.

        @param pVm
        A JNI pointer to virtual machine.  Must not be null.

        @param nVersion
        The JNI version of the virtual machine pointed to by pVm.  Must be at
        least JNI_VERSION_1_2.  This parameter should be of type jint, not int,
        but at least on some platforms the definition of jint changed from
        JDK 1.3 (long) to JDK 1.4 (int), so that the mangled C++ name of the
        constructor would depend on the JDK version used at compile time.

        @param bDestroy
        Whether to destroy the virtual machine when destructing the wrapper
        (i.e., whether the wrapper owns the virtual machine pointed to by pVm).

        @param pMainThreadEnv
        A valid JNI environment pointer for the current thread; must not be
        null.  The current thread must be "initially attached" to the virtual
        machine while this constructor is being called (i.e., it must be the
        thread that has called JNI_CreateJavaVM in case the virtual machine has
        been started via the JNI Invocation API, and it must not already have
        called DetachCurrentThread; or it must be executing native code called
        from a "primordial" virtual machine).  This environment pointer is used
        to obtain a reference to the thread's current context class loader
        (java.lang.Thread.getCurrentClassLoader).  If later a native thread is
        attached to the virtual machine, that thread's context class loader
        would be null, so the AttachGuard first of all sets it to the saved
        value.  In a nutshell, this means that all native threads attached to
        the virtual machine use the context class loader of the "initial Java
        thread."
     */
    VirtualMachine(JavaVM * pVm, int nVersion, bool bDestroy,
                   JNIEnv * pMainThreadEnv);

private:
    VirtualMachine(VirtualMachine &); // not implemented
    void operator =(VirtualMachine); // not implemented

    virtual ~VirtualMachine();

    void acquireInitialContextClassLoader(JNIEnv * pEnv);

    void releaseInitialContextClassLoader() const;

    JNIEnv * attachThread(bool * pAttached) const;

    void detachThread() const;

    JavaVM * m_pVm;
    jint m_nVersion;
    bool m_bDestroy;
    jobject m_aInitialContextClassLoader;

    friend class AttachGuard; // to access attachThread, detachThread
};

}

#endif // INCLUDED_JVMACCESS_VIRTUALMACHINE_HXX
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#include "dll/dbn.hpp"
#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE( "dbn/sgd/1", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.3;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dbn/sgd/2", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::momentum
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dbn/sgd/3", "[dbn][mnist][sgd][gaussian]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
            dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::deque, double>(1000);

    REQUIRE(!dataset.training_images.empty());

    mnist::normalize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 0.2);
}

//This test should not perform well, but should not fail
TEST_CASE( "dbn/sgd/4", "[dbn][mnist][sgd][relu]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::deque, double>(200);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(std::isfinite(error));
}

TEST_CASE( "dbn/sgd/5", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::weight_decay<dll::decay_type::L2>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>();

    REQUIRE(!dataset.training_images.empty());
    dataset.training_images.resize(200);
    dataset.training_labels.resize(200);

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 5);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);

    REQUIRE(error < 1e-1);
}

TEST_CASE( "dbn/sgd/6", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::momentum
        , dll::weight_decay<dll::decay_type::L2>
        , dll::batch_size<100>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>();

    REQUIRE(!dataset.training_images.empty());
    dataset.training_images.resize(200);
    dataset.training_labels.resize(200);

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 10);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);

    REQUIRE(error < 5e-2);
}

TEST_CASE( "dbn/sgd/7", "[dbn][mnist][sgd][memory]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::sgd_trainer>
        , dll::memory
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 0.2);
}
<commit_msg>Complete the test<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#include "dll/dbn.hpp"
#include "dll/dense_stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE( "dbn/sgd/1", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->pretrain(dataset.training_images, 50);

    dbn->learning_rate = 0.1;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    std::cout << "ft_error:" << ft_error << std::endl;
    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dbn/sgd/2", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::momentum
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    dbn->pretrain(dataset.training_images, 20);

    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dbn/sgd/3", "[dbn][mnist][sgd][gaussian]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
            dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::deque, double>(1000);

    REQUIRE(!dataset.training_images.empty());

    mnist::normalize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

//This test should not perform well, but should not fail
//TODO This should be improved
TEST_CASE( "dbn/sgd/4", "[dbn][mnist][sgd][relu]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::deque, double>(200);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);
    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);

    REQUIRE(std::isfinite(error));
}

TEST_CASE( "dbn/sgd/5", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::weight_decay<dll::decay_type::L2>
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(200);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 20);

    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 200);
    REQUIRE(error < 1e-1);
}

//Here to test large batch size
TEST_CASE( "dbn/sgd/6", "[dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::momentum
        , dll::weight_decay<dll::decay_type::L2>
        , dll::batch_size<100>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(300);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.1;

    dbn->pretrain(dataset.training_images, 10);

    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    REQUIRE(error < 1e-1);
}

TEST_CASE( "dbn/sgd/7", "[dbn][mnist][sgd][memory]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
            dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
        , dll::trainer<dll::dense_sgd_trainer>
        , dll::memory
        , dll::batch_size<10>
        >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->pretrain(dataset.training_images, 20);

    dbn->learning_rate = 0.1;

    auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100);
    REQUIRE(error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}
<|endoftext|>


<commit_before>#include <stdio.h>

struct A {
	int a;
	A()
		: a(5)
	{
		puts("A cstr");
	}
	~A()
	{
		puts("A dstr");
	}
	void put() const
	{
		printf("a=%d\n", a);
	}
};

template<int dummy = 0>
struct XT {
	static A a;
};

template<int dummy>
A XT<dummy>::a;

typedef XT<0> X;

static struct Init {
	Init()
	{
		puts("Init");
		X::a.put();
	}
} s_init;

int main()
{
	puts("main");
	X::a.put();
}
<commit_msg>change name of var<commit_after>#include <stdio.h>

struct A {
	int aaa;
	A()
		: aaa(123)
	{
		puts("A cstr");
	}
	~A()
	{
		puts("A dstr");
	}
	void put() const
	{
		printf("aaa=%d\n", aaa);
	}
};

template<int dummy = 0>
struct XT {
	static A sss;
};

template<int dummy>
A XT<dummy>::sss;

typedef XT<0> X;

static struct Init {
	Init()
	{
		puts("Init");
		X::sss.put();
	}
} s_init;

int main()
{
	puts("main");
	X::sss.put();
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Alexey Korepanov <kaikaikai@yandex.ru>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>

template<typename MatrixType> void real_qz(const MatrixType& m)
{
  /* this test covers the following files:
     RealQZ.h
  */
  using std::abs;
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  Index dim = m.cols();

  MatrixType A = MatrixType::Random(dim,dim),
             B = MatrixType::Random(dim,dim);

  // Regression test for bug 985: Randomly set rows or columns to zero
  Index k=internal::random<int>(0, dim-1);
  switch(internal::random<int>(0,10)) {
  case 0:
    A.row(k).setZero(); break;
  case 1:
    A.col(k).setZero(); break;
  case 2:
    B.row(k).setZero(); break;
  case 3:
    B.col(k).setZero(); break;
  default:
    break;
  }

  RealQZ<MatrixType> qz(A,B);

  VERIFY_IS_EQUAL(qz.info(), Success);
  // check for zeros
  bool all_zeros = true;
  for (Index i=0; i<A.cols(); i++)
    for (Index j=0; j<i; j++) {
      if (abs(qz.matrixT()(i,j))!=Scalar(0.0))
        all_zeros = false;
      if (j<i-1 && abs(qz.matrixS()(i,j))!=Scalar(0.0))
        all_zeros = false;
      if (j==i-1 && j>0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))
        all_zeros = false;
    }
  VERIFY_IS_EQUAL(all_zeros, true);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));
  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));
}

void test_real_qz()
{
  int s = 0;
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( real_qz(Matrix4f()) );
    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );

    // some trivial but implementation-wise tricky cases
    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );
    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );
    CALL_SUBTEST_3( real_qz(Matrix<double,1,1>()) );
    CALL_SUBTEST_4( real_qz(Matrix2d()) );
  }

  TEST_SET_BUT_UNUSED_VARIABLE(s)
}
<commit_msg>Addendum to last patch: k is Index and not int (transplanted from 01a0782f0768a79972ea5bff5a43711114017e96)<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Alexey Korepanov <kaikaikai@yandex.ru>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>

template<typename MatrixType> void real_qz(const MatrixType& m)
{
  /* this test covers the following files:
     RealQZ.h
  */
  using std::abs;
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  Index dim = m.cols();

  MatrixType A = MatrixType::Random(dim,dim),
             B = MatrixType::Random(dim,dim);

  // Regression test for bug 985: Randomly set rows or columns to zero
  Index k=internal::random<Index>(0, dim-1);
  switch(internal::random<int>(0,10)) {
  case 0:
    A.row(k).setZero(); break;
  case 1:
    A.col(k).setZero(); break;
  case 2:
    B.row(k).setZero(); break;
  case 3:
    B.col(k).setZero(); break;
  default:
    break;
  }

  RealQZ<MatrixType> qz(A,B);

  VERIFY_IS_EQUAL(qz.info(), Success);
  // check for zeros
  bool all_zeros = true;
  for (Index i=0; i<A.cols(); i++)
    for (Index j=0; j<i; j++) {
      if (abs(qz.matrixT()(i,j))!=Scalar(0.0))
        all_zeros = false;
      if (j<i-1 && abs(qz.matrixS()(i,j))!=Scalar(0.0))
        all_zeros = false;
      if (j==i-1 && j>0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))
        all_zeros = false;
    }
  VERIFY_IS_EQUAL(all_zeros, true);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));
  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));
}

void test_real_qz()
{
  int s = 0;
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( real_qz(Matrix4f()) );
    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );

    // some trivial but implementation-wise tricky cases
    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );
    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );
    CALL_SUBTEST_3( real_qz(Matrix<double,1,1>()) );
    CALL_SUBTEST_4( real_qz(Matrix2d()) );
  }

  TEST_SET_BUT_UNUSED_VARIABLE(s)
}
<|endoftext|>