<commit_before>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"

using namespace te;

namespace te
{
    class LuaGameState
    {
    public:
        LuaGameState(const std::string& filename = "init.lua")
            : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
            , mHandleCount(0)
            , mEntities()
            , mPositionMap()
            , mVelocityMap()
            , mBoundingBoxMap()
            , mDimensionMap()
        {
            lua_State* pL = mpL.get();
            luaL_openlibs(pL);

            luabridge::getGlobalNamespace(pL)
                .beginClass<LuaGameState>("GameState")
                .addFunction("createEntity", &LuaGameState::createEntity)
                .addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
                .addFunction("setSprite", &LuaGameState::setSprite)
                .addFunction("destroyEntity", &LuaGameState::destroyEntity)
                .endClass();
            luabridge::push(pL, this);
            lua_setglobal(pL, "game");

            luaL_dofile(pL, filename.c_str());
            luabridge::getGlobal(pL, "main")();
        }

        typedef unsigned int EntityHandle;

        EntityHandle createEntity(float x, float y, float dx, float dy)
        {
            EntityHandle handle = mHandleCount++;
            mEntities.push_back(handle);
            mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));
            mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));
            mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
            return handle;
        }

        void setBoundingBox(EntityHandle handle, int width, int height)
        {
            if (!exists(handle)) return;

            auto it = mBoundingBoxMap.find(handle);
            it->second = Vector2i(width, height);
        }

        void setSprite(EntityHandle handle, int width, int height)
        {
            if (!exists(handle)) return;

            insertOrAssign(mDimensionMap, std::make_pair(
                handle, Vector2i(width, height)));
        }

        bool exists(EntityHandle handle)
        {
            auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
            return it != std::end(mEntities);
        }

        void destroyEntity(EntityHandle handle)
        {
            mEntities.erase(
                std::remove(mEntities.begin(), mEntities.end(), handle),
                mEntities.end());
            auto positionIt = mPositionMap.find(handle);
            if (positionIt != mPositionMap.end())
            {
                mPositionMap.erase(positionIt);
            }
            auto velocityIt = mVelocityMap.find(handle);
            if (velocityIt != mVelocityMap.end())
            {
                mVelocityMap.erase(velocityIt);
            }
            auto boundingBoxIt = mBoundingBoxMap.find(handle);
            if (boundingBoxIt != mBoundingBoxMap.end())
            {
                mBoundingBoxMap.erase(boundingBoxIt);
            }
            auto dimensionIt = mDimensionMap.find(handle);
            if (dimensionIt != mDimensionMap.end())
            {
                mDimensionMap.erase(dimensionIt);
            }
        }

        void update(float dt)
        {
            forEachEntity([&](const EntityHandle& handle)
            {
                Vector2f& velocity = mVelocityMap.find(handle)->second;
                Vector2f& position = mPositionMap.find(handle)->second;
                position.x += velocity.x * dt;
                position.y += velocity.y * dt;
            });
        }

        void draw(RendererPtr pRenderer)
        {
            forEachEntity([&](const EntityHandle& handle)
            {
                auto positionIt = mPositionMap.find(handle);
                auto spriteIt = mDimensionMap.find(handle);
                if (spriteIt != mDimensionMap.end())
                {
                    SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
                    SDL_Rect rect = {
                        (int)positionIt->second.x,
                        (int)positionIt->second.y,
                        spriteIt->second.x,
                        spriteIt->second.y
                    };
                    SDL_RenderFillRect(pRenderer.get(), &rect);
                }
            });
        }

        void forEachEntity(const std::function<void(const EntityHandle&)>& func)
        {
            std::for_each(mEntities.begin(), mEntities.end(), func);
        }

    private:
        std::shared_ptr<lua_State> mpL;
        EntityHandle mHandleCount;
        std::vector<EntityHandle> mEntities;
        std::map<EntityHandle, Vector2f> mPositionMap;
        std::map<EntityHandle, Vector2f> mVelocityMap;
        std::map<EntityHandle, Vector2i> mBoundingBoxMap;
        std::map<EntityHandle, Vector2i> mDimensionMap;
    };
}

int main(int argc, char** argv)
{
    LuaGameState state;

    const int WIDTH = 640;
    const int HEIGHT = 480;

    te::Initialization init;
    te::WindowPtr pWindow = te::wrapWindow(
        SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
    );
    te::RendererPtr pRenderer = te::createRenderer(pWindow);
    SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);

    SDL_Rect ballRect = { 0, 0, 25, 25 };
    float x = 0;
    float ballSpeed = 50;

    Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
    std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
    std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
    Rectangle topWall(0.f, 0.f, 640, 10);
    Rectangle bottomWall(0.f, 470.f, 640, 10);

    KeyMap keys = createPaddleKeyMap();

    Player player1(pPaddle1, 1);
    Player player2(pPaddle2, 2);

    SDL_Event e;
    bool running = true;

    Uint32 FPS = 60;
    Uint32 TIME_PER_FRAME = 1000 / FPS;

    Uint64 t0 = SDL_GetPerformanceCounter();

    while (running)
    {
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT)
            {
                running = false;
            }
            player1.issueCommand(e.key.keysym.sym, e.type)();
            player2.issueCommand(e.key.keysym.sym, e.type)();
        }

        Uint64 now = SDL_GetPerformanceCounter();
        float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

        dot.update(dt);
        pPaddle1->update(dt);
        pPaddle2->update(dt);
        topWall.update(dt);
        bottomWall.update(dt);

        handlePaddleCollision(dot, *pPaddle1.get(), dt);
        handlePaddleCollision(dot, *pPaddle2.get(), dt);
        handleWallCollision(dot, topWall, dt);
        handleWallCollision(dot, bottomWall, dt);

        SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
        SDL_RenderClear(pRenderer.get());

        dot.draw(pRenderer);
        pPaddle1->draw(pRenderer);
        pPaddle2->draw(pRenderer);
        topWall.draw(pRenderer);
        bottomWall.draw(pRenderer);

        SDL_RenderPresent(pRenderer.get());
        t0 = now;
    }

    return 0;
}
<commit_msg>Add LuaGameState collision handling<commit_after>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"

using namespace te;

namespace te
{
    class LuaGameState
    {
    public:
        LuaGameState(const std::string& filename = "init.lua")
            : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
            , mHandleCount(0)
            , mEntities()
            , mPositionMap()
            , mVelocityMap()
            , mBoundingBoxMap()
            , mDimensionMap()
            , mCollisionHandlerMap()
        {
            lua_State* pL = mpL.get();
            luaL_openlibs(pL);

            luabridge::getGlobalNamespace(pL)
                .beginClass<LuaGameState>("GameState")
                .addFunction("createEntity", &LuaGameState::createEntity)
                .addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
                .addFunction("setSprite", &LuaGameState::setSprite)
                .addFunction("handleCollision", &LuaGameState::handleCollision)
                .addFunction("destroyEntity", &LuaGameState::destroyEntity)
                .endClass();
            luabridge::push(pL, this);
            lua_setglobal(pL, "game");

            luaL_dofile(pL, filename.c_str());
            luabridge::getGlobal(pL, "main")();
        }

