<commit_before>// ----------------------------------------------------------------------------
// Copyright 2017 Nervana Systems Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// ----------------------------------------------------------------------------

#include <cassert>
#include <list>
#include <memory>
#include <unordered_map>
#include <unordered_set>

#include "ngraph/autodiff/adjoints.hpp"
#include "ngraph/function.hpp"
#include "ngraph/node.hpp"
#include "ngraph/ops/add.hpp"
#include "ngraph/ops/broadcast.hpp"
#include "ngraph/ops/constant.hpp"
#include "ngraph/ops/convert.hpp"
#include "ngraph/ops/tuple.hpp"
#include "ngraph/types/type.hpp"

using namespace ngraph;

/// @brief Make a zero matching a value type.
std::shared_ptr<Node> make_zero(const std::shared_ptr<const ValueType>& value_type);

std::shared_ptr<Node> make_zero(const std::shared_ptr<const TensorViewType>& tensor_view_type)
{
    std::shared_ptr<Node> zero =
        std::make_shared<op::Constant>(tensor_view_type->get_element_type(), Shape{}, "0");
    const Shape& shape = tensor_view_type->get_shape();
    if (shape.size() > 0)
    {
        AxisSet axes;
        for (size_t i = 0; i < shape.size(); i++)
        {
            axes.insert(i);
        }
        zero = std::make_shared<op::Broadcast>(zero, shape, axes);
    }
    return zero;
}

std::shared_ptr<Node> make_zero(const std::shared_ptr<const TupleType>& tuple_type)
{
    std::vector<std::shared_ptr<Node>> elements;
    for (auto& value_type : tuple_type->get_element_types())
    {
        elements.push_back(make_zero(value_type));
    }
    return std::make_shared<op::Tuple>(elements);
}

std::shared_ptr<Node> make_zero(const std::shared_ptr<const ValueType>& value_type)
{
    std::shared_ptr<const TensorViewType> tensor_view_type =
        std::dynamic_pointer_cast<const TensorViewType>(value_type);
    if (nullptr != tensor_view_type)
    {
        return (make_zero(tensor_view_type));
    }
    std::shared_ptr<const TupleType> tuple_type =
        std::dynamic_pointer_cast<const TupleType>(value_type);
    if (nullptr != tuple_type)
    {
        return make_zero(tuple_type);
    }
    // Should be impossible
    throw ngraph_error("Unknown value type");
}

autodiff::Adjoints::Adjoints(const std::shared_ptr<Node>& y, const std::shared_ptr<Node>& c)
{
    // Pass 1 determines which nodes contribute to y as well as setting up a reverse
    // topological sort.

    // Number of nodes that use the node's value
    std::unordered_map<std::shared_ptr<Node>, size_t> parent_counts;

    // Nodes that have been processed
    std::unordered_set<std::shared_ptr<Node>> visited_nodes;

    // Nodes we should check
    std::list<std::shared_ptr<Node>> nodes_to_check;
    nodes_to_check.push_front(y);
    while (nodes_to_check.size() > 0)
    {
        auto node = nodes_to_check.front();
        nodes_to_check.pop_front();
        if (visited_nodes.count(node) != 0)
        {
            continue;
        }
        for (auto arg : node->get_arguments())
        {
            auto count_it = parent_counts.find(arg);
            if (count_it == parent_counts.end())
            {
                parent_counts[arg] = 1;
                nodes_to_check.push_front(arg);
            }
            else
            {
                parent_counts[arg]++;
            }
        }
        visited_nodes.insert(node);
    }

    // Second pass visits the nodes so that all users of a node's value are visited
    // before a node is visited.
    m_adjoint_map[y.get()] = c;
    nodes_to_check.push_front(y);
    while (nodes_to_check.size() > 0)
    {
        auto node = nodes_to_check.front();
        nodes_to_check.pop_front();
        // Look for nodes that will be available when this node is done
        for (auto arg : node->get_arguments())
        {
            auto count_it = parent_counts.find(arg);
            count_it->second--;
            if (0 == count_it->second)
            {
                nodes_to_check.push_front(arg);
            }
        }
        node->generate_adjoints(*this, m_adjoint_map.at(node.get()));
    }
}

std::shared_ptr<Node> autodiff::Adjoints::get(const std::shared_ptr<Node>& x)
{
    auto adjoint_it = m_adjoint_map.find(x.get());
    if (m_adjoint_map.end() == adjoint_it)
    {
        auto result = make_zero(x->get_value_type());
        adjoint_it = m_adjoint_map.insert({x.get(), result}).first;
    }
    return adjoint_it->second;
}

void autodiff::Adjoints::add_delta(const std::shared_ptr<Node>& x,
                                   const std::shared_ptr<Node>& delta)
{
    assert(*x->get_value_type() == *delta->get_value_type());
    auto adjoint_it = m_adjoint_map.find(x.get());
    if (m_adjoint_map.end() == adjoint_it)
    {
        m_adjoint_map.insert({x.get(), delta});
    }
    else
    {
        m_adjoint_map.insert({x.get(), std::make_shared<op::Add>(adjoint_it->second, delta)});
    }
}
<commit_msg>Update map correctly; fixes autodiff from two sources bug.<commit_after>// ----------------------------------------------------------------------------
// Copyright 2017 Nervana Systems Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// ----------------------------------------------------------------------------

#include <cassert>
#include <list>
#include <memory>
#include <unordered_map>
#include <unordered_set>

#include "ngraph/autodiff/adjoints.hpp"
#include "ngraph/function.hpp"
#include "ngraph/node.hpp"
#include "ngraph/ops/add.hpp"
#include "ngraph/ops/broadcast.hpp"
#include "ngraph/ops/constant.hpp"
#include "ngraph/ops/convert.hpp"
#include "ngraph/ops/tuple.hpp"
#include "ngraph/types/type.hpp"

using namespace ngraph;

/// @brief Make a zero matching a value type.
std::shared_ptr<Node> make_zero(const std::shared_ptr<const ValueType>& value_type);

std::shared_ptr<Node> make_zero(const std::shared_ptr<const TensorViewType>& tensor_view_type)
{
    std::shared_ptr<Node> zero =
        std::make_shared<op::Constant>(tensor_view_type->get_element_type(), Shape{}, "0");
    const Shape& shape = tensor_view_type->get_shape();
    if (shape.size() > 0)
    {
        AxisSet axes;
        for (size_t i = 0; i < shape.size(); i++)
        {
            axes.insert(i);
        }
        zero = std::make_shared<op::Broadcast>(zero, shape, axes);
    }
    return zero;
}

std::shared_ptr<Node> make_zero(const std::shared_ptr<const TupleType>& tuple_type)
{
    std::vector<std::shared_ptr<Node>> elements;
    for (auto& value_type : tuple_type->get_element_types())
    {
        elements.push_back(make_zero(value_type));
    }
    return std::make_shared<op::Tuple>(elements);
}

std::shared_ptr<Node> make_zero(const std::shared_ptr<const ValueType>& value_type)
{
    std::shared_ptr<const TensorViewType> tensor_view_type =
        std::dynamic_pointer_cast<const TensorViewType>(value_type);
    if (nullptr != tensor_view_type)
    {
        return (make_zero(tensor_view_type));
    }
    std::shared_ptr<const TupleType> tuple_type =
        std::dynamic_pointer_cast<const TupleType>(value_type);
    if (nullptr != tuple_type)
    {
        return make_zero(tuple_type);
    }
    // Should be impossible
    throw ngraph_error("Unknown value type");
}

autodiff::Adjoints::Adjoints(const std::shared_ptr<Node>& y, const std::shared_ptr<Node>& c)
{
    // Pass 1 determines which nodes contribute to y as well as setting up a reverse
    // topological sort.

    // Number of nodes that use the node's value
    std::unordered_map<std::shared_ptr<Node>, size_t> parent_counts;

    // Nodes that have been processed
    std::unordered_set<std::shared_ptr<Node>> visited_nodes;

    // Nodes we should check
    std::list<std::shared_ptr<Node>> nodes_to_check;
    nodes_to_check.push_front(y);
    while (nodes_to_check.size() > 0)
    {
        auto node = nodes_to_check.front();
        nodes_to_check.pop_front();
        if (visited_nodes.count(node) != 0)
        {
            continue;
        }
        for (auto arg : node->get_arguments())
        {
            auto count_it = parent_counts.find(arg);
            if (count_it == parent_counts.end())
            {
                parent_counts[arg] = 1;
                nodes_to_check.push_front(arg);
            }
            else
            {
                parent_counts[arg]++;
            }
        }
        visited_nodes.insert(node);
    }

    // Second pass visits the nodes so that all users of a node's value are visited
    // before a node is visited.
    m_adjoint_map[y.get()] = c;
    nodes_to_check.push_front(y);
    while (nodes_to_check.size() > 0)
    {
        auto node = nodes_to_check.front();
        nodes_to_check.pop_front();
        // Look for nodes that will be available when this node is done
        for (auto arg : node->get_arguments())
        {
            auto count_it = parent_counts.find(arg);
            count_it->second--;
            if (0 == count_it->second)
            {
                nodes_to_check.push_front(arg);
            }
        }
        node->generate_adjoints(*this, m_adjoint_map.at(node.get()));
    }
}

std::shared_ptr<Node> autodiff::Adjoints::get(const std::shared_ptr<Node>& x)
{
    auto adjoint_it = m_adjoint_map.find(x.get());
    if (m_adjoint_map.end() == adjoint_it)
    {
        auto result = make_zero(x->get_value_type());
        adjoint_it = m_adjoint_map.insert({x.get(), result}).first;
    }
    return adjoint_it->second;
}

void autodiff::Adjoints::add_delta(const std::shared_ptr<Node>& x,
                                   const std::shared_ptr<Node>& delta)
{
    assert(*x->get_value_type() == *delta->get_value_type());
    auto adjoint_it = m_adjoint_map.find(x.get());
    if (m_adjoint_map.end() == adjoint_it)
    {
        m_adjoint_map.insert({x.get(), delta});
    }
    else
    {
        adjoint_it->second = std::make_shared<op::Add>(adjoint_it->second, delta);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pal.h"
#include "utils.h"
#include "trace.h"
#include "libhost.h"
#include "host_startup_info.h"

void get_runtime_config_paths_from_app(const pal::string_t& app, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(app);
    auto path = get_directory(app);

    get_runtime_config_paths(path, name, cfg, dev_cfg);
}

void get_runtime_config_paths_from_arg(const pal::string_t& arg, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(arg);

    auto json_name = name + _X(".json");
    auto dev_json_name = name + _X(".dev.json");

    auto json_path = get_directory(arg);
    auto dev_json_path = json_path;

    append_path(&json_path, json_name.c_str());
    append_path(&dev_json_path, dev_json_name.c_str());

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());

    dev_cfg->assign(dev_json_path);
    cfg->assign(json_path);
}

void get_runtime_config_paths(const pal::string_t& path, const pal::string_t& name, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto json_path = path;
    auto json_name = name + _X(".runtimeconfig.json");
    append_path(&json_path, json_name.c_str());
    cfg->assign(json_path);

    auto dev_json_path = path;
    auto dev_json_name = name + _X(".runtimeconfig.dev.json");
    append_path(&dev_json_path, dev_json_name.c_str());
    dev_cfg->assign(dev_json_path);

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());
}