        typedef unsigned int EntityHandle;
        typedef std::pair<EntityHandle, EntityHandle> EntityPair;

        EntityHandle createEntity(float x, float y, float dx, float dy)
        {
            EntityHandle handle = mHandleCount++;
            mEntities.push_back(handle);
            mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));
            mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));
            mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
            return handle;
        }

        void setBoundingBox(EntityHandle handle, int width, int height)
        {
            if (!exists(handle)) return;

            auto it = mBoundingBoxMap.find(handle);
            it->second = Vector2i(width, height);
        }

        void setSprite(EntityHandle handle, int width, int height)
        {
            if (!exists(handle)) return;

            insertOrAssign(mDimensionMap, std::make_pair(
                handle, Vector2i(width, height)));
        }

        void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)
        {
            if (!exists(e1) || !exists(e2)) return;

            auto key = std::make_pair(e1, e2);
            auto it = mCollisionHandlerMap.find(key);
            if (it == mCollisionHandlerMap.end())
            {
                mCollisionHandlerMap.insert(std::make_pair(
                    key,
                    handler));
            }
            else
            {
                it->second = handler;
            }
        }

        bool exists(EntityHandle handle)
        {
            auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
            return it != std::end(mEntities);
        }

        void destroyEntity(EntityHandle handle)
        {
            mEntities.erase(
                std::remove(mEntities.begin(), mEntities.end(), handle),
                mEntities.end());
            auto positionIt = mPositionMap.find(handle);
            if (positionIt != mPositionMap.end())
            {
                mPositionMap.erase(positionIt);
            }
            auto velocityIt = mVelocityMap.find(handle);
            if (velocityIt != mVelocityMap.end())
            {
                mVelocityMap.erase(velocityIt);
            }
            auto boundingBoxIt = mBoundingBoxMap.find(handle);
            if (boundingBoxIt != mBoundingBoxMap.end())
            {
                mBoundingBoxMap.erase(boundingBoxIt);
            }
            auto dimensionIt = mDimensionMap.find(handle);
            if (dimensionIt != mDimensionMap.end())
            {
                mDimensionMap.erase(dimensionIt);
            }
        }

        void update(float dt)
        {
            forEachEntity([&](const EntityHandle& handle)
            {
                Vector2f& velocity = mVelocityMap.find(handle)->second;
                Vector2f& position = mPositionMap.find(handle)->second;
                position.x += velocity.x * dt;
                position.y += velocity.y * dt;
            });
            std::for_each(
                mCollisionHandlerMap.begin(),
                mCollisionHandlerMap.end(),
                [&](std::pair<const EntityPair, luabridge::LuaRef> kv)
            {
                EntityHandle e1 = kv.first.first;

                auto e1Position = mPositionMap.find(e1)->second;
                auto e1BoundingBox = mBoundingBoxMap.find(e1)->second;

                EntityHandle e2 = kv.first.second;

                auto e2Position = mPositionMap.find(e2)->second;
                auto e2BoundingBox = mBoundingBoxMap.find(e2)->second;

                if (checkCollision(
                    SDL_Rect{ (int)e1Position.x, (int)e1Position.y, e1BoundingBox.x, e1BoundingBox.y },
                    SDL_Rect{ (int)e2Position.x, (int)e2Position.y, e2BoundingBox.x, e2BoundingBox.y }))
                {
                    kv.second();
                }
            });
        }

        void draw(RendererPtr pRenderer)
        {
            forEachEntity([&](const EntityHandle& handle)
            {
                auto positionIt = mPositionMap.find(handle);
                auto spriteIt = mDimensionMap.find(handle);
                if (spriteIt != mDimensionMap.end())
                {
                    SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
                    SDL_Rect rect = {
                        (int)positionIt->second.x,
                        (int)positionIt->second.y,
                        spriteIt->second.x,
                        spriteIt->second.y
                    };
                    SDL_RenderFillRect(pRenderer.get(), &rect);
                }
            });
        }

        void forEachEntity(const std::function<void(const EntityHandle&)>& func)
        {
            std::for_each(mEntities.begin(), mEntities.end(), func);
        }

    private:
        std::shared_ptr<lua_State> mpL;
        EntityHandle mHandleCount;

        std::vector<EntityHandle> mEntities;

        std::map<EntityHandle, Vector2f> mPositionMap;
        std::map<EntityHandle, Vector2f> mVelocityMap;
        std::map<EntityHandle, Vector2i> mBoundingBoxMap;
        std::map<EntityHandle, Vector2i> mDimensionMap;

        std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;
    };
}