host_mode_t detect_operating_mode(const host_startup_info_t& host_info)
{
    if (coreclr_exists_in_dir(host_info.dotnet_root))
    {
        // Detect between standalone apphost or legacy split mode (specifying --depsfile and --runtimeconfig)

        pal::string_t deps_in_dotnet_root = host_info.dotnet_root;
        pal::string_t deps_filename = host_info.get_app_name() + _X(".deps.json");
        append_path(&deps_in_dotnet_root, deps_filename.c_str());
        bool deps_exists = pal::file_exists(deps_in_dotnet_root);

        trace::info(_X("Detecting mode... CoreCLR present in dotnet root [%d] and checking if [%s] file present=[%d]"),
            host_info.dotnet_root.c_str(), deps_filename.c_str(), deps_exists);

        // Name of runtimeconfig file; since no path is included here the check is in the current working directory
        pal::string_t config_in_cwd = host_info.get_app_name() + _X(".runtimeconfig.json");

        return (deps_exists || !pal::file_exists(config_in_cwd)) && pal::file_exists(host_info.app_path) ? host_mode_t::apphost : host_mode_t::split_fx;
    }

    if (pal::file_exists(host_info.app_path))
    {
        // Framework-dependent apphost
        return host_mode_t::apphost;
    }

    return host_mode_t::muxer;
}

void try_patch_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading patch roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_star = start_ver.patch_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering patch roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, true))
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Patch roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}

void try_prerelease_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading prerelease roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_pat_star = start_ver.prerelease_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_pat_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering prerelease roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, false)
            && ver.is_prerelease()) // Pre-release can roll forward to only pre-release
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Prerelease roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}
<commit_msg>Fix tracing of a string to show the string and not the address. (#4977)<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pal.h"
#include "utils.h"
#include "trace.h"
#include "libhost.h"
#include "host_startup_info.h"

void get_runtime_config_paths_from_app(const pal::string_t& app, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(app);
    auto path = get_directory(app);

    get_runtime_config_paths(path, name, cfg, dev_cfg);
}

void get_runtime_config_paths_from_arg(const pal::string_t& arg, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto name = get_filename_without_ext(arg);

    auto json_name = name + _X(".json");
    auto dev_json_name = name + _X(".dev.json");

    auto json_path = get_directory(arg);
    auto dev_json_path = json_path;

    append_path(&json_path, json_name.c_str());
    append_path(&dev_json_path, dev_json_name.c_str());

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());

    dev_cfg->assign(dev_json_path);
    cfg->assign(json_path);
}

void get_runtime_config_paths(const pal::string_t& path, const pal::string_t& name, pal::string_t* cfg, pal::string_t* dev_cfg)
{
    auto json_path = path;
    auto json_name = name + _X(".runtimeconfig.json");
    append_path(&json_path, json_name.c_str());
    cfg->assign(json_path);

    auto dev_json_path = path;
    auto dev_json_name = name + _X(".runtimeconfig.dev.json");
    append_path(&dev_json_path, dev_json_name.c_str());
    dev_cfg->assign(dev_json_path);

    trace::verbose(_X("Runtime config is cfg=%s dev=%s"), json_path.c_str(), dev_json_path.c_str());
}

host_mode_t detect_operating_mode(const host_startup_info_t& host_info)
{
    if (coreclr_exists_in_dir(host_info.dotnet_root))
    {
        // Detect between standalone apphost or legacy split mode (specifying --depsfile and --runtimeconfig)

        pal::string_t deps_in_dotnet_root = host_info.dotnet_root;
        pal::string_t deps_filename = host_info.get_app_name() + _X(".deps.json");
        append_path(&deps_in_dotnet_root, deps_filename.c_str());
        bool deps_exists = pal::file_exists(deps_in_dotnet_root);

        trace::info(_X("Detecting mode... CoreCLR present in dotnet root [%s] and checking if [%s] file present=[%d]"),
            host_info.dotnet_root.c_str(), deps_filename.c_str(), deps_exists);

        // Name of runtimeconfig file; since no path is included here the check is in the current working directory
        pal::string_t config_in_cwd = host_info.get_app_name() + _X(".runtimeconfig.json");

        return (deps_exists || !pal::file_exists(config_in_cwd)) && pal::file_exists(host_info.app_path) ? host_mode_t::apphost : host_mode_t::split_fx;
    }

    if (pal::file_exists(host_info.app_path))
    {
        // Framework-dependent apphost
        return host_mode_t::apphost;
    }

    return host_mode_t::muxer;
}

void try_patch_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading patch roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_star = start_ver.patch_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering patch roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, true))
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Patch roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}

void try_prerelease_roll_forward_in_dir(const pal::string_t& cur_dir, const fx_ver_t& start_ver, pal::string_t* max_str)
{
    pal::string_t path = cur_dir;

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Reading prerelease roll forward candidates in dir [%s] for version [%s]"), path.c_str(), start_str.c_str());
    }

    pal::string_t maj_min_pat_star = start_ver.prerelease_glob();

    std::vector<pal::string_t> list;
    pal::readdir_onlydirectories(path, maj_min_pat_star, &list);

    fx_ver_t max_ver = start_ver;
    fx_ver_t ver;
    for (const auto& str : list)
    {
        trace::verbose(_X("Considering prerelease roll forward candidate version [%s]"), str.c_str());
        if (fx_ver_t::parse(str, &ver, false)
            && ver.is_prerelease()) // Pre-release can roll forward to only pre-release
        {
            max_ver = std::max(ver, max_ver);
        }
    }
    max_str->assign(max_ver.as_str());

    if (trace::is_enabled())
    {
        pal::string_t start_str = start_ver.as_str();
        trace::verbose(_X("Prerelease roll forwarded [%s] -> [%s] in [%s]"), start_str.c_str(), max_str->c_str(), path.c_str());
    }
}
<|endoftext|>


<commit_before>#include "CPPFORT/lctrk.h"

#include "lcio.h"
#include "IMPL/TrackImpl.h"
#include "LCIOSTLTypes.h"

using namespace lcio ;

#include <iostream>

#define NCOVARIANCE 10

// create delete ReconstructedParticle

PTRTYPE lctrkcreate(){
  TrackImpl* trk = new TrackImpl ;
  return C2F_POINTER( LCObject*, trk ) ;
}
int lctrkdelete( PTRTYPE track ){
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  delete trk ;
  return LCIO::SUCCESS ;
}

// get Methods

int lctrkid( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->id() ;
}

int lctrkgettype( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getType() ;
}

int lctrktesttype( PTRTYPE track , int bit )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->testType( bit ) ;
}

// float lctrkgetmomentum( PTRTYPE track )  {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   return trk->getMomentum() ;
// }

float lctrkgetomega( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getOmega() ;
}

// float lctrkgettheta( PTRTYPE track ) {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   return trk->getTheta() ;
// }

float lctrkgettanlambda( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getTanLambda() ;
}

float lctrkgetphi( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getPhi() ;
}

float lctrkgetd0( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getD0() ;
}

float lctrkgetz0( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getZ0() ;
}

int lctrkgetcovmatrix( PTRTYPE track, float cvmtx[NCOVARIANCE] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  for( int i=0 ; i<NCOVARIANCE ;  cvmtx[i] = trk->getCovMatrix()[i++]  ) ;
  return LCIO::SUCCESS ;
}

int lctrkgetreferencepoint( PTRTYPE track, float* refpoint ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  for( int i=0 ; i<3 ;  *refpoint++ = trk->getReferencePoint()[i++]  ) ;
  return LCIO::SUCCESS ;
}

int lctrkisreferencepointpca( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->isReferencePointPCA() ;
}

float lctrkgetchi2( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getChi2() ;
}

int lctrkgetndf( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getNdf() ;
}

float lctrkgetdedx( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getdEdx() ;
}

float lctrkgetdedxerror( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getdEdxError() ;
}

float lctrkgetradiusofinnermosthit( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getRadiusOfInnermostHit() ;
}

PTRTYPE lctrkgetsubdetectorhitnumbers( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  const IntVec& nums = trk->getSubdetectorHitNumbers();
  return reinterpret_cast<PTRTYPE>( &nums );
}

PTRTYPE lctrkgettracks( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  const TrackVec& idvect = trk->getTracks();
  return reinterpret_cast<PTRTYPE>( &idvect );
}

PTRTYPE lctrkgettrackerhits( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  const TrackerHitVec& idvect = trk->getTrackerHits();
  return reinterpret_cast<PTRTYPE>( &idvect );
}

// set,add Methods

// int lctrksettype( PTRTYPE track, int type ) {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   trk->setType( type ) ;
//   return LCIO::SUCCESS ;
// }

int lctrksettypebit( PTRTYPE track, int index ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setTypeBit( index ) ;
  return LCIO::SUCCESS ;
}

int lctrksetomega( PTRTYPE track, float omega ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
   trk->setOmega( omega ) ;
   return LCIO::SUCCESS ;
}

int lctrksettanlambda( PTRTYPE track, float tanLambda ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setTanLambda( tanLambda ) ;
  return LCIO::SUCCESS ;
}

int lctrksetphi( PTRTYPE track, float phi ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setPhi( phi ) ;
  return LCIO::SUCCESS ;
}

int lctrksetd0( PTRTYPE track, float d0 ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setD0( d0 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetz0( PTRTYPE track, float z0 ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setZ0( z0 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetcovmatrix( PTRTYPE track, float cvmtx[NCOVARIANCE] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setCovMatrix( cvmtx ) ;
  return LCIO::SUCCESS ;
}

int lctrksetreferencepoint( PTRTYPE track, float refpoint[3] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setReferencePoint( refpoint ) ;
  return LCIO::SUCCESS ;
}

int lctrksetisreferencepointpca( PTRTYPE track , int val) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setIsReferencePointPCA( val ) ;
  return LCIO::SUCCESS ;
}

int lctrksetchi2( PTRTYPE track, float chi2) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setChi2( chi2 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetndf( PTRTYPE track, int ndf) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setNdf( ndf ) ;
  return LCIO::SUCCESS ;
}

int lctrksetdedx( PTRTYPE track, float dedx) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setdEdx( dedx ) ;
  return LCIO::SUCCESS ;
}

int lctrksetdedxerror( PTRTYPE track, float dedxerr) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setdEdxError( dedxerr ) ;
  return LCIO::SUCCESS ;
}

int lctrksetradiusofinnermosthit( PTRTYPE track, float r) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setRadiusOfInnermostHit( r ) ;
  return LCIO::SUCCESS ;
}