int main(int argc, char** argv)
{
    LuaGameState state;

    const int WIDTH = 640;
    const int HEIGHT = 480;

    te::Initialization init;
    te::WindowPtr pWindow = te::wrapWindow(
        SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
    );
    te::RendererPtr pRenderer = te::createRenderer(pWindow);
    SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);

    SDL_Rect ballRect = { 0, 0, 25, 25 };
    float x = 0;
    float ballSpeed = 50;

    Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
    std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
    std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
    Rectangle topWall(0.f, 0.f, 640, 10);
    Rectangle bottomWall(0.f, 470.f, 640, 10);

    KeyMap keys = createPaddleKeyMap();

    Player player1(pPaddle1, 1);
    Player player2(pPaddle2, 2);

    SDL_Event e;
    bool running = true;

    Uint32 FPS = 60;
    Uint32 TIME_PER_FRAME = 1000 / FPS;

    Uint64 t0 = SDL_GetPerformanceCounter();

    while (running)
    {
        while (SDL_PollEvent(&e) != 0)
        {
            if (e.type == SDL_QUIT)
            {
                running = false;
            }
            player1.issueCommand(e.key.keysym.sym, e.type)();
            player2.issueCommand(e.key.keysym.sym, e.type)();
        }

        Uint64 now = SDL_GetPerformanceCounter();
        float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();

        dot.update(dt);
        pPaddle1->update(dt);
        pPaddle2->update(dt);
        topWall.update(dt);
        bottomWall.update(dt);

        handlePaddleCollision(dot, *pPaddle1.get(), dt);
        handlePaddleCollision(dot, *pPaddle2.get(), dt);
        handleWallCollision(dot, topWall, dt);
        handleWallCollision(dot, bottomWall, dt);

        SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
        SDL_RenderClear(pRenderer.get());

        dot.draw(pRenderer);
        pPaddle1->draw(pRenderer);
        pPaddle2->draw(pRenderer);
        topWall.draw(pRenderer);
        bottomWall.draw(pRenderer);

        SDL_RenderPresent(pRenderer.get());
        t0 = now;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <gflags/gflags.h>
#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;

// Used in device query
DEFINE_int32(device_id, 0,
             "[devicequery,speedtest] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
              "[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
              "[speedtest] The net proto file to use.");
DEFINE_string(resume_point_file, "",
              "[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
              "[train] (optional) A pretrained network to run finetune from. "
              "Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
             "[speedtest] The number of iterations to run.");
DEFINE_bool(speedtest_with_gpu, false,
            "[speedtest] Test the model with GPU.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const caffe::string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe actions that could be called in the form
//     caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);

int devicequery() {
  LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
  caffe::Caffe::SetDevice(FLAGS_device_id);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(devicequery);

int train() {
  CHECK_GT(FLAGS_solver_proto_file.size(), 0);

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);

  LOG(INFO) << "Starting Optimization";
  caffe::SGDSolver<float> solver(solver_param);
  if (FLAGS_resume_point_file.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
    solver.Solve(FLAGS_resume_point_file);
  } else if (FLAGS_pretrained_net_file.size()) {
    LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
    solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
    solver.Solve();
  } else {
    solver.Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

int speedtest() {
  // Set device id and mode
  if (FLAGS_speedtest_with_gpu) {
    LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
    Caffe::SetDevice(FLAGS_device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Caffe::set_phase(Caffe::TRAIN);
  Net<float> caffe_net(FLAGS_net_proto_file);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  forward_timer.Start();
  Timer timer;
  for (int i = 0; i < layers.size(); ++i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
    }
    LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
        " milli seconds.";
  }
  LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
      " milli seconds.";
  Timer backward_timer;
  backward_timer.Start();
  for (int i = layers.size() - 1; i >= 0; --i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          &bottom_vecs[i]);
    }
    LOG(INFO) << layername << "\tbackward: "
        << timer.MilliSeconds() << " milli seconds.";
  }
  LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(speedtest);

int main(int argc, char** argv) {
  caffe::GlobalInit(&argc, &argv);
  CHECK_EQ(argc, 2);
  return GetBrewFunction(caffe::string(argv[1]))();
}
<commit_msg>rename tools<commit_after>#include <gflags/gflags.h>
#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;

// Used in device query
DEFINE_int32(device_id, 0,
             "[device_query,time] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
              "[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
              "[time] The net proto file to use.");
DEFINE_string(resume_point_file, "",
              "[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
              "[train] (optional) A pretrained network to run finetune from. "
              "Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
             "[time] The number of iterations to run.");
DEFINE_bool(time_with_gpu, false,
            "[time] Test the model with GPU.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const caffe::string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe actions that could be called in the form
//     caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);

int device_query() {
  LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
  caffe::Caffe::SetDevice(FLAGS_device_id);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(device_query);

int train() {
  CHECK_GT(FLAGS_solver_proto_file.size(), 0);

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);

  LOG(INFO) << "Starting Optimization";
  caffe::SGDSolver<float> solver(solver_param);
  if (FLAGS_resume_point_file.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
    solver.Solve(FLAGS_resume_point_file);
  } else if (FLAGS_pretrained_net_file.size()) {
    LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
    solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
    solver.Solve();
  } else {
    solver.Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

int time() {
  // Set device id and mode
  if (FLAGS_time_with_gpu) {
    LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
    Caffe::SetDevice(FLAGS_device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Caffe::set_phase(Caffe::TRAIN);
  Net<float> caffe_net(FLAGS_net_proto_file);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  forward_timer.Start();
  Timer timer;
  for (int i = 0; i < layers.size(); ++i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
    }
    LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
        " milli seconds.";
  }
  LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
      " milli seconds.";
  Timer backward_timer;
  backward_timer.Start();
  for (int i = layers.size() - 1; i >= 0; --i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < FLAGS_run_iterations; ++j) {
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          &bottom_vecs[i]);
    }
    LOG(INFO) << layername << "\tbackward: "
        << timer.MilliSeconds() << " milli seconds.";
  }
  LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(time);

int main(int argc, char** argv) {
  caffe::GlobalInit(&argc, &argv);
  CHECK_EQ(argc, 2);
  return GetBrewFunction(caffe::string(argv[1]))();
}
<|endoftext|>


<commit_before>
/***************************************************************************
 *  print_plan.cpp - print plan as PDDL to output
 *
 *  Created: Wed Mar 22 14:40:56 2017
 *  Copyright  2017  Tim Niemueller [www.niemueller.de]
 ****************************************************************************/

/*  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 * - Neither the name of the authors nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ros/ros.h>
#include <rosplan_dispatch_msgs/CompletePlan.h>

#include <cstdio>

void
plan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)
{
/*	for (const auto &a : msg->plan) {
		std::string s;
		for (const auto &p : a.parameters) {
			s += " " + p.value;
		}
		printf("%7.3f: (%s %s)  [%.3f]\n", a.dispatch_time, a.name.c_str(), s.c_str(), a.duration);
	}
	ros::shutdown();
*/}

int
main(int argc, char **argv)
{
	ros::init(argc, argv, "rcll_refbox_peer");

	ros::NodeHandle n;
	ros::Subscriber sub_plan = n.subscribe("kcl_rosplan/plan", 1, plan_cb);

	ros::spin();

	return 0;
}
<commit_msg>print pla change to remove auto<commit_after>
/***************************************************************************
 *  print_plan.cpp - print plan as PDDL to output
 *
 *  Created: Wed Mar 22 14:40:56 2017
 *  Copyright  2017  Tim Niemueller [www.niemueller.de]
 ****************************************************************************/

/*  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 * - Neither the name of the authors nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ros/ros.h>
#include <rosplan_dispatch_msgs/CompletePlan.h>
#include <rosplan_dispatch_msgs/ActionDispatch.h>

#include <cstdio>

void
plan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)
{
	for (int i=0; i<msg->plan.size(); i++) {
		std::string s;
		for (int j=0; j<msg->plan[i].parameters.size(); j++) {
			s += " " + msg->plan[i].parameters[j].value;
		}
		printf("%7.3f: (%s %s)  [%.3f]\n", msg->plan[i].dispatch_time, msg->plan[i].name.c_str(), s.c_str(), msg->plan[i].duration);
	}
	ros::shutdown();
}

int
main(int argc, char **argv)
{
	ros::init(argc, argv, "rcll_refbox_peer");

	ros::NodeHandle n;
	ros::Subscriber sub_plan = n.subscribe("kcl_rosplan/plan", 1, plan_cb);

	ros::spin();

	return 0;
}
<|endoftext|>


<commit_before>/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <prototypes.h>
#include <maxdispargs.h>
#include <pthread.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rt.h"
#include "../rtstuff/rtdefs.h"
#include "../sys/mixerr.h"
#include <stdio.h>
#include <string.h>

extern heap rtHeap;     // intraverse.C

//#define DEBUG

#ifdef PFIELD_CLASS

static void
_printargs(const char *instname, const Arg arglist[], const int nargs)
{
   int i;
   Arg arg;

   if (print_is_on) {
      printf("========<rt-queueing>=======\n");
      printf("%s:  ", instname);
      for (i = 0; i < nargs; i++) {
         arg = arglist[i];
         switch (arg.type) {
            case FloatType:
               printf("%g ", arg.val.number);
               break;
            case StringType:
               printf("\"%s\" ", arg.val.string);
               break;
            case HandleType:
               printf("Handle:%p ", arg.val.handle);
               break;
            case ArrayType:
               printf("[%g...%g] ", arg.val.array->data[0],
                              arg.val.array->data[arg.val.array->len - 1]);
               break;
            default:
               break;
         }
      }
      putchar('\n');
      fflush(stdout);
   }
}

double
checkInsts(const char *instname, const Arg arglist[], const int nargs,
   Arg *retval)
{
// FIXME: set this up as in addcheckfuncs, so that the guts of the
// instrument name list are not exposed here.  -JGG
   rt_item *rt_p;       // rt_item defined in rt.h
   rt_item *rt_temp;
   Instrument *Iptr;
   float p[MAXDISPARGS];
   double pp[MAXDISPARGS];

#ifdef DEBUG
   printf("ENTERING checkInsts() FUNCTION -----\n");
#endif

// FIXME: this is just temporary  -JGG
   for (int i = 0; i < nargs; i++) {
      switch (arglist[i].type) {
         case FloatType:
            p[i] = (float) arglist[i].val.number;
            pp[i] = (double) arglist[i].val.number;
            break;
         case StringType:
            break;
         case HandleType:
            break;
         default:
            break;
      }
   }

   mixerr = MX_FNAME;
   rt_temp = rt_list;
   rt_p = rt_list;

   while (rt_p) {

      if (strcmp(rt_p->rt_name, instname) == 0) {

         _printargs(instname, arglist, nargs);

         /* set up the Instrument */

         Iptr = (*(rt_p->rt_ptr))();

         Iptr->ref();   // We do this to assure one reference

         double rv = (double) Iptr->init(p, nargs, pp);

         if (rv != (double) DONT_SCHEDULE) { // only schedule if no init() error
            // For non-interactive case, configure() is delayed until just
            // before instrument run time.
            if (rtInteractive)
               Iptr->configure();

            /* schedule instrument */
            Iptr->schedule(&rtHeap);

            mixerr = MX_NOERR;
            rt_list = rt_temp;
         }
         else
            return rv;

#ifdef DEBUG
         printf("EXITING checkInsts() FUNCTION -----\n");
#endif

//FIXME: ??need to create Handle for Iptr on return
//       and return double rv?  can't be done in parse_dispatch now!

         return rv;
      }
      rt_p = rt_p->rt_next;
   }
   rt_list = rt_temp;

   return 0.0;
}

#else /* !PFIELD_CLASS */

double checkInsts(char *fname, double *pp, int n_args, void **inst)
{
   int i;
   rt_item *rt_p;
   rt_item *rt_temp;
   Instrument *Iptr;
   double rv;
   float p[MAXDISPARGS];

#ifdef DEBUG
   printf("ENTERING checkInsts() FUNCTION -----\n");
#endif

   /* convert pp to floats */
   for (i = 0; i < n_args; i++) p[i] = (float)pp[i];
   /* and zero out the rest */
   for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;

   mixerr = MX_FNAME;
   rt_temp = rt_list;
   rt_p = rt_list;

   while (rt_p) {

      if (strcmp(rt_p->rt_name, fname) == 0) {
         if (print_is_on) {
            printf("========<rt-queueing>=======\n");
            printf("%s:  ",fname);
            for (i = 0; i < n_args; i++)
               printf("%f ",p[i]);
            printf("\n");
         }

         /* set up the Instrument */

         Iptr = (*(rt_p->rt_ptr))();

         Iptr->ref();   // We do this to assure one reference

         rv = (double) Iptr->init(p, n_args, pp);

         if (rv != DONT_SCHEDULE) { // only schedule if no init() error
            // For non-interactive case, configure() is delayed until just
            // before instrument run time.
            if (rtInteractive)
               Iptr->configure();

            /* schedule instrument */
            Iptr->schedule(&rtHeap);

            mixerr = MX_NOERR;
            rt_list = rt_temp;
         } else {
            return rv;
         }

#ifdef DEBUG
         printf("EXITING checkInsts() FUNCTION -----\n");
#endif

         if (inst != NULL)
            *inst = (void *) Iptr;
         return rv;
      }
      rt_p = rt_p->rt_next;
   }
   rt_list = rt_temp;

#ifdef DEBUG
   printf("EXITING checkInsts() FUNCTION (function not found) -----\n");
#endif

   return 0.0;
}

#endif /* !PFIELD_CLASS */
<commit_msg>Fleshed out conditional support for PField classes (within ifdefs).<commit_after>/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <prototypes.h>
#include <maxdispargs.h>
#include <pthread.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/PField.h"
#include "../rtstuff/PFieldSet.h"
#include "../rtstuff/rt.h"
#include "../rtstuff/rtdefs.h"
#include "../sys/mixerr.h"
#include <stdio.h>
#include <string.h>

extern heap rtHeap;     // intraverse.C

//#define DEBUG

#ifdef PFIELD_CLASS

static void
_printargs(const char *instname, const Arg arglist[], const int nargs)
{
   int i;
   Arg arg;

   if (print_is_on) {
      printf("========<rt-queueing>=======\n");
      printf("%s:  ", instname);
      for (i = 0; i < nargs; i++) {
         arg = arglist[i];
         switch (arg.type) {
            case FloatType:
               printf("%g ", arg.val.number);
               break;
            case StringType:
               printf("\"%s\" ", arg.val.string);
               break;
            case HandleType:
               printf("Handle:%p ", arg.val.handle);
               break;
            case ArrayType:
               printf("[%g...%g] ", arg.val.array->data[0],
                              arg.val.array->data[arg.val.array->len - 1]);
               break;
            default:
               break;
         }
      }
      putchar('\n');
      fflush(stdout);
   }
}

double
checkInsts(const char *instname, const Arg arglist[], const int nargs, Arg *retval)
{
// FIXME: set this up as in addcheckfuncs, so that the guts of the
// instrument name list are not exposed here.  -JGG
   rt_item *rt_p;       // rt_item defined in rt.h
   rt_item *rt_temp;
   Instrument *Iptr;

#ifdef DEBUG
   printf("ENTERING checkInsts() FUNCTION -----\n");
#endif

   mixerr = MX_FNAME;
   rt_temp = rt_list;
   rt_p = rt_list;

   while (rt_p) {

      if (strcmp(rt_p->rt_name, instname) == 0) {

         _printargs(instname, arglist, nargs);

         /* set up the Instrument */

         Iptr = (*(rt_p->rt_ptr))();

         Iptr->ref();   // We do this to assure one reference

		// Load PFieldSet with ConstPField instances for each
		// valid p field.
		PFieldSet *pfieldset = new PFieldSet(nargs);
		for (int arg = 0; arg < nargs; ++arg) {
		  const Arg *pArg = &arglist[arg];
		  switch (pArg->type) {
    		 case FloatType:
        		pfieldset->load(new ConstPField((double) pArg->val.number), arg);
        		break;
    		 case StringType:
        		break;
    		 case HandleType:
        		pfieldset->load((PField *) pArg->val.handle, arg);
        		break;
			 case ArrayType:
				pfieldset->load(new TablePField(pArg->val.array->data,
												pArg->val.array->len),
								arg);
        		break;
    		 default:
        		break;
		  }
		}
         double rv = (double) Iptr->setup(pfieldset);

         if (rv != (double) DONT_SCHEDULE) { // only schedule if no init() error
            // For non-interactive case, configure() is delayed until just
            // before instrument run time.
            if (rtInteractive)
               Iptr->configure();

            /* schedule instrument */
            Iptr->schedule(&rtHeap);

            mixerr = MX_NOERR;
            rt_list = rt_temp;
         }
         else
            return rv;

#ifdef DEBUG
         printf("EXITING checkInsts() FUNCTION -----\n");
#endif

//FIXME: ??need to create Handle for Iptr on return
//       and return double rv?  can't be done in parse_dispatch now!

         return rv;
      }
      rt_p = rt_p->rt_next;
   }
   rt_list = rt_temp;

   return 0.0;
}

#else /* !PFIELD_CLASS */

double checkInsts(char *fname, double *pp, int n_args, void **inst)
{
   int i;
   rt_item *rt_p;
   rt_item *rt_temp;
   Instrument *Iptr;
   double rv;
   float p[MAXDISPARGS];

#ifdef DEBUG
   printf("ENTERING checkInsts() FUNCTION -----\n");
#endif

   /* convert pp to floats */
   for (i = 0; i < n_args; i++) p[i] = (float)pp[i];
   /* and zero out the rest */
   for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;

   mixerr = MX_FNAME;
   rt_temp = rt_list;
   rt_p = rt_list;

   while (rt_p) {

      if (strcmp(rt_p->rt_name, fname) == 0) {
         if (print_is_on) {
            printf("========<rt-queueing>=======\n");
            printf("%s:  ",fname);
            for (i = 0; i < n_args; i++)
               printf("%f ",p[i]);
            printf("\n");
         }

         /* set up the Instrument */

         Iptr = (*(rt_p->rt_ptr))();

         Iptr->ref();   // We do this to assure one reference

         rv = (double) Iptr->init(p, n_args, pp);

         if (rv != DONT_SCHEDULE) { // only schedule if no init() error
            // For non-interactive case, configure() is delayed until just
            // before instrument run time.
            if (rtInteractive)
               Iptr->configure();

            /* schedule instrument */
            Iptr->schedule(&rtHeap);

            mixerr = MX_NOERR;
            rt_list = rt_temp;
         } else {
            return rv;
         }

#ifdef DEBUG
         printf("EXITING checkInsts() FUNCTION -----\n");
#endif

         if (inst != NULL)
            *inst = (void *) Iptr;
         return rv;
      }
      rt_p = rt_p->rt_next;
   }
   rt_list = rt_temp;

#ifdef DEBUG
   printf("EXITING checkInsts() FUNCTION (function not found) -----\n");
#endif

   return 0.0;
}

#endif /* !PFIELD_CLASS */
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/codecs/test/videoprocessor_integrationtest.h"

#include <vector>

#include "test/field_trial.h"
#include "test/testsupport/fileutils.h"

namespace webrtc {
namespace test {

#if defined(WEBRTC_ANDROID)

namespace {
const int kForemanNumFrames = 300;
const std::nullptr_t kNoVisualizationParams = nullptr;
}  // namespace

class VideoProcessorIntegrationTestMediaCodec
    : public VideoProcessorIntegrationTest {
 protected:
  VideoProcessorIntegrationTestMediaCodec() {
    config_.filename = "foreman_cif";
    config_.input_filename = ResourcePath(config_.filename, "yuv");
    config_.output_filename =
        TempFilename(OutputPath(), "videoprocessor_integrationtest_mediacodec");
    config_.verbose = false;
    config_.hw_encoder = true;
    config_.hw_decoder = true;
  }
};

TEST_F(VideoProcessorIntegrationTestMediaCodec, ForemanCif500kbpsVp8) {
  SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
                   false, 352, 288);

  RateProfile rate_profile;
  SetRateProfile(&rate_profile, 0, 500, 30, 0);  // Start below |low_kbps|.
  rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;
  rate_profile.num_frames = kForemanNumFrames;

  // The thresholds below may have to be tweaked to let even poor MediaCodec
  // implementations pass. If this test fails on the bots, disable it and
  // ping brandtr@.
  std::vector<RateControlThresholds> rc_thresholds;
  AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);

  QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);

  ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
                              kNoVisualizationParams);
}

TEST_F(VideoProcessorIntegrationTestMediaCodec,
       Foreman240p100kbpsVp8WithForcedSwFallback) {
  ScopedFieldTrials override_field_trials(
      "WebRTC-VP8-Forced-Fallback-Encoder/Enabled-150,175,10000,1/");

  config_.filename = "foreman_320x240";
  config_.input_filename = ResourcePath(config_.filename, "yuv");
  config_.sw_fallback_encoder = true;
  SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
                   false, 320, 240);

  RateProfile rate_profile;
  SetRateProfile(&rate_profile, 0, 100, 10, 0);    // Start below |low_kbps|.
  SetRateProfile(&rate_profile, 1, 100, 10, 80);   // Fallback in this bucket.
  SetRateProfile(&rate_profile, 2, 200, 10, 200);  // Switch back here.
  rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;
  rate_profile.num_frames = kForemanNumFrames;

  // The thresholds below may have to be tweaked to let even poor MediaCodec
  // implementations pass. If this test fails on the bots, disable it and
  // ping brandtr@.
  std::vector<RateControlThresholds> rc_thresholds;
  AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);
  AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);
  AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);

  QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);

  ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
                              kNoVisualizationParams);
}

#endif  // defined(WEBRTC_ANDROID)

}  // namespace test
}  // namespace webrtc
<commit_msg>Disable flaky test VideoProcessorIntegrationTestMediaCodec.ForemanCif500kbpsVp8.<commit_after>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/codecs/test/videoprocessor_integrationtest.h"

#include <vector>

#include "test/field_trial.h"
#include "test/testsupport/fileutils.h"

namespace webrtc {
namespace test {

#if defined(WEBRTC_ANDROID)

namespace {
const int kForemanNumFrames = 300;
const std::nullptr_t kNoVisualizationParams = nullptr;
}  // namespace

class VideoProcessorIntegrationTestMediaCodec
    : public VideoProcessorIntegrationTest {
 protected:
  VideoProcessorIntegrationTestMediaCodec() {
    config_.filename = "foreman_cif";
    config_.input_filename = ResourcePath(config_.filename, "yuv");
    config_.output_filename =
        TempFilename(OutputPath(), "videoprocessor_integrationtest_mediacodec");
    config_.verbose = false;
    config_.hw_encoder = true;
    config_.hw_decoder = true;
  }
};

TEST_F(VideoProcessorIntegrationTestMediaCodec, DISABLED_ForemanCif500kbpsVp8) {
  SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
                   false, 352, 288);