int lctrkaddtrack( PTRTYPE track, PTRTYPE addtrack ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  Track* addtrk = f2c_pointer<Track,LCObject>( addtrack ) ;
  trk->addTrack( addtrk ) ;
  return LCIO::SUCCESS ;
}

int lctrkaddhit( PTRTYPE track, PTRTYPE hit ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  TrackerHit* addhit = f2c_pointer<TrackerHit,LCObject>( hit ) ;
  trk->addHit( addhit ) ;
  return LCIO::SUCCESS ;
}

int     lctrksetsubdetectorhitnumbers( PTRTYPE track, int* intv, const int nintv ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  IntVec& intVec =  trk->subdetectorHitNumbers() ;
  intVec.resize( nintv ) ;
  for(int j=0;j<nintv;j++) {
    intVec[j] =  intv[j]  ;
  }
  return LCIO::SUCCESS ;
}

<commit_msg>subdetectorHitNumbers get/set functions added<commit_after>#include "CPPFORT/lctrk.h"

#include "lcio.h"
#include "IMPL/TrackImpl.h"
#include "LCIOSTLTypes.h"

using namespace lcio ;

#include <iostream>

#define NCOVARIANCE 10

// create delete ReconstructedParticle

PTRTYPE lctrkcreate(){
  TrackImpl* trk = new TrackImpl ;
  return C2F_POINTER( LCObject*, trk ) ;
}
int lctrkdelete( PTRTYPE track ){
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  delete trk ;
  return LCIO::SUCCESS ;
}

// get Methods

int lctrkid( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->id() ;
}

int lctrkgettype( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getType() ;
}

int lctrktesttype( PTRTYPE track , int bit )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->testType( bit ) ;
}

// float lctrkgetmomentum( PTRTYPE track )  {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   return trk->getMomentum() ;
// }

float lctrkgetomega( PTRTYPE track )  {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getOmega() ;
}

// float lctrkgettheta( PTRTYPE track ) {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   return trk->getTheta() ;
// }

float lctrkgettanlambda( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getTanLambda() ;
}

float lctrkgetphi( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getPhi() ;
}

float lctrkgetd0( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getD0() ;
}

float lctrkgetz0( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getZ0() ;
}

int lctrkgetcovmatrix( PTRTYPE track, float cvmtx[NCOVARIANCE] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  for( int i=0 ; i<NCOVARIANCE ;  cvmtx[i] = trk->getCovMatrix()[i++]  ) ;
  return LCIO::SUCCESS ;
}

int lctrkgetreferencepoint( PTRTYPE track, float* refpoint ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  for( int i=0 ; i<3 ;  *refpoint++ = trk->getReferencePoint()[i++]  ) ;
  return LCIO::SUCCESS ;
}

int lctrkisreferencepointpca( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->isReferencePointPCA() ;
}

float lctrkgetchi2( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getChi2() ;
}

int lctrkgetndf( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getNdf() ;
}

float lctrkgetdedx( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getdEdx() ;
}

float lctrkgetdedxerror( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getdEdxError() ;
}

float lctrkgetradiusofinnermosthit( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  return trk->getRadiusOfInnermostHit() ;
}

int     lctrkgetsubdetectorhitnumbers( PTRTYPE track, int* intv, int* nintv ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  IntVec& intVec =  trk->subdetectorHitNumbers() ;
  int n = intVec.size() ;
  if (n > *nintv) {
    std::cerr << "Warning in lctrkgetsubdetectorhitnumbers: vector size " <<  n
              << " larger then target array size " << *nintv << std::endl ;
      n = *nintv ;
  }
  for(int j=0;j<n;j++) {
    intv[j] = intVec[j] ;
  }
  *nintv = n ;
  return LCIO::SUCCESS ;
}

PTRTYPE lctrkgettracks( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  const TrackVec& idvect = trk->getTracks();
  return reinterpret_cast<PTRTYPE>( &idvect );
}

PTRTYPE lctrkgettrackerhits( PTRTYPE track ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  const TrackerHitVec& idvect = trk->getTrackerHits();
  return reinterpret_cast<PTRTYPE>( &idvect );
}

// set,add Methods

// int lctrksettype( PTRTYPE track, int type ) {
//   TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
//   trk->setType( type ) ;
//   return LCIO::SUCCESS ;
// }

int lctrksettypebit( PTRTYPE track, int index ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setTypeBit( index ) ;
  return LCIO::SUCCESS ;
}

int lctrksetomega( PTRTYPE track, float omega ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
   trk->setOmega( omega ) ;
   return LCIO::SUCCESS ;
}

int lctrksettanlambda( PTRTYPE track, float tanLambda ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setTanLambda( tanLambda ) ;
  return LCIO::SUCCESS ;
}

int lctrksetphi( PTRTYPE track, float phi ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setPhi( phi ) ;
  return LCIO::SUCCESS ;
}

int lctrksetd0( PTRTYPE track, float d0 ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setD0( d0 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetz0( PTRTYPE track, float z0 ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setZ0( z0 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetcovmatrix( PTRTYPE track, float cvmtx[NCOVARIANCE] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setCovMatrix( cvmtx ) ;
  return LCIO::SUCCESS ;
}

int lctrksetreferencepoint( PTRTYPE track, float refpoint[3] ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setReferencePoint( refpoint ) ;
  return LCIO::SUCCESS ;
}

int lctrksetisreferencepointpca( PTRTYPE track , int val) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setIsReferencePointPCA( val ) ;
  return LCIO::SUCCESS ;
}

int lctrksetchi2( PTRTYPE track, float chi2) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setChi2( chi2 ) ;
  return LCIO::SUCCESS ;
}

int lctrksetndf( PTRTYPE track, int ndf) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setNdf( ndf ) ;
  return LCIO::SUCCESS ;
}

int lctrksetdedx( PTRTYPE track, float dedx) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setdEdx( dedx ) ;
  return LCIO::SUCCESS ;
}

int lctrksetdedxerror( PTRTYPE track, float dedxerr) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setdEdxError( dedxerr ) ;
  return LCIO::SUCCESS ;
}

int lctrksetradiusofinnermosthit( PTRTYPE track, float r) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  trk->setRadiusOfInnermostHit( r ) ;
  return LCIO::SUCCESS ;
}

int lctrkaddtrack( PTRTYPE track, PTRTYPE addtrack ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  Track* addtrk = f2c_pointer<Track,LCObject>( addtrack ) ;
  trk->addTrack( addtrk ) ;
  return LCIO::SUCCESS ;
}

int lctrkaddhit( PTRTYPE track, PTRTYPE hit ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  TrackerHit* addhit = f2c_pointer<TrackerHit,LCObject>( hit ) ;
  trk->addHit( addhit ) ;
  return LCIO::SUCCESS ;
}