  RateProfile rate_profile;
  SetRateProfile(&rate_profile, 0, 500, 30, 0);  // Start below |low_kbps|.
  rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;
  rate_profile.num_frames = kForemanNumFrames;

  // The thresholds below may have to be tweaked to let even poor MediaCodec
  // implementations pass. If this test fails on the bots, disable it and
  // ping brandtr@.
  std::vector<RateControlThresholds> rc_thresholds;
  AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);

  QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);

  ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
                              kNoVisualizationParams);
}

TEST_F(VideoProcessorIntegrationTestMediaCodec,
       Foreman240p100kbpsVp8WithForcedSwFallback) {
  ScopedFieldTrials override_field_trials(
      "WebRTC-VP8-Forced-Fallback-Encoder/Enabled-150,175,10000,1/");

  config_.filename = "foreman_320x240";
  config_.input_filename = ResourcePath(config_.filename, "yuv");
  config_.sw_fallback_encoder = true;
  SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
                   false, 320, 240);

  RateProfile rate_profile;
  SetRateProfile(&rate_profile, 0, 100, 10, 0);    // Start below |low_kbps|.
  SetRateProfile(&rate_profile, 1, 100, 10, 80);   // Fallback in this bucket.
  SetRateProfile(&rate_profile, 2, 200, 10, 200);  // Switch back here.
  rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;
  rate_profile.num_frames = kForemanNumFrames;

  // The thresholds below may have to be tweaked to let even poor MediaCodec
  // implementations pass. If this test fails on the bots, disable it and
  // ping brandtr@.
  std::vector<RateControlThresholds> rc_thresholds;
  AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);
  AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);
  AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);

  QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);

  ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
                              kNoVisualizationParams);
}