int     lctrksetsubdetectorhitnumbers( PTRTYPE track, int* intv, const int nintv ) {
  TrackImpl* trk = f2c_pointer<TrackImpl,LCObject>( track ) ;
  IntVec& intVec =  trk->subdetectorHitNumbers() ;
  intVec.resize( nintv ) ;
  for(int j=0;j<nintv;j++) {
    intVec[j] =  intv[j]  ;
  }
  return LCIO::SUCCESS ;
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
///
/// Copyright (c) 2016 Slava Melanko.
///
/// This code is licensed under the MIT License (MIT).
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
///
///////////////////////////////////////////////////////////////////////////////

#include "creational/Singleton.h"

namespace pattern
{
namespace creational
{

Session& Session::GetInstance()
{
	static Session session;
	return &session;
}

} // namespace creational
} // namespace pattern
<commit_msg>Session::GetInstance has been fixed.<commit_after>///////////////////////////////////////////////////////////////////////////////
///
/// Copyright (c) 2016 Slava Melanko.
///
/// This code is licensed under the MIT License (MIT).
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
///
///////////////////////////////////////////////////////////////////////////////

#include "creational/Singleton.h"

namespace pattern
{
namespace creational
{

Session& Session::GetInstance() noexcept
{
	static Session instance;
	return instance;
}

} // namespace creational
} // namespace pattern
<|endoftext|>


<commit_before>// Copyright 2016 Alex Silva Torres
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "cmd-exec.h"

#include <cstring>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/shm.h>

#include "interpreter/cmd-executor.h"

namespace seti {
namespace internal {

int ExecCmd(std::vector<std::string>&& args) {
  char** p_args = new char*[args.size() + 1];

  for (size_t i = 0; i < args.size(); i++) {
    p_args[i] = const_cast<char*>(args[i].data());
  }

  p_args[args.size()] = NULL;

  int ret = execvp(p_args[0], p_args);

  delete[] p_args;

  return ret;
}

int WaitCmd(int pid) {
  int status;

  waitpid(pid,&status,0);
  return status;
}

void Process::LaunchProcess(int infile, int outfile, int errfile, pid_t pgid,
                            bool foreground) {
  pid_t pid;
  bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();
  int shell_terminal = EnvShell::instance()->shell_terminal();

  if (shell_is_interactive) {
    // Put the process into the process group and give the process group
    // the terminal, if appropriate.
    // This has to be done both by the shell and in the individual
    // child processes because of potential race conditions.
    pid = getpid ();

    if (pgid == 0) {
      pgid = pid;
    }

    setpgid (pid, pgid);

    if (foreground) {
      tcsetpgrp (shell_terminal, pgid);
    }

    /* Set the handling for job control signals back to the default.  */
    signal (SIGINT, SIG_DFL);
    signal (SIGQUIT, SIG_DFL);
    signal (SIGTSTP, SIG_DFL);
    signal (SIGTTIN, SIG_DFL);
    signal (SIGTTOU, SIG_DFL);
    signal (SIGCHLD, SIG_DFL);
  }

  // set the standard input/output channels of the new process
  if (infile != STDIN_FILENO) {
    dup2 (infile, STDIN_FILENO);
    close (infile);
  }

  if (outfile != STDOUT_FILENO) {
    dup2 (outfile, STDOUT_FILENO);
    close (outfile);
  }

  if (errfile != STDERR_FILENO) {
    dup2 (errfile, STDERR_FILENO);
    close (errfile);
  }

  CmdEntryPtr cmd = sym_tab_.LookupCmd(args_[0]);

  if (cmd) {
    LaunchCmd(cmd);
    exit(0);
  }

  CmdSharedError *err = (CmdSharedError*)
      shmat(EnvShell::instance()->shmid(), 0, 0);
  err->error = false;

  // Exec the new process
  execvp (argv_[0], argv_);

  // set error on memory region
  err->error = true;
  err->except_code = static_cast<int>(RunTimeError::ErrorCode::INVALID_COMMAND);
  err->err_code = errno;
  int len = std::strlen(argv_[0]);
  len = len >= SETI_CMD_SIZE_MAX? SETI_CMD_SIZE_MAX-1: len;
  memcpy(err->err_str, argv_[0], len);

  // set \0 to end string
  err->err_str[len] = '\0';

  shmdt(err);
  exit(-1);
}

void Process::LaunchCmd(CmdEntryPtr cmd) {
  cmd->Exec(parent_, std::move(args_));
}

int Job::MarkProcessStatus(pid_t pid, int status) {
  if (pid > 0) {
    for (auto& p: process_) {
      if (p.pid_ == pid) {
        p.status_ = status;
        if (WIFSTOPPED (status)) {
          p.stopped_ = true;
        } else {
          p.completed_ = true;
        }
        return 0;
      }
    }
  } else if (pid == 0 || errno == ECHILD) {
    /* No processes ready to report.  */
    return -1;
  }

  return -1;
}

bool Job::JobIsStopped() {
  for (auto& p: process_) {
    if (!p.completed_ && !p.stopped_) {
      return false;
    }
  }

  return true;
}

bool Job::JobIsCompleted() {
  for (auto& p: process_) {
    if (!p.completed_) {
      return false;
    }
  }

  return true;
}

void Job::WaitForJob() {
  pid_t pid;
  int status;

  do {
    pid = waitpid (WAIT_ANY, &status, WUNTRACED);
  } while (!MarkProcessStatus(pid, status)
           && !JobIsStopped() && !JobIsCompleted());

  signal(SIGCHLD, SIG_IGN);
}

int Job::Status() {
  int status = 0;

  for (auto& p: process_) {
    status |= p.status_;
  }

  return status;
}

void Job::PutJobInForeground(int cont) {
  int shell_terminal = EnvShell::instance()->shell_terminal();
  struct termios* tmodes = EnvShell::instance()->shell_tmodes();
  pid_t shell_pgid = EnvShell::instance()->shell_pgid();

  // put the job into the foreground
  tcsetpgrp (shell_terminal, pgid_);

  // send the job a continue signal, if necessary
  if (cont) {
    tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes_);
    if (kill (- pgid_, SIGCONT) < 0) {
      perror ("kill (SIGCONT)");
    }
  }

  // wait for it to report
  WaitForJob();

  // put the shell back in the foreground
  tcsetpgrp(shell_terminal, shell_pgid);

  /* Restore the shell’s terminal modes.  */
  tcgetattr(shell_terminal, &shell_tmodes_);
  tcsetattr(shell_terminal, TCSADRAIN, tmodes);
}

void Job::PutJobInBackground(int cont) {
  /* Send the job a continue signal, if necessary.  */
  if (cont) {
    if (kill (-pgid_, SIGCONT) < 0)
      perror ("kill (SIGCONT)");
  }
}

void Job::LaunchInternalCmd(CmdEntryPtr cmd) {
  static_cast<CmdInEntry&>(*cmd).SetStdFd(stdout_, stderr_, stdin_);
  cmd->Exec(parent_, std::move(process_[0].args_));

  if (stdin_ != STDIN_FILENO) {
    close (stdin_);
  }

  if (stdout_ != STDOUT_FILENO) {
    close (stdout_);
  }

  if (stderr_ != STDERR_FILENO) {
    close (stderr_);
  }
}

void Job::LaunchJob(int foreground) {
  // executes commands that change self process status
  // commands like cd and exit must be executed this way
  if (process_.size() == 1) {
    CmdEntryPtr cmd = sym_tab_.LookupCmd(process_[0].args_[0]);

    if (cmd) {
      if (cmd->type() == CmdEntry::Type::kIn) {
        LaunchInternalCmd(cmd);
        return;
      }
    }
  }

  pid_t pid;
  int mypipe[2], infile, outfile;

  infile = stdin_;
  for (size_t i = 0; i < process_.size(); i++) {
    // set up pipes, if necessary
    if (i != (process_.size() - 1)) {
      if (pipe (mypipe) < 0) {
        perror ("pipe");
        exit (1);
      }

      outfile = mypipe[1];
    }
    else {
      outfile = stdout_;
    }

    // fork the child processes
    pid = fork ();
    if (pid == 0) {
      // this is the child process
      process_[i].LaunchProcess(infile, outfile, stderr_, pgid_, foreground);
    } else if (pid < 0) {
      // the fork failed
      perror ("fork");
      exit (1);
    } else {
      // this is the parent process
      process_[i].pid_ = pid;
      bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();

      if (shell_is_interactive) {
        if (!pgid_) {
          pgid_ = pid;
        }

        setpgid(pid, pgid_);
      }
    }

    // clean up after pipes
    if (infile != stdin_)
      close (infile);
    if (outfile != stdout_)
      close (outfile);
    infile = mypipe[0];
  }

  bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();

  if (!shell_is_interactive) {
    WaitForJob();
    CheckCmdError();
  } else if (foreground) {
    signal (SIGCHLD, SIG_DFL);
    PutJobInForeground(0);
    CheckCmdError();
  } else {
    PutJobInBackground(0);
  }
}

void Job::CheckCmdError() {
  // verify if there was some error executing command
  CmdSharedError *cmd_err = (CmdSharedError *) shmat(
        EnvShell::instance()->shmid(), 0, 0);

  CmdSharedError cpy_err;
  std::memcpy(&cpy_err, cmd_err, sizeof(CmdSharedError));

  shmdt(cmd_err);
  if (cpy_err.error) {
        throw RunTimeError(RunTimeError::ErrorCode::INVALID_COMMAND,
                           boost::format("%1%: %2%")%
                           cpy_err.err_str %strerror(cpy_err.err_code));
  }
}

}
}
<commit_msg>fix stuck problem on tcsetpgrp<commit_after>// Copyright 2016 Alex Silva Torres
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "cmd-exec.h"

#include <cstring>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/shm.h>

#include "interpreter/cmd-executor.h"

namespace seti {
namespace internal {

int ExecCmd(std::vector<std::string>&& args) {
  char** p_args = new char*[args.size() + 1];

  for (size_t i = 0; i < args.size(); i++) {
    p_args[i] = const_cast<char*>(args[i].data());
  }

  p_args[args.size()] = NULL;

  int ret = execvp(p_args[0], p_args);

  delete[] p_args;

  return ret;
}

int WaitCmd(int pid) {
  int status;

  waitpid(pid,&status,0);
  return status;
}

void Process::LaunchProcess(int infile, int outfile, int errfile, pid_t pgid,
                            bool foreground) {
  pid_t pid;
  bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();
  int shell_terminal = EnvShell::instance()->shell_terminal();

  if (shell_is_interactive) {
    // Put the process into the process group and give the process group
    // the terminal, if appropriate.
    // This has to be done both by the shell and in the individual
    // child processes because of potential race conditions.
    pid = getpid ();

    if (pgid == 0) {
      pgid = pid;
    }

    setpgid (pid, pgid);

    if (foreground) {
      // this part fix the problem fo stuck on tcsetpgrp
      // sources: https://dev.haiku-os.org/ticket/3417
      // https://dev.haiku-os.org/attachment/ticket/3417/tcsetpgrp-test.c
      sigset_t blocked;
      sigemptyset(&blocked);
      sigaddset(&blocked, SIGTTOU);
      pthread_sigmask(SIG_BLOCK, &blocked, NULL);
      tcsetpgrp(shell_terminal, pgid);
    }

    /* Set the handling for job control signals back to the default.  */
    signal (SIGINT, SIG_DFL);
    signal (SIGQUIT, SIG_DFL);
    signal (SIGTSTP, SIG_DFL);
    signal (SIGTTIN, SIG_DFL);
    signal (SIGTTOU, SIG_DFL);
    signal (SIGCHLD, SIG_DFL);
  }

  // set the standard input/output channels of the new process
  if (infile != STDIN_FILENO) {
    dup2 (infile, STDIN_FILENO);
    close (infile);
  }

  if (outfile != STDOUT_FILENO) {
    dup2 (outfile, STDOUT_FILENO);
    close (outfile);
  }

  if (errfile != STDERR_FILENO) {
    dup2 (errfile, STDERR_FILENO);
    close (errfile);
  }

  CmdEntryPtr cmd = sym_tab_.LookupCmd(args_[0]);

  if (cmd) {
    LaunchCmd(cmd);
    exit(0);
  }

  CmdSharedError *err = (CmdSharedError*)
      shmat(EnvShell::instance()->shmid(), 0, 0);
  err->error = false;

  // Exec the new process
  execvp (argv_[0], argv_);

  // set error on memory region
  err->error = true;
  err->except_code = static_cast<int>(RunTimeError::ErrorCode::INVALID_COMMAND);
  err->err_code = errno;
  int len = std::strlen(argv_[0]);
  len = len >= SETI_CMD_SIZE_MAX? SETI_CMD_SIZE_MAX-1: len;
  memcpy(err->err_str, argv_[0], len);

  // set \0 to end string
  err->err_str[len] = '\0';

  shmdt(err);
  exit(-1);
}

void Process::LaunchCmd(CmdEntryPtr cmd) {
  cmd->Exec(parent_, std::move(args_));
}

int Job::MarkProcessStatus(pid_t pid, int status) {
  if (pid > 0) {
    for (auto& p: process_) {
      if (p.pid_ == pid) {
        p.status_ = status;
        if (WIFSTOPPED (status)) {
          p.stopped_ = true;
        } else {
          p.completed_ = true;
        }
        return 0;
      }
    }
  } else if (pid == 0 || errno == ECHILD) {
    /* No processes ready to report.  */
    return -1;
  }

  return -1;
}

bool Job::JobIsStopped() {
  for (auto& p: process_) {
    if (!p.completed_ && !p.stopped_) {
      return false;
    }
  }

  return true;
}

bool Job::JobIsCompleted() {
  for (auto& p: process_) {
    if (!p.completed_) {
      return false;
    }
  }

  return true;
}

void Job::WaitForJob() {
  pid_t pid;
  int status;

  do {
    pid = waitpid (WAIT_ANY, &status, WUNTRACED);
  } while (!MarkProcessStatus(pid, status)
           && !JobIsStopped() && !JobIsCompleted());

  signal(SIGCHLD, SIG_IGN);
}

int Job::Status() {
  int status = 0;

  for (auto& p: process_) {
    status |= p.status_;
  }

  return status;
}

void Job::PutJobInForeground(int cont) {
  int shell_terminal = EnvShell::instance()->shell_terminal();
  struct termios* tmodes = EnvShell::instance()->shell_tmodes();
  pid_t shell_pgid = EnvShell::instance()->shell_pgid();

  // put the job into the foreground
  tcsetpgrp (shell_terminal, pgid_);

  // send the job a continue signal, if necessary
  if (cont) {
    tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes_);
    if (kill (- pgid_, SIGCONT) < 0) {
      perror ("kill (SIGCONT)");
    }
  }

  // wait for it to report
  WaitForJob();

  // put the shell back in the foreground
  tcsetpgrp(shell_terminal, shell_pgid);

  /* Restore the shell’s terminal modes.  */
  tcgetattr(shell_terminal, &shell_tmodes_);
  tcsetattr(shell_terminal, TCSADRAIN, tmodes);
}

void Job::PutJobInBackground(int cont) {
  /* Send the job a continue signal, if necessary.  */
  if (cont) {
    if (kill (-pgid_, SIGCONT) < 0)
      perror ("kill (SIGCONT)");
  }
}

void Job::LaunchInternalCmd(CmdEntryPtr cmd) {
  static_cast<CmdInEntry&>(*cmd).SetStdFd(stdout_, stderr_, stdin_);
  cmd->Exec(parent_, std::move(process_[0].args_));

  if (stdin_ != STDIN_FILENO) {
    close (stdin_);
  }

  if (stdout_ != STDOUT_FILENO) {
    close (stdout_);
  }

  if (stderr_ != STDERR_FILENO) {
    close (stderr_);
  }
}

void Job::LaunchJob(int foreground) {
  // executes commands that change self process status
  // commands like cd and exit must be executed this way
  if (process_.size() == 1) {
    CmdEntryPtr cmd = sym_tab_.LookupCmd(process_[0].args_[0]);

    if (cmd) {
      if (cmd->type() == CmdEntry::Type::kIn) {
        LaunchInternalCmd(cmd);
        return;
      }
    }
  }

  pid_t pid;
  int mypipe[2], infile, outfile;

  infile = stdin_;
  for (size_t i = 0; i < process_.size(); i++) {
    // set up pipes, if necessary
    if (i != (process_.size() - 1)) {
      if (pipe (mypipe) < 0) {
        perror ("pipe");
        exit (1);
      }

      outfile = mypipe[1];
    }
    else {
      outfile = stdout_;
    }

    // fork the child processes
    pid = fork ();
    if (pid == 0) {
      // this is the child process
      process_[i].LaunchProcess(infile, outfile, stderr_, pgid_, foreground);
    } else if (pid < 0) {
      // the fork failed
      perror ("fork");
      exit (1);
    } else {
      // this is the parent process
      process_[i].pid_ = pid;
      bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();

      if (shell_is_interactive) {
        if (!pgid_) {
          pgid_ = pid;
        }

        setpgid(pid, pgid_);
      }
    }

    // clean up after pipes
    if (infile != stdin_)
      close (infile);
    if (outfile != stdout_)
      close (outfile);
    infile = mypipe[0];
  }

  bool shell_is_interactive = EnvShell::instance()->shell_is_interactive();

  if (!shell_is_interactive) {
    WaitForJob();
    CheckCmdError();
  } else if (foreground) {
    signal (SIGCHLD, SIG_DFL);
    PutJobInForeground(0);
    CheckCmdError();
  } else {
    PutJobInBackground(0);
  }
}

void Job::CheckCmdError() {
  // verify if there was some error executing command
  CmdSharedError *cmd_err = (CmdSharedError *) shmat(
        EnvShell::instance()->shmid(), 0, 0);

  CmdSharedError cpy_err;
  std::memcpy(&cpy_err, cmd_err, sizeof(CmdSharedError));

  shmdt(cmd_err);
  if (cpy_err.error) {
        throw RunTimeError(RunTimeError::ErrorCode::INVALID_COMMAND,
                           boost::format("%1%: %2%")%
                           cpy_err.err_str %strerror(cpy_err.err_code));
  }
}

}
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/api/wordcount_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/common/string.hpp>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(WordCount, WordCountExample) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    auto line_to_words = [](std::string line, std::function<void(WordPair)> emit) {

                             std::vector<std::string> words = c7a::split(line,
                                                                         " ");
                             for (auto word : words) {
                                 if (word.length() > 1) {
                                     WordPair wp = std::make_pair(word, 1);
                                     emit(wp);
                                 }
                             }
                         };
    auto key = [](WordPair in) {
                   return in.first;
               };
    auto red_fn = [](WordPair in1, WordPair in2) {
                      WordPair wp = std::make_pair(in1.first, in1.second + in2.second);
                      return wp;
                  };

    auto lines = ReadFromFileSystem(
        ctx,
        "wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto word_pairs = lines.FlatMap(line_to_words);

    auto red_words = word_pairs.ReduceBy(key).With(red_fn);

    red_words.WriteToFileSystem("wordcount.out",
                                [](const WordPair& item) {
                                    std::string str;
                                    str += item.first;
                                    str += ":";
                                    str.append(std::to_string(item.second));
                                    return str;
                                });
}

int word_count_generated_nored(c7a::Context& ctx, size_t size) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    auto word_pair_gen = [](std::string line) {
                             WordPair wp = std::make_pair(line, 1);
                             return wp;
                         };

    auto lines = GenerateFromFile(
        ctx,
        "headwords",
        [](const std::string& line) {
            return line;
        },
        size);

    auto word_pairs = lines.Map(word_pair_gen);

    word_pairs.WriteToFileSystem("wordcount" + std::to_string(ctx.rank()) + ".out",
                                 [](const WordPair& item) {
                                     std::string str;
                                     str += item.first;
                                     str += ": ";
                                     str += std::to_string(item.second);
                                     return str;
                                 });
    return 0;
}

TEST(WordCount, GenerateAndWriteWith2Workers) {
    using c7a::Execute;

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(30000, 65000);
    const size_t port_base = distribution(generator);

    unsigned int workers = 2;

    unsigned int elements = 100;

    std::vector<std::thread> threads(workers);
    std::vector<char**> arguments(workers);
    std::vector<std::vector<std::string> > strargs(workers);

    for (size_t i = 0; i < workers; i++) {

        arguments[i] = new char*[workers + 3];
        strargs[i].resize(workers + 3);

        for (size_t j = 0; j < workers; j++) {
            strargs[i][j + 3] += "127.0.0.1:";
            strargs[i][j + 3] += std::to_string(port_base + j);
            arguments[i][j + 3] = const_cast<char*>(strargs[i][j + 3].c_str());
        }

        std::function<int(c7a::Context&)> start_func = [elements](c7a::Context& ctx) {
                                                           return word_count_generated_nored(ctx, elements);
                                                       };

        strargs[i][0] = "wordcount";
        arguments[i][0] = const_cast<char*>(strargs[i][0].c_str());
        strargs[i][1] = "-r";
        arguments[i][1] = const_cast<char*>(strargs[i][1].c_str());
        strargs[i][2] = std::to_string(i);
        arguments[i][2] = const_cast<char*>(strargs[i][2].c_str());
        threads[i] = std::thread([=]() { Execute(workers + 3, arguments[i], start_func); });
    }

    for (size_t i = 0; i < workers; i++) {
        threads[i].join();
    }
}

/******************************************************************************/
<commit_msg>less core, more clarity, wordcount_test.cpp<commit_after>/*******************************************************************************
 * tests/api/wordcount_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/common/string.hpp>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(WordCount, WordCountExample) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    auto line_to_words =
        [](std::string line, std::function<void(WordPair)> emit) {
        for (auto word : c7a::split(line, " ")) {
            if (word.length() > 1) {
                emit(std::make_pair(word, 1));
            }
        }
    };
    auto key = [](WordPair in) {
                   return in.first;
               };
    auto red_fn = [](WordPair in1, WordPair in2) {
                      return std::make_pair(in1.first, in1.second + in2.second);
                  };

    auto lines = ReadFromFileSystem(
        ctx,
        "wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto word_pairs = lines.FlatMap(line_to_words);

    auto red_words = word_pairs.ReduceBy(key).With(red_fn);

    red_words.WriteToFileSystem("wordcount.out",
                                [](const WordPair& item) {
                                    std::string str;
                                    str += item.first;
                                    str += ":";
                                    str.append(std::to_string(item.second));
                                    return str;
                                });
}

int word_count_generated_nored(c7a::Context& ctx, size_t size) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    auto word_pair_gen = [](std::string line) {
                             WordPair wp = std::make_pair(line, 1);
                             return wp;
                         };

    auto lines = GenerateFromFile(
        ctx,
        "headwords",
        [](const std::string& line) {
            return line;
        },
        size);

    auto word_pairs = lines.Map(word_pair_gen);

    word_pairs.WriteToFileSystem("wordcount" + std::to_string(ctx.rank())
                                 + ".out",
                                 [](const WordPair& item) {
                                     std::string str;
                                     str += item.first;
                                     str += ": ";
                                     str += std::to_string(item.second);
                                     return str;
                                 });
    return 0;
}

TEST(WordCount, GenerateAndWriteWith2Workers) {
    using c7a::Execute;

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(30000, 65000);
    const size_t port_base = distribution(generator);

    unsigned int workers = 2;

    unsigned int elements = 100;

    std::vector<std::thread> threads(workers);
    std::vector<char**> arguments(workers);
    std::vector<std::vector<std::string> > strargs(workers);

    for (size_t i = 0; i < workers; i++) {

        arguments[i] = new char*[workers + 3];
        strargs[i].resize(workers + 3);

        for (size_t j = 0; j < workers; j++) {
            strargs[i][j + 3] += "127.0.0.1:";
            strargs[i][j + 3] += std::to_string(port_base + j);
            arguments[i][j + 3] = const_cast<char*>(strargs[i][j + 3].c_str());
        }

        std::function<int(c7a::Context&)> start_func =
            [elements](c7a::Context& ctx) {
            return word_count_generated_nored(ctx, elements);
        };

        strargs[i][0] = "wordcount";
        arguments[i][0] = const_cast<char*>(strargs[i][0].c_str());
        strargs[i][1] = "-r";
        arguments[i][1] = const_cast<char*>(strargs[i][1].c_str());
        strargs[i][2] = std::to_string(i);
        arguments[i][2] = const_cast<char*>(strargs[i][2].c_str());
        threads[i] = std::thread([=]() {
                Execute(workers + 3, arguments[i], start_func); });
    }

    for (size_t i = 0; i < workers; i++) {
        threads[i].join();
    }
}

/******************************************************************************/
<|endoftext|>