#endif  // defined(WEBRTC_ANDROID)

}  // namespace test
}  // namespace webrtc
<|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2012, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Willow Garage nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>

namespace kinematics_plugin_loader
{

const double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;

class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
  KinematicsLoaderImpl(const std::string &robot_description,
                       const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
                       const std::map<std::string, std::vector<double> > &search_res,
                       const std::map<std::string, std::string> &ik_links) :
    robot_description_(robot_description),
    possible_kinematics_solvers_(possible_kinematics_solvers),
    search_res_(search_res),
    ik_links_(ik_links)
  {
    try
    {
      kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
    }
    catch(pluginlib::PluginlibException& e)
    {
      ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
    }
  }

  boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
  {
    boost::shared_ptr<kinematics::KinematicsBase> result;
    if (!jmg)
    {
      ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
      return result;
    }

    ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());

    if (kinematics_loader_ && jmg)
    {
      std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
      if (it != possible_kinematics_solvers_.end())
      {
        // just to be sure, do not call the same pluginlib instance allocation function in parallel
        boost::mutex::scoped_lock slock(lock_);

        for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
        {
          try
          {
            result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
            if (result)
            {
              const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
              if (!links.empty())
              {
                const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
                  links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();
                std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
                const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
                double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
                if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))
                {
                  ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
                  result.reset();
                }
                else
                  ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
                            it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
              }
              else
                ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
            }
          }
          catch (pluginlib::PluginlibException& e)
          {
            ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
          }
        }
      }
      else
        ROS_DEBUG("No kinematics solver available for this group");
    }

    if (!result)
      ROS_DEBUG("No usable kinematics solver was found for this group");
    return result;
  }

  boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
  {
    {
      boost::mutex::scoped_lock slock(lock_);
      const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
      for (std::size_t i = 0 ;  i < vi.size() ; ++i)
        if (vi[i].unique())
        {
          ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
          return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
        }
    }

    boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);

    {
      boost::mutex::scoped_lock slock(lock_);
      instances_[jmg].push_back(res);
      return res;
    }
  }

  void status() const
  {
    for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
      for (std::size_t i = 0 ; i < it->second.size() ; ++i)
        ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
  }

private:

  std::string                                                            robot_description_;
  std::map<std::string, std::vector<std::string> >                       possible_kinematics_solvers_;
  std::map<std::string, std::vector<double> >                            search_res_;
  std::map<std::string, std::string>                                     ik_links_;
  boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
  std::map<const robot_model::JointModelGroup*,
           std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
  boost::mutex                                                           lock_;
};

}

void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
  if (loader_)
    loader_->status();
  else
    ROS_INFO("Loader function was never required");
}

robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
  moveit::Profiler::ScopedStart prof_start;
  moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");

  if (loader_)
    return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);

  rdf_loader::RDFLoader rml(robot_description_);
  robot_description_ = rml.getRobotDescription();
  return getLoaderFunction(rml.getSRDF());
}

robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
  moveit::Profiler::ScopedStart prof_start;
  moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");

  if (!loader_)
  {
    ROS_DEBUG("Configuring kinematics solvers");
    groups_.clear();

    std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
    std::map<std::string, std::vector<double> > search_res;
    std::map<std::string, std::string> ik_links;

    if (srdf_model)
    {
      const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
      if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
        default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;

      if (default_solver_plugin_.empty())
      {
        ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");

        // read data using ROS params
        ros::NodeHandle nh("~");

        // read the list of plugin names for possible kinematics solvers
        for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
        {
          ROS_DEBUG("Looking for param %s ", (known_groups[i].name_ + "/kinematics_solver").c_str());
          std::string ksolver_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver", ksolver_param_name))
          {
            ROS_DEBUG("Found param %s ", ksolver_param_name.c_str());
            std::string ksolver;
            if (nh.getParam(ksolver_param_name, ksolver))
            {
              std::stringstream ss(ksolver);
              bool first = true;
              while (ss.good() && !ss.eof())
              {
                if (first)
                {
                  first = false;
                  groups_.push_back(known_groups[i].name_);
                }
                std::string solver; ss >> solver >> std::ws;
                possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
                ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
              }
            }
          }

          std::string ksolver_timeout_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_timeout", ksolver_timeout_param_name))
          {
            double ksolver_timeout;
            if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
              ik_timeout_[known_groups[i].name_] = ksolver_timeout;
            else
            {// just in case this is an int
              int ksolver_timeout_i;
              if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
                ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
            }
          }

          std::string ksolver_attempts_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_attempts", ksolver_attempts_param_name))
          {
            int ksolver_attempts;
            if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
              ik_attempts_[known_groups[i].name_] = ksolver_attempts;
          }

          std::string ksolver_res_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_search_resolution", ksolver_res_param_name))
          {
            std::string ksolver_res;
            if (nh.getParam(ksolver_res_param_name, ksolver_res))
            {
              std::stringstream ss(ksolver_res);
              while (ss.good() && !ss.eof())
              {
                double res; ss >> res >> std::ws;
                search_res[known_groups[i].name_].push_back(res);
              }
            }
            else
            { // handle the case this param is just one value and parsed as a double
              double res;
              if (nh.getParam(ksolver_res_param_name, res))
                search_res[known_groups[i].name_].push_back(res);
              else
              {
                int res_i;
                if (nh.getParam(ksolver_res_param_name, res_i))
                  search_res[known_groups[i].name_].push_back(res_i);
              }
            }
          }

          std::string ksolver_ik_link_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
          {
            std::string ksolver_ik_link;
            if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
              ik_links[known_groups[i].name_] = ksolver_ik_link;
          }

          // make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
          while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
            search_res[known_groups[i].name_].push_back(default_search_resolution_);
        }
      }
      else
      {
        ROS_DEBUG("Using specified default settings for kinematics solvers ...");
        for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
        {
          possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
          search_res[known_groups[i].name_].resize(1, default_search_resolution_);
          ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
          ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
          groups_.push_back(known_groups[i].name_);
        }
      }
    }

    loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
  }

  return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