<commit_before>#include "trikKit/robotModel/trikRobotModelBase.h"

#include <kitBase/robotModel/robotParts/display.h>
#include <kitBase/robotModel/robotParts/speaker.h>
#include <kitBase/robotModel/robotParts/button.h>
#include <kitBase/robotModel/robotParts/gyroscopeSensor.h>
#include <kitBase/robotModel/robotParts/accelerometerSensor.h>

#include <kitBase/robotModel/robotParts/encoderSensor.h>

#include <kitBase/robotModel/robotParts/lightSensor.h>

#include "trikKit/robotModel/parts/trikServoMotor.h"
#include "trikKit/robotModel/parts/trikPowerMotor.h"
#include "trikKit/robotModel/parts/trikInfraredSensor.h"
#include "trikKit/robotModel/parts/trikSonarSensor.h"
#include "trikKit/robotModel/parts/trikMotionSensor.h"
#include "trikKit/robotModel/parts/trikColorSensor.h"
#include "trikKit/robotModel/parts/trikLineSensor.h"
#include "trikKit/robotModel/parts/trikObjectSensor.h"
#include "trikKit/robotModel/parts/trikLed.h"
#include "trikKit/robotModel/parts/trikShell.h"
#include "trikKit/robotModel/parts/trikGamepadButton.h"
#include "trikKit/robotModel/parts/trikGamepadConnectionIndicator.h"
#include "trikKit/robotModel/parts/trikGamepadPad.h"
#include "trikKit/robotModel/parts/trikGamepadPadPressSensor.h"
#include "trikKit/robotModel/parts/trikGamepadWheel.h"

using namespace trik::robotModel;
using namespace kitBase::robotModel;