<commit_msg>Added debug info to remind user to load kinematics.yaml<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2012, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Willow Garage nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>

namespace kinematics_plugin_loader
{

const double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;

class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
  KinematicsLoaderImpl(const std::string &robot_description,
                       const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
                       const std::map<std::string, std::vector<double> > &search_res,
                       const std::map<std::string, std::string> &ik_links) :
    robot_description_(robot_description),
    possible_kinematics_solvers_(possible_kinematics_solvers),
    search_res_(search_res),
    ik_links_(ik_links)
  {
    try
    {
      kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
    }
    catch(pluginlib::PluginlibException& e)
    {
      ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
    }
  }

  boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
  {
    boost::shared_ptr<kinematics::KinematicsBase> result;
    if (!jmg)
    {
      ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
      return result;
    }

    ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());

    if (kinematics_loader_ && jmg)
    {
      std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
      if (it != possible_kinematics_solvers_.end())
      {
        // just to be sure, do not call the same pluginlib instance allocation function in parallel
        boost::mutex::scoped_lock slock(lock_);

        for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
        {
          try
          {
            result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
            if (result)
            {
              const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
              if (!links.empty())
              {
                const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
                  links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();
                std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
                const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
                double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
                if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))
                {
                  ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
                  result.reset();
                }
                else
                  ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
                            it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
              }
              else
                ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
            }
          }
          catch (pluginlib::PluginlibException& e)
          {
            ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
          }
        }
      }
      else
        ROS_DEBUG("No kinematics solver available for this group");
    }

    if (!result)
    {
      ROS_DEBUG("No usable kinematics solver was found for this group.");
      ROS_DEBUG("Did you load kinematics.yaml into your node's namespace?");
    }
    return result;
  }

  boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
  {
    {
      boost::mutex::scoped_lock slock(lock_);
      const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
      for (std::size_t i = 0 ;  i < vi.size() ; ++i)
        if (vi[i].unique())
        {
          ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
          return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
        }
    }

    boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);

    {
      boost::mutex::scoped_lock slock(lock_);
      instances_[jmg].push_back(res);
      return res;
    }
  }

  void status() const
  {
    for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
      for (std::size_t i = 0 ; i < it->second.size() ; ++i)
        ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
  }

private:

  std::string                                                            robot_description_;
  std::map<std::string, std::vector<std::string> >                       possible_kinematics_solvers_;
  std::map<std::string, std::vector<double> >                            search_res_;
  std::map<std::string, std::string>                                     ik_links_;
  boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
  std::map<const robot_model::JointModelGroup*,
           std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
  boost::mutex                                                           lock_;
};

}

void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
  if (loader_)
    loader_->status();
  else
    ROS_INFO("Loader function was never required");
}

robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
  moveit::Profiler::ScopedStart prof_start;
  moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");

  if (loader_)
    return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);

  rdf_loader::RDFLoader rml(robot_description_);
  robot_description_ = rml.getRobotDescription();
  return getLoaderFunction(rml.getSRDF());
}

robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
  moveit::Profiler::ScopedStart prof_start;
  moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");

  if (!loader_)
  {
    ROS_DEBUG("Configuring kinematics solvers");
    groups_.clear();

    std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
    std::map<std::string, std::vector<double> > search_res;
    std::map<std::string, std::string> ik_links;

    if (srdf_model)
    {
      const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
      if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
        default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;

      if (default_solver_plugin_.empty())
      {
        ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");

        // read data using ROS params
        ros::NodeHandle nh("~");

        // read the list of plugin names for possible kinematics solvers
        for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
        {
          ROS_DEBUG("Looking for param %s ", (known_groups[i].name_ + "/kinematics_solver").c_str());
          std::string ksolver_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver", ksolver_param_name))
          {
            ROS_DEBUG("Found param %s ", ksolver_param_name.c_str());
            std::string ksolver;
            if (nh.getParam(ksolver_param_name, ksolver))
            {
              std::stringstream ss(ksolver);
              bool first = true;
              while (ss.good() && !ss.eof())
              {
                if (first)
                {
                  first = false;
                  groups_.push_back(known_groups[i].name_);
                }
                std::string solver; ss >> solver >> std::ws;
                possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
                ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
              }
            }
          }

          std::string ksolver_timeout_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_timeout", ksolver_timeout_param_name))
          {
            double ksolver_timeout;
            if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
              ik_timeout_[known_groups[i].name_] = ksolver_timeout;
            else
            {// just in case this is an int
              int ksolver_timeout_i;
              if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
                ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
            }
          }

          std::string ksolver_attempts_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_attempts", ksolver_attempts_param_name))
          {
            int ksolver_attempts;
            if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
              ik_attempts_[known_groups[i].name_] = ksolver_attempts;
          }

          std::string ksolver_res_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_search_resolution", ksolver_res_param_name))
          {
            std::string ksolver_res;
            if (nh.getParam(ksolver_res_param_name, ksolver_res))
            {
              std::stringstream ss(ksolver_res);
              while (ss.good() && !ss.eof())
              {
                double res; ss >> res >> std::ws;
                search_res[known_groups[i].name_].push_back(res);
              }
            }
            else
            { // handle the case this param is just one value and parsed as a double
              double res;
              if (nh.getParam(ksolver_res_param_name, res))
                search_res[known_groups[i].name_].push_back(res);
              else
              {
                int res_i;
                if (nh.getParam(ksolver_res_param_name, res_i))
                  search_res[known_groups[i].name_].push_back(res_i);
              }
            }
          }

          std::string ksolver_ik_link_param_name;
          if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
          {
            std::string ksolver_ik_link;
            if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
              ik_links[known_groups[i].name_] = ksolver_ik_link;
          }

          // make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
          while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
            search_res[known_groups[i].name_].push_back(default_search_resolution_);
        }
      }
      else
      {
        ROS_DEBUG("Using specified default settings for kinematics solvers ...");
        for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
        {
          possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
          search_res[known_groups[i].name_].resize(1, default_search_resolution_);
          ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
          ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
          groups_.push_back(known_groups[i].name_);
        }
      }
    }

    loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
  }

  return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/Directory.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"
#include "File.h"
#include "logging/Logger.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <cassert>
#include <windows.h>
#include <winapifamily.h>