TrikRobotModelBase::TrikRobotModelBase(const QString &kitId, const QString &robotId)
	: CommonRobotModel(kitId, robotId)
{
	QList<DeviceInfo> const analogPortConnections = {
		lightSensorInfo()
		, infraredSensorInfo()
	};

	addAllowedConnection(PortInfo("DisplayPort", output), { displayInfo() });
	addAllowedConnection(PortInfo("SpeakerPort", output), { speakerInfo() });

	addAllowedConnection(PortInfo("Left", input, {}, "buttonLeft"), { buttonInfo() });
	addAllowedConnection(PortInfo("Right", input, {}, "buttonRight"), { buttonInfo() });
	addAllowedConnection(PortInfo("Up", input, {}, "buttonUp"), { buttonInfo() });
	addAllowedConnection(PortInfo("Down", input, {}, "buttonDown"), { buttonInfo() });
	addAllowedConnection(PortInfo("Enter", input, {}, "buttonEnter"), { buttonInfo() });
	addAllowedConnection(PortInfo("Esc", input, {}, "buttonEsc"), { buttonInfo() });

	addAllowedConnection(PortInfo("C1", output, { "JC1" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("C2", output, { "JC2" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("C3", output, { "JC3" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E1", output, { "JE1" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E2", output, { "JE2" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E3", output, { "JE3" }), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E4", output, { "JE4" }), { servoMotorInfo() });

	addAllowedConnection(PortInfo("M1", output, { "JM1", "A", "1" }), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M2", output, { "JM2", "B", "2" }), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M3", output, { "JM3", "C", "3" }), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M4", output, { "JM4", "D", "4" }), { powerMotorInfo() });

	addAllowedConnection(PortInfo("B1", input, { "JB1", "M1", "JM1", "A", "1" }, "encoder1"), { encoderInfo() });
	addAllowedConnection(PortInfo("B2", input, { "JB2", "M2", "JM2", "B", "2" }, "encoder2"), { encoderInfo() });
	addAllowedConnection(PortInfo("B3", input, { "JB3", "M3", "JM3", "C", "3" }, "encoder3"), { encoderInfo() });
	addAllowedConnection(PortInfo("B4", input, { "JB4", "M4", "JM4", "D", "4" }, "encoder4"), { encoderInfo() });

	addAllowedConnection(PortInfo("A1", input, { "JA1" }, "sensorA1"), analogPortConnections);
	addAllowedConnection(PortInfo("A2", input, { "JA2" }, "sensorA2"), analogPortConnections);
	addAllowedConnection(PortInfo("A3", input, { "JA3" }, "sensorA3"), analogPortConnections);
	addAllowedConnection(PortInfo("A4", input, { "JA4" }, "sensorA4"), analogPortConnections);
	addAllowedConnection(PortInfo("A5", input, { "JA5" }, "sensorA5"), analogPortConnections);
	addAllowedConnection(PortInfo("A6", input, { "JA6" }, "sensorA6"), analogPortConnections);

	addAllowedConnection(PortInfo("D1", input, { "JD1" }, "sensorD1"), { sonarSensorInfo() });
	addAllowedConnection(PortInfo("D2", input, { "JD2" }, "sensorD2"), { sonarSensorInfo() });

	addAllowedConnection(PortInfo("F1", input, { "JF1" }, "sensorF1"), { motionSensorInfo() });

	addAllowedConnection(PortInfo("GyroscopePortX", input, {}, "gyroscopeX"), { gyroscopeInfo() });
	addAllowedConnection(PortInfo("GyroscopePortY", input, {}, "gyroscopeY"), { gyroscopeInfo() });
	addAllowedConnection(PortInfo("GyroscopePortZ", input, {}, "gyroscopeZ"), { gyroscopeInfo() });

	addAllowedConnection(PortInfo("AccelerometerPortX", input, {}, "accelerometerX"), { accelerometerInfo() });
	addAllowedConnection(PortInfo("AccelerometerPortY", input, {}, "accelerometerY"), { accelerometerInfo() });
	addAllowedConnection(PortInfo("AccelerometerPortZ", input, {}, "accelerometerZ"), { accelerometerInfo() });

	addAllowedConnection(PortInfo("LedPort", output), { ledInfo() });

	addAllowedConnection(PortInfo("LineSensorXPort", input, {}, "lineSensorX"), { lineSensorInfo() });
	addAllowedConnection(PortInfo("LineSensorSizePort", input, {}, "lineSensorSize"), { lineSensorInfo() });
	addAllowedConnection(PortInfo("LineSensorCrossroadsPort", input, {}, "lineSensorCross"), { lineSensorInfo() });

	addAllowedConnection(PortInfo("ObjectSensorXPort", input, {}, "objectSensorX"), { objectSensorInfo() });
	addAllowedConnection(PortInfo("ObjectSensorYPort", input, {}, "objectSensorY"), { objectSensorInfo() });
	addAllowedConnection(PortInfo("ObjectSensorSizePort", input, {}, "objectSensorSize"), { objectSensorInfo() });

	addAllowedConnection(PortInfo("ColorSensorRPort", input, {}, "colorSensorR"), { colorSensorInfo() });
	addAllowedConnection(PortInfo("ColorSensorGPort", input, {}, "colorSensorG"), { colorSensorInfo() });
	addAllowedConnection(PortInfo("ColorSensorBPort", input, {}, "colorSensorB"), { colorSensorInfo() });

	addAllowedConnection(PortInfo("ShellPort", output), { shellInfo() });

	addAllowedConnection(PortInfo("GamepadPad1PosPort", input, {}, "gamepadPad1"
			, PortInfo::ReservedVariableType::vector), { gamepadPadInfo() });
	addAllowedConnection(PortInfo("GamepadPad2PosPort", input, {}, "gamepadPad2"
			, PortInfo::ReservedVariableType::vector), { gamepadPadInfo() });

	addAllowedConnection(PortInfo("GamepadPad1PressedPort", input, {}, "gamepadPad1Pressed")
			, { gamepadPadPressSensorInfo() });
	addAllowedConnection(PortInfo("GamepadPad2PressedPort", input, {}, "gamepadPad2Pressed")
			, { gamepadPadPressSensorInfo() });

	addAllowedConnection(PortInfo("GamepadWheelPort", input, {}, "gamepadWheel"), { gamepadWheelInfo() });

	addAllowedConnection(PortInfo("GamepadButton1Port", input, {}, "gamepadButton1"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton2Port", input, {}, "gamepadButton2"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton3Port", input, {}, "gamepadButton3"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton4Port", input, {}, "gamepadButton4"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton5Port", input, {}, "gamepadButton5"), { gamepadButtonInfo() });

	addAllowedConnection(PortInfo("GamepadConnectionIndicatorPort", input, {}, "gamepadConnected")
			, { gamepadConnectionIndicatorInfo() });
}

QList<PortInfo> TrikRobotModelBase::configurablePorts() const
{
	QList<PortInfo> const digitalPorts = {
			  PortInfo("D1", input, { "JD1" }, "sensorD1")
			, PortInfo("D2", input, { "JD2" }, "sensorD2")
			, PortInfo("F1", input, { "JF1" }, "sensorF1") };
	return CommonRobotModel::configurablePorts() + digitalPorts;
}

QList<DeviceInfo> TrikRobotModelBase::convertibleBases() const
{
	return { DeviceInfo::create<robotParts::LightSensor>()
		, DeviceInfo::create<parts::TrikInfraredSensor>()
		, DeviceInfo::create<parts::TrikSonarSensor>()
		, DeviceInfo::create<parts::TrikMotionSensor>()
	};
}

DeviceInfo TrikRobotModelBase::displayInfo() const
{
	return DeviceInfo::create<robotParts::Display>();
}

DeviceInfo TrikRobotModelBase::speakerInfo() const
{
	return DeviceInfo::create<robotParts::Speaker>();
}

DeviceInfo TrikRobotModelBase::buttonInfo() const
{
	return DeviceInfo::create<robotParts::Button>();
}

DeviceInfo TrikRobotModelBase::powerMotorInfo() const
{
	return DeviceInfo::create<robotParts::Motor>();
}

DeviceInfo TrikRobotModelBase::servoMotorInfo() const
{
	return DeviceInfo::create<robotParts::Motor>();
}

DeviceInfo TrikRobotModelBase::encoderInfo() const
{
	return DeviceInfo::create<robotParts::EncoderSensor>();
}

DeviceInfo TrikRobotModelBase::lightSensorInfo() const
{
	return DeviceInfo::create<robotParts::LightSensor>();
}

DeviceInfo TrikRobotModelBase::infraredSensorInfo() const
{
	return DeviceInfo::create<parts::TrikInfraredSensor>();
}

DeviceInfo TrikRobotModelBase::sonarSensorInfo() const
{
	return DeviceInfo::create<parts::TrikSonarSensor>();
}

DeviceInfo TrikRobotModelBase::motionSensorInfo() const
{
	return DeviceInfo::create<parts::TrikMotionSensor>();
}

DeviceInfo TrikRobotModelBase::gyroscopeInfo() const
{
	return DeviceInfo::create<robotParts::GyroscopeSensor>();
}

DeviceInfo TrikRobotModelBase::accelerometerInfo() const
{
	return DeviceInfo::create<robotParts::AccelerometerSensor>();
}

DeviceInfo TrikRobotModelBase::ledInfo() const
{
	return DeviceInfo::create<parts::TrikLed>();
}

DeviceInfo TrikRobotModelBase::lineSensorInfo() const
{
	return DeviceInfo::create<parts::TrikLineSensor>();
}

DeviceInfo TrikRobotModelBase::colorSensorInfo() const
{
	return DeviceInfo::create<parts::TrikColorSensor>();
}

DeviceInfo TrikRobotModelBase::objectSensorInfo() const
{
	return DeviceInfo::create<parts::TrikObjectSensor>();
}

DeviceInfo TrikRobotModelBase::shellInfo() const
{
	return DeviceInfo::create<parts::TrikShell>();
}

DeviceInfo TrikRobotModelBase::gamepadButtonInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadButton>();
}

DeviceInfo TrikRobotModelBase::gamepadPadInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadPad>();
}

DeviceInfo TrikRobotModelBase::gamepadPadPressSensorInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadPadPressSensor>();
}

DeviceInfo TrikRobotModelBase::gamepadWheelInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadWheel>();
}

DeviceInfo TrikRobotModelBase::gamepadConnectionIndicatorInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadConnectionIndicator>();
}
<commit_msg>removed aliases from TRIK model<commit_after>#include "trikKit/robotModel/trikRobotModelBase.h"

#include <kitBase/robotModel/robotParts/display.h>
#include <kitBase/robotModel/robotParts/speaker.h>
#include <kitBase/robotModel/robotParts/button.h>
#include <kitBase/robotModel/robotParts/gyroscopeSensor.h>
#include <kitBase/robotModel/robotParts/accelerometerSensor.h>

#include <kitBase/robotModel/robotParts/encoderSensor.h>

#include <kitBase/robotModel/robotParts/lightSensor.h>

#include "trikKit/robotModel/parts/trikServoMotor.h"
#include "trikKit/robotModel/parts/trikPowerMotor.h"
#include "trikKit/robotModel/parts/trikInfraredSensor.h"
#include "trikKit/robotModel/parts/trikSonarSensor.h"
#include "trikKit/robotModel/parts/trikMotionSensor.h"
#include "trikKit/robotModel/parts/trikColorSensor.h"
#include "trikKit/robotModel/parts/trikLineSensor.h"
#include "trikKit/robotModel/parts/trikObjectSensor.h"
#include "trikKit/robotModel/parts/trikLed.h"
#include "trikKit/robotModel/parts/trikShell.h"
#include "trikKit/robotModel/parts/trikGamepadButton.h"
#include "trikKit/robotModel/parts/trikGamepadConnectionIndicator.h"
#include "trikKit/robotModel/parts/trikGamepadPad.h"
#include "trikKit/robotModel/parts/trikGamepadPadPressSensor.h"
#include "trikKit/robotModel/parts/trikGamepadWheel.h"

using namespace trik::robotModel;
using namespace kitBase::robotModel;

TrikRobotModelBase::TrikRobotModelBase(const QString &kitId, const QString &robotId)
	: CommonRobotModel(kitId, robotId)
{
	QList<DeviceInfo> const analogPortConnections = {
		lightSensorInfo()
		, infraredSensorInfo()
	};

	addAllowedConnection(PortInfo("DisplayPort", output), { displayInfo() });
	addAllowedConnection(PortInfo("SpeakerPort", output), { speakerInfo() });

	addAllowedConnection(PortInfo("Left", input, {}, "buttonLeft"), { buttonInfo() });
	addAllowedConnection(PortInfo("Right", input, {}, "buttonRight"), { buttonInfo() });
	addAllowedConnection(PortInfo("Up", input, {}, "buttonUp"), { buttonInfo() });
	addAllowedConnection(PortInfo("Down", input, {}, "buttonDown"), { buttonInfo() });
	addAllowedConnection(PortInfo("Enter", input, {}, "buttonEnter"), { buttonInfo() });
	addAllowedConnection(PortInfo("Esc", input, {}, "buttonEsc"), { buttonInfo() });

	addAllowedConnection(PortInfo("C1", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("C2", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("C3", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E1", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E2", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E3", output, {}), { servoMotorInfo() });
	addAllowedConnection(PortInfo("E4", output, {}), { servoMotorInfo() });

	addAllowedConnection(PortInfo("M1", output, {}), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M2", output, {}), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M3", output, {}), { powerMotorInfo() });
	addAllowedConnection(PortInfo("M4", output, {}), { powerMotorInfo() });

	addAllowedConnection(PortInfo("B1", input, {"M1"}, "encoder1"), { encoderInfo() });
	addAllowedConnection(PortInfo("B2", input, {"M2"}, "encoder2"), { encoderInfo() });
	addAllowedConnection(PortInfo("B3", input, {"M3"}, "encoder3"), { encoderInfo() });
	addAllowedConnection(PortInfo("B4", input, {"M4"}, "encoder4"), { encoderInfo() });

	addAllowedConnection(PortInfo("A1", input, {}, "sensorA1"), analogPortConnections);
	addAllowedConnection(PortInfo("A2", input, {}, "sensorA2"), analogPortConnections);
	addAllowedConnection(PortInfo("A3", input, {}, "sensorA3"), analogPortConnections);
	addAllowedConnection(PortInfo("A4", input, {}, "sensorA4"), analogPortConnections);
	addAllowedConnection(PortInfo("A5", input, {}, "sensorA5"), analogPortConnections);
	addAllowedConnection(PortInfo("A6", input, {}, "sensorA6"), analogPortConnections);

	addAllowedConnection(PortInfo("D1", input, {}, "sensorD1"), { sonarSensorInfo() });
	addAllowedConnection(PortInfo("D2", input, {}, "sensorD2"), { sonarSensorInfo() });

	addAllowedConnection(PortInfo("F1", input, {}, "sensorF1"), { motionSensorInfo() });

	addAllowedConnection(PortInfo("GyroscopePortX", input, {}, "gyroscopeX"), { gyroscopeInfo() });
	addAllowedConnection(PortInfo("GyroscopePortY", input, {}, "gyroscopeY"), { gyroscopeInfo() });
	addAllowedConnection(PortInfo("GyroscopePortZ", input, {}, "gyroscopeZ"), { gyroscopeInfo() });

	addAllowedConnection(PortInfo("AccelerometerPortX", input, {}, "accelerometerX"), { accelerometerInfo() });
	addAllowedConnection(PortInfo("AccelerometerPortY", input, {}, "accelerometerY"), { accelerometerInfo() });
	addAllowedConnection(PortInfo("AccelerometerPortZ", input, {}, "accelerometerZ"), { accelerometerInfo() });

	addAllowedConnection(PortInfo("LedPort", output), { ledInfo() });

	addAllowedConnection(PortInfo("LineSensorXPort", input, {}, "lineSensorX"), { lineSensorInfo() });
	addAllowedConnection(PortInfo("LineSensorSizePort", input, {}, "lineSensorSize"), { lineSensorInfo() });
	addAllowedConnection(PortInfo("LineSensorCrossroadsPort", input, {}, "lineSensorCross"), { lineSensorInfo() });

	addAllowedConnection(PortInfo("ObjectSensorXPort", input, {}, "objectSensorX"), { objectSensorInfo() });
	addAllowedConnection(PortInfo("ObjectSensorYPort", input, {}, "objectSensorY"), { objectSensorInfo() });
	addAllowedConnection(PortInfo("ObjectSensorSizePort", input, {}, "objectSensorSize"), { objectSensorInfo() });

	addAllowedConnection(PortInfo("ColorSensorRPort", input, {}, "colorSensorR"), { colorSensorInfo() });
	addAllowedConnection(PortInfo("ColorSensorGPort", input, {}, "colorSensorG"), { colorSensorInfo() });
	addAllowedConnection(PortInfo("ColorSensorBPort", input, {}, "colorSensorB"), { colorSensorInfo() });

	addAllowedConnection(PortInfo("ShellPort", output), { shellInfo() });

	addAllowedConnection(PortInfo("GamepadPad1PosPort", input, {}, "gamepadPad1"
			, PortInfo::ReservedVariableType::vector), { gamepadPadInfo() });
	addAllowedConnection(PortInfo("GamepadPad2PosPort", input, {}, "gamepadPad2"
			, PortInfo::ReservedVariableType::vector), { gamepadPadInfo() });

	addAllowedConnection(PortInfo("GamepadPad1PressedPort", input, {}, "gamepadPad1Pressed")
			, { gamepadPadPressSensorInfo() });
	addAllowedConnection(PortInfo("GamepadPad2PressedPort", input, {}, "gamepadPad2Pressed")
			, { gamepadPadPressSensorInfo() });

	addAllowedConnection(PortInfo("GamepadWheelPort", input, {}, "gamepadWheel"), { gamepadWheelInfo() });

	addAllowedConnection(PortInfo("GamepadButton1Port", input, {}, "gamepadButton1"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton2Port", input, {}, "gamepadButton2"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton3Port", input, {}, "gamepadButton3"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton4Port", input, {}, "gamepadButton4"), { gamepadButtonInfo() });
	addAllowedConnection(PortInfo("GamepadButton5Port", input, {}, "gamepadButton5"), { gamepadButtonInfo() });

	addAllowedConnection(PortInfo("GamepadConnectionIndicatorPort", input, {}, "gamepadConnected")
			, { gamepadConnectionIndicatorInfo() });
}

QList<PortInfo> TrikRobotModelBase::configurablePorts() const
{
	QList<PortInfo> const digitalPorts = {
			  PortInfo("D1", input, {}, "sensorD1")
			, PortInfo("D2", input, {}, "sensorD2")
			, PortInfo("F1", input, {}, "sensorF1") };

	return CommonRobotModel::configurablePorts() + digitalPorts;
}

QList<DeviceInfo> TrikRobotModelBase::convertibleBases() const
{
	return { DeviceInfo::create<robotParts::LightSensor>()
		, DeviceInfo::create<parts::TrikInfraredSensor>()
		, DeviceInfo::create<parts::TrikSonarSensor>()
		, DeviceInfo::create<parts::TrikMotionSensor>()
	};
}

DeviceInfo TrikRobotModelBase::displayInfo() const
{
	return DeviceInfo::create<robotParts::Display>();
}

DeviceInfo TrikRobotModelBase::speakerInfo() const
{
	return DeviceInfo::create<robotParts::Speaker>();
}

DeviceInfo TrikRobotModelBase::buttonInfo() const
{
	return DeviceInfo::create<robotParts::Button>();
}

DeviceInfo TrikRobotModelBase::powerMotorInfo() const
{
	return DeviceInfo::create<robotParts::Motor>();
}

DeviceInfo TrikRobotModelBase::servoMotorInfo() const
{
	return DeviceInfo::create<robotParts::Motor>();
}

DeviceInfo TrikRobotModelBase::encoderInfo() const
{
	return DeviceInfo::create<robotParts::EncoderSensor>();
}

DeviceInfo TrikRobotModelBase::lightSensorInfo() const
{
	return DeviceInfo::create<robotParts::LightSensor>();
}

DeviceInfo TrikRobotModelBase::infraredSensorInfo() const
{
	return DeviceInfo::create<parts::TrikInfraredSensor>();
}

DeviceInfo TrikRobotModelBase::sonarSensorInfo() const
{
	return DeviceInfo::create<parts::TrikSonarSensor>();
}

DeviceInfo TrikRobotModelBase::motionSensorInfo() const
{
	return DeviceInfo::create<parts::TrikMotionSensor>();
}

DeviceInfo TrikRobotModelBase::gyroscopeInfo() const
{
	return DeviceInfo::create<robotParts::GyroscopeSensor>();
}

DeviceInfo TrikRobotModelBase::accelerometerInfo() const
{
	return DeviceInfo::create<robotParts::AccelerometerSensor>();
}

DeviceInfo TrikRobotModelBase::ledInfo() const
{
	return DeviceInfo::create<parts::TrikLed>();
}

DeviceInfo TrikRobotModelBase::lineSensorInfo() const
{
	return DeviceInfo::create<parts::TrikLineSensor>();
}

DeviceInfo TrikRobotModelBase::colorSensorInfo() const
{
	return DeviceInfo::create<parts::TrikColorSensor>();
}

DeviceInfo TrikRobotModelBase::objectSensorInfo() const
{
	return DeviceInfo::create<parts::TrikObjectSensor>();
}

DeviceInfo TrikRobotModelBase::shellInfo() const
{
	return DeviceInfo::create<parts::TrikShell>();
}

DeviceInfo TrikRobotModelBase::gamepadButtonInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadButton>();
}

DeviceInfo TrikRobotModelBase::gamepadPadInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadPad>();
}

DeviceInfo TrikRobotModelBase::gamepadPadPressSensorInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadPadPressSensor>();
}

DeviceInfo TrikRobotModelBase::gamepadWheelInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadWheel>();
}

DeviceInfo TrikRobotModelBase::gamepadConnectionIndicatorInfo() const
{
	return DeviceInfo::create<parts::TrikGamepadConnectionIndicator>();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AxTestComponents.cpp,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jl $ $Date: 2000-10-12 13:17:46 $
 *
 *  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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES 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): _______________________________________
 *
 *
 ************************************************************************/

// Note: Proxy/Stub Information
//      To build a separate proxy/stub DLL,
//      run nmake -f AxTestComponentsps.mk in the project directory.

#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "AxTestComponents.h"

#include "AxTestComponents_i.c"
#include "Basic.h"

CComModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_Basic, CBasic)
END_OBJECT_MAP()

/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point

extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
    if (dwReason == DLL_PROCESS_ATTACH)
    {
        _Module.Init(ObjectMap, hInstance, &LIBID_AXTESTCOMPONENTSLib);
        DisableThreadLibraryCalls(hInstance);
    }
    else if (dwReason == DLL_PROCESS_DETACH)
        _Module.Term();
    return TRUE;    // ok
}