namespace medialibrary
{

namespace fs
{

Directory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
{
    m_path = utils::file::toFolderPath(
                utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );
    assert( *m_path.crbegin() == '/' || *m_path.crbegin() == '\\' );
    m_mrl = utils::file::toMrl( m_path );
}

const std::string& Directory::mrl() const
{
    return m_mrl;
}

void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
    WIN32_FIND_DATA f;
    auto pattern = m_path + '*';
    auto wpattern = charset::ToWide( pattern.c_str() );
    auto h = FindFirstFile( wpattern.get(), &f );
    if ( h == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to browse ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
    }
    do
    {
        auto file = charset::FromWide( f.cFileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        auto fullpath = m_path + file.get();
        try
        {
            if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory(
                                         m_mrl + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( fullpath ) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    } while ( FindNextFile( h, &f ) != 0 );
    FindClose( h );
#else
    // We must remove the trailing /
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
    // «Do not use a trailing backslash (\), which indicates the root directory of a drive»
    auto tmpPath = path.substr( 0, m_path.length() - 1 );
    auto wpath = charset::ToWide( tmpPath.c_str() );

    CREATEFILE2_EXTENDED_PARAMETERS params{};
    params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
    auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params );
    if ( handle == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to open directory ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
    }

    std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
            decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );

    // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
    size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
    std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
                reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
                [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
    if ( dirInfo == nullptr )
        throw std::bad_alloc();

    while ( true )
    {
        auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
        if ( h == 0 )
        {
            auto error = GetLastError();
            if ( error == ERROR_FILE_NOT_FOUND )
                break;
            else if ( error == ERROR_MORE_DATA )
            {
                buffSize *= 2;
                dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
                if ( dirInfo == nullptr )
                    throw std::bad_alloc();
                continue;
            }
            LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
            throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
        }

        auto file = charset::FromWide( dirInfo->FileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        try
        {
            if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    }
#endif
}

}

}
<commit_msg>fix typo when compiling for Windows Store<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/Directory.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"
#include "File.h"
#include "logging/Logger.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <cassert>
#include <windows.h>
#include <winapifamily.h>

namespace medialibrary
{

namespace fs
{

Directory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
{
    m_path = utils::file::toFolderPath(
                utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );
    assert( *m_path.crbegin() == '/' || *m_path.crbegin() == '\\' );
    m_mrl = utils::file::toMrl( m_path );
}

const std::string& Directory::mrl() const
{
    return m_mrl;
}

void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
    WIN32_FIND_DATA f;
    auto pattern = m_path + '*';
    auto wpattern = charset::ToWide( pattern.c_str() );
    auto h = FindFirstFile( wpattern.get(), &f );
    if ( h == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to browse ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
    }
    do
    {
        auto file = charset::FromWide( f.cFileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        auto fullpath = m_path + file.get();
        try
        {
            if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory(
                                         m_mrl + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( fullpath ) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    } while ( FindNextFile( h, &f ) != 0 );
    FindClose( h );
#else
    // We must remove the trailing /
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
    // «Do not use a trailing backslash (\), which indicates the root directory of a drive»
    auto tmpPath = m_path.substr( 0, m_path.length() - 1 );
    auto wpath = charset::ToWide( tmpPath.c_str() );

    CREATEFILE2_EXTENDED_PARAMETERS params{};
    params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
    auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params );
    if ( handle == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to open directory ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
    }

    std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
            decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );

    // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
    size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
    std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
                reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
                [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
    if ( dirInfo == nullptr )
        throw std::bad_alloc();

    while ( true )
    {
        auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
        if ( h == 0 )
        {
            auto error = GetLastError();
            if ( error == ERROR_FILE_NOT_FOUND )
                break;
            else if ( error == ERROR_MORE_DATA )
            {
                buffSize *= 2;
                dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
                if ( dirInfo == nullptr )
                    throw std::bad_alloc();
                continue;
            }
            LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
            throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
        }

        auto file = charset::FromWide( dirInfo->FileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        try
        {
            if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    }
#endif
}

}

}
<|endoftext|>


<commit_before>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013                                   Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
	the size of the array as user input (validate!), max size
	should be 10 (declared as class constant). Perform a
	variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
	perform functions.
************************************************************/
#include <iostream>
using namespace std;

// various array handling functions
float average(float numbers[]);
void even(float numbers[]);
void odd(float numbers[]);
float evenSum(float numbers[]);
float oddSum(float numbers[]);

int main()
{
	// redo with arrays
	// copy back in commit c864814b032eff90c493701556f869aff79629d4
	//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp

	int arraySize = 0; // size of the array
	const int maxArraySize = 10; // max size of the array
	float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in

	cout << "This program does a number of calculations on an array.\n"
		<< "Enter the size of the array up to 10.\n";
	while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
	{
		cin.clear();     // Clear the error flags
		cin.ignore(100, '\n');    // Remove unwanted characters from buffer
		cout << "\aEnter a positive integer, less than 10: ";   // Re-issue the prompt
	}
	// test:
	cout << arraySize;

	float *numbers;
	numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions

	for (int i = 0; i < arraySize; i++) // loop to fill array
	{
		cout << "Position " << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
		while ((!(cin >> numbers[i]))) //detects errors in input
		{
			cin.clear();     // Clear the error flags
			cin.ignore(100, '\n');    // Remove unwanted characters from buffer
			cout << "\aInput Error. Please enter a number only.\n" // if error, sound the alarm
				<< "Position " << (i + 1) << ": ";
		}
	}

	cout << "\nExcellent. Your inputs are:\n";
	cout << "| "; // first separator for clarity
	for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
	{
		cout << numbers[i] << " | "; // put formatted separator in
	}

	return 0;
}<commit_msg>removed test<commit_after>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013                                   Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
	the size of the array as user input (validate!), max size
	should be 10 (declared as class constant). Perform a
	variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
	perform functions.
************************************************************/
#include <iostream>
using namespace std;

// various array handling functions
float average(float numbers[]);
void even(float numbers[]);
void odd(float numbers[]);
float evenSum(float numbers[]);
float oddSum(float numbers[]);

int main()
{
	// redo with arrays
	// copy back in commit c864814b032eff90c493701556f869aff79629d4
	//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp

	int arraySize = 0; // size of the array
	const int maxArraySize = 10; // max size of the array
	float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in

	cout << "This program does a number of calculations on an array.\n"
		<< "Enter the size of the array up to 10.\n";
	while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
	{
		cin.clear();     // Clear the error flags
		cin.ignore(100, '\n');    // Remove unwanted characters from buffer
		cout << "\aEnter a positive integer, less than 10: ";   // Re-issue the prompt
	}

	float *numbers;
	numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions

	for (int i = 0; i < arraySize; i++) // loop to fill array
	{
		cout << "Position " << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
		while ((!(cin >> numbers[i]))) //detects errors in input
		{
			cin.clear();     // Clear the error flags
			cin.ignore(100, '\n');    // Remove unwanted characters from buffer
			cout << "\aInput Error. Please enter a number only.\n" // if error, sound the alarm
				<< "Position " << (i + 1) << ": ";
		}
	}

	cout << "\nExcellent. Your inputs are:\n";
	cout << "| "; // first separator for clarity
	for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
	{
		cout << numbers[i] << " | "; // put formatted separator in
	}

	return 0;
}<|endoftext|>