/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE

STDAPI DllCanUnloadNow(void)
{
    return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
    return _Module.GetClassObject(rclsid, riid, ppv);
}

/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry

STDAPI DllRegisterServer(void)
{
    // registers object, typelib and all interfaces in typelib
    return _Module.RegisterServer(TRUE);
}

/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry

STDAPI DllUnregisterServer(void)
{
    return _Module.UnregisterServer(TRUE);
}

//VT_I4 size_t V_ERROR VARIANT VARIANT_FALSE CComVariant FADF_EMBEDDED    <commit_msg>INTEGRATION: CWS jl5vba (1.2.256); FILE MERGED 2004/01/16 12:51:20 jl 1.2.256.1: #109536# #112889# merge from cws ab02vba<commit_after>/*************************************************************************
 *
 *  $RCSfile: AxTestComponents.cpp,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-17 13:10:16 $
 *
 *  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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES 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): _______________________________________
 *
 *
 ************************************************************************/

// Note: Proxy/Stub Information
//      To build a separate proxy/stub DLL,
//      run nmake -f AxTestComponentsps.mk in the project directory.

#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
//#include "AxTestComponents.h"

//#include "AxTestComponents_i.c"
#include "Basic.h"
#include "Foo.h"

CComModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_Basic, CBasic)
OBJECT_ENTRY(CLSID_Foo, CFoo)
END_OBJECT_MAP()

/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point

extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
    if (dwReason == DLL_PROCESS_ATTACH)
    {
        _Module.Init(ObjectMap, hInstance, &LIBID_AXTESTCOMPONENTSLib);
        DisableThreadLibraryCalls(hInstance);
    }
    else if (dwReason == DLL_PROCESS_DETACH)
        _Module.Term();
    return TRUE;    // ok
}

/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE

STDAPI DllCanUnloadNow(void)
{
    return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
    return _Module.GetClassObject(rclsid, riid, ppv);
}

/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry

STDAPI DllRegisterServer(void)
{
    // registers object, typelib and all interfaces in typelib
    return _Module.RegisterServer(TRUE);
}

/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry

STDAPI DllUnregisterServer(void)
{
    return _Module.UnregisterServer(TRUE);
}

//VT_I4 size_t V_ERROR VARIANT VARIANT_FALSE CComVariant FADF_EMBEDDED    <|endoftext|>


<commit_before>#include "matrix.h"

template <typename T>
inline void cgemm(const int M, const int N, const int K,
                  const mipp::vector<T> &A,
                  const mipp::vector<T> &tB,
                        mipp::vector<T> &tC)
{
	assert( A.size() == (M * K * 2));
	assert(tB.size() == (K * N * 2));
	assert(tC.size() == (M * N * 2));

	const T*  A_real =  A.data();
	const T*  A_imag =  A.data() + ( A.size() >> 1);
	const T* tB_real = tB.data();
	const T* tB_imag = tB.data() + (tB.size() >> 1);
	      T* tC_real = tC.data();
	      T* tC_imag = tC.data() + (tC.size() >> 1);

	for (auto i = 0; i < M; i++)
	{
		for (auto j = 0; j < N; j++)
		{
			T sum_r = 0, sum_i = 0;
			for (auto k = 0; k < K; k++)
			{
				sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k];
				sum_i += A_imag[i * K + k] * tB_real[j * K + k] + A_real[i * K + k] * tB_imag[j * K + k];
			}

			tC_real[j * M + i] = sum_r;
			tC_imag[j * M + i] = sum_i;
		}
	}
}

template <typename T>
inline void cgemm_r(const int M, const int N, const int K,
                    const mipp::vector<T> &A,
                    const mipp::vector<T> &tB,
                          mipp::vector<T> &tC)
{
	assert( A.size() == unsigned (M * K * 2));
	assert(tB.size() == unsigned (K * N * 2));
	assert(tC.size() == unsigned (M * N * 1)); // because we only store the real part

	const T*  A_real =  A.data();
	const T*  A_imag =  A.data() + ( A.size() >> 1);
	const T* tB_real = tB.data();
	const T* tB_imag = tB.data() + (tB.size() >> 1);
	      T* tC_real = tC.data();

	for (auto i = 0; i < M; i++)
	{
		for (auto j = 0; j < N; j++)
		{
			T sum_r = 0;
			for (auto k = 0; k < K; k++)
				sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k];

			tC_real[j * M + i] = sum_r;
		}
	}
}<commit_msg>Fix a compiler warning.<commit_after>#include "matrix.h"

template <typename T>
inline void cgemm(const int M, const int N, const int K,
                  const mipp::vector<T> &A,
                  const mipp::vector<T> &tB,
                        mipp::vector<T> &tC)
{
	assert( A.size() == unsigned(M * K * 2));
	assert(tB.size() == unsigned(K * N * 2));
	assert(tC.size() == unsigned(M * N * 2));

	const T*  A_real =  A.data();
	const T*  A_imag =  A.data() + ( A.size() >> 1);
	const T* tB_real = tB.data();
	const T* tB_imag = tB.data() + (tB.size() >> 1);
	      T* tC_real = tC.data();
	      T* tC_imag = tC.data() + (tC.size() >> 1);

	for (auto i = 0; i < M; i++)
	{
		for (auto j = 0; j < N; j++)
		{
			T sum_r = 0, sum_i = 0;
			for (auto k = 0; k < K; k++)
			{
				sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k];
				sum_i += A_imag[i * K + k] * tB_real[j * K + k] + A_real[i * K + k] * tB_imag[j * K + k];
			}

			tC_real[j * M + i] = sum_r;
			tC_imag[j * M + i] = sum_i;
		}
	}
}

template <typename T>
inline void cgemm_r(const int M, const int N, const int K,
                    const mipp::vector<T> &A,
                    const mipp::vector<T> &tB,
                          mipp::vector<T> &tC)
{
	assert( A.size() == unsigned(M * K * 2));
	assert(tB.size() == unsigned(K * N * 2));
	assert(tC.size() == unsigned(M * N * 1)); // because we only store the real part

	const T*  A_real =  A.data();
	const T*  A_imag =  A.data() + ( A.size() >> 1);
	const T* tB_real = tB.data();
	const T* tB_imag = tB.data() + (tB.size() >> 1);
	      T* tC_real = tC.data();

	for (auto i = 0; i < M; i++)
	{
		for (auto j = 0; j < N; j++)
		{
			T sum_r = 0;
			for (auto k = 0; k < K; k++)
				sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k];

			tC_real[j * M + i] = sum_r;
		}
	}
}<|endoftext|>