<commit_before>#include <easylogging.h>

#include "utils/texture2d.h"

#include <glm/gtc/type_ptr.hpp>

#include <functional>
#include <stdexcept>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <cstdint>
#include <cctype>
#include <locale>

static unsigned char saturate(float x)
{
    if (x < 0) return 0;
    if (x > 1) return 255;
    return (int)(x * 255);
}

static GLuint alloc_texture(const glm::ivec2& dims,
                            const void *raw_ptr,
                            GLenum internal,
                            GLenum format)
{
    GLuint tex;

    glGenTextures(1, &tex);
    if (!tex) {
        LOG(ERROR) << "Failed to generate texture.";
        LOG(TRACE) << "glGenTextures failed.";
        throw std::runtime_error("");
    }

    glBindTexture(GL_TEXTURE_2D, tex);

    glTexImage2D(GL_TEXTURE_2D, 0, internal, dims.x, dims.y,
                         0, GL_RGBA, format, raw_ptr);

    return tex;
}

static std::vector<uint8_t> image_to_bytes(const image& img)
{
    auto w = img.dims().x;
    auto h = img.dims().y;

    auto buf = std::vector<unsigned char>();
    buf.resize(w * h * 4); // 4 bytes/pixel

    for (int y = 0; y < h; ++y) {
        const glm::vec4* ptr = img[y];

        for (int x = 0; x < w; ++x) {
            buf[4 * (y * w + x) + 0] = saturate(ptr->x);
            buf[4 * (y * w + x) + 1] = saturate(ptr->y);
            buf[4 * (y * w + x) + 2] = saturate(ptr->z);
            buf[4 * (y * w + x) + 3] = saturate(ptr->w);

            ++ptr;
        }
    }

    return buf;
}

static bool image_is_opaque(const image& img)
{
    for (int y = 0; y < img.dims().y; ++y) {
        const glm::vec4* ptr = img[y];

        for (int x = 0; x < img.dims().x; ++x) {
            if ((ptr->w > 0) && (ptr->w < 1)) {
                return false;
            }

            ++ptr;
        }
    }

    return true;
}

namespace gl
{
    texture2D::texture2D(const std::string& path, GLenum format)
        : m_fmt(format), m_tex(0)
    {
        image img(path);
        m_dims = img.dims();

        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, img.data(),
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }

        m_opaque = image_is_opaque(img);
    }

    texture2D::texture2D(const image& img, GLenum format)
        : m_fmt(format)
    {
        m_dims = img.dims();

        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, img.data(),
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }

        m_opaque = image_is_opaque(img);
    }

    texture2D::texture2D(const glm::ivec2& dims, GLenum format)
        : m_dims(dims), m_fmt(format), m_opaque(true)
    {
        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }
    }

    texture2D::~texture2D()
    {
        if (m_tex) {
            glDeleteTextures(1, &m_tex);
        }
    }

    void texture2D::resize(const glm::ivec2& dims)
    {
        m_dims = dims;

        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA32F, GL_FLOAT);
        }

        m_opaque = true;
    }

    void texture2D::bind(int unit, int min_filter,
                                   int mag_filter,
                                   int wrap_s,
                                   int wrap_t) const
    {
        glActiveTexture(GL_TEXTURE0 + unit);
        glBindTexture(GL_TEXTURE_2D, m_tex);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t);
    }

    GLuint texture2D::operator()() const
    {
        return m_tex;
    }

    glm::ivec2 texture2D::dims() const
    {
        return m_dims;
    }

    bool texture2D::is_opaque() const
    {
        return m_opaque;
    }
}
<commit_msg>Memory leak fix<commit_after>#include <easylogging.h>

#include "utils/texture2d.h"

#include <glm/gtc/type_ptr.hpp>

#include <functional>
#include <stdexcept>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <cstdint>
#include <cctype>
#include <locale>

static unsigned char saturate(float x)
{
    if (x < 0) return 0;
    if (x > 1) return 255;
    return (int)(x * 255);
}

static GLuint alloc_texture(const glm::ivec2& dims,
                            const void *raw_ptr,
                            GLenum internal,
                            GLenum format)
{
    GLuint tex;

    glGenTextures(1, &tex);
    if (!tex) {
        LOG(ERROR) << "Failed to generate texture.";
        LOG(TRACE) << "glGenTextures failed.";
        throw std::runtime_error("");
    }

    glBindTexture(GL_TEXTURE_2D, tex);

    glTexImage2D(GL_TEXTURE_2D, 0, internal, dims.x, dims.y,
                         0, GL_RGBA, format, raw_ptr);

    return tex;
}

static std::vector<uint8_t> image_to_bytes(const image& img)
{
    auto w = img.dims().x;
    auto h = img.dims().y;

    auto buf = std::vector<unsigned char>();
    buf.resize(w * h * 4); // 4 bytes/pixel

    for (int y = 0; y < h; ++y) {
        const glm::vec4* ptr = img[y];

        for (int x = 0; x < w; ++x) {
            buf[4 * (y * w + x) + 0] = saturate(ptr->x);
            buf[4 * (y * w + x) + 1] = saturate(ptr->y);
            buf[4 * (y * w + x) + 2] = saturate(ptr->z);
            buf[4 * (y * w + x) + 3] = saturate(ptr->w);

            ++ptr;
        }
    }

    return buf;
}

static bool image_is_opaque(const image& img)
{
    for (int y = 0; y < img.dims().y; ++y) {
        const glm::vec4* ptr = img[y];

        for (int x = 0; x < img.dims().x; ++x) {
            if ((ptr->w > 0) && (ptr->w < 1)) {
                return false;
            }

            ++ptr;
        }
    }

    return true;
}

namespace gl
{
    texture2D::texture2D(const std::string& path, GLenum format)
        : m_fmt(format), m_tex(0)
    {
        image img(path);
        m_dims = img.dims();

        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, img.data(),
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }

        m_opaque = image_is_opaque(img);
    }

    texture2D::texture2D(const image& img, GLenum format)
        : m_fmt(format)
    {
        m_dims = img.dims();

        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, img.data(),
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }

        m_opaque = image_is_opaque(img);
    }

    texture2D::texture2D(const glm::ivec2& dims, GLenum format)
        : m_dims(dims), m_fmt(format), m_opaque(true)
    {
        if (m_fmt == GL_UNSIGNED_BYTE) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA32F, GL_FLOAT);
        } else {
            LOG(ERROR) << "Unsupported texture format.";
            LOG(TRACE) << "Supported formats are:";
            LOG(TRACE) << "* GL_UNSIGNED_BYTE";
            LOG(TRACE) << "* GL_FLOAT";
            throw std::logic_error("");
        }
    }

    texture2D::~texture2D()
    {
        glDeleteTextures(1, &m_tex);
    }

    void texture2D::resize(const glm::ivec2& dims)
    {
        m_dims = dims;

        if (m_fmt == GL_UNSIGNED_BYTE) {
            glDeleteTextures(1, &m_tex);
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA, GL_UNSIGNED_BYTE);
        } else if (m_fmt == GL_FLOAT) {
            glDeleteTextures(1, &m_tex);
            m_tex = alloc_texture(m_dims, nullptr,
                                  GL_RGBA32F, GL_FLOAT);
        }

        m_opaque = true;
    }

    void texture2D::bind(int unit, int min_filter,
                                   int mag_filter,
                                   int wrap_s,
                                   int wrap_t) const
    {
        glActiveTexture(GL_TEXTURE0 + unit);
        glBindTexture(GL_TEXTURE_2D, m_tex);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t);
    }

    GLuint texture2D::operator()() const
    {
        return m_tex;
    }

    glm::ivec2 texture2D::dims() const
    {
        return m_dims;
    }

    bool texture2D::is_opaque() const
    {
        return m_opaque;
    }
}
<|endoftext|>


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

#ifndef included_6603F051_ED25_4096_8DCF_0F4A5829CACD
#define included_6603F051_ED25_4096_8DCF_0F4A5829CACD

#include <type_traits>
#include <utility>

namespace acm {
    namespace detail  {

        namespace adl_swap_ns {
            using std::swap;

            template <class T>
            struct is_nothrow_swappable_test {
                static bool constexpr value = noexcept(swap(std::declval<T&>(), std::declval<T&>()));
            };
        } // namespace adl_swap_ns

        // This really should be part of C++
        template <class T>
        struct is_nothrow_swappable
            : std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<T>::value>
        {};

    } // namespace detail
} // namespace acm

#endif // included_6603F051_ED25_4096_8DCF_0F4A5829CACD
<commit_msg>Add is_swappable and make is_nothrow_swappable honor it<commit_after>// Copyright 2013 Andrew C. Morrow
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef included_6603F051_ED25_4096_8DCF_0F4A5829CACD
#define included_6603F051_ED25_4096_8DCF_0F4A5829CACD

#include <type_traits>
#include <utility>

namespace acm {
    namespace detail  {

        namespace adl_swap_ns {
            using std::swap;

            template<typename T>
            struct is_swappable_test {

                template<typename U>
                static decltype(swap(std::declval<U&>(), std::declval<U&>())) test(const U&);

                template<typename U>
                static bool test(...);

                using test_type = decltype(test<T>(std::declval<T&>()));
                static constexpr bool value = std::is_void<test_type>::value;
            };

            template<bool, typename T>
            struct is_nothrow_swappable_test :
                std::integral_constant<bool, noexcept(swap(std::declval<T&>(), std::declval<T&>()))> {
            };

            template<typename T>
            struct is_nothrow_swappable_test<false, T> :
                std::false_type {
            };

        } // namespace adl_swap_ns

        template<typename T>
        struct is_swappable :
            std::integral_constant<bool, adl_swap_ns::is_swappable_test<T>::value> {};

        // This really should be part of C++
        template<typename T>
        struct is_nothrow_swappable
            : std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<is_swappable<T>::value, T>::value>
        {};

    } // namespace detail
} // namespace acm

#endif // included_6603F051_ED25_4096_8DCF_0F4A5829CACD
<|endoftext|>


<commit_before>#include "game_mode.hpp"
#include "mock_controller.hpp"
#include "mock_observer.hpp"
#include "mock_view.hpp"

#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::Return;

#include <stdexcept>
using namespace std;

namespace {
  class DISABLED_GameModeTest : public ::testing::Test {
  protected:
    DISABLED_GameModeTest() {
    }

    virtual ~DISABLED_GameModeTest() {
    }

    virtual void SetUp() {
    }

    virtual void TearDown() {
    }

  };

  TEST_F(DISABLED_GameModeTest, GetsAndProcessEventsFromController) {

    MockController mc;
    MockView mv;
    GameMode gm(&mc, &mv);

    EXPECT_CALL(mc,check_events())
      .WillOnce(Return(false))
      .WillOnce(Return(true));
    EXPECT_CALL(mc,handle_event());

    // First call will get nothing
    gm.update_game(10);
    // Second call will get an event and process it
    gm.update_game(10);

  }

  TEST_F(DISABLED_GameModeTest, UsesViewToRenderTheContent) {
    MockController mc;
    MockView mv;
    GameMode gm(&mc, &mv);

    EXPECT_CALL(mv, render_game()).Times(1);

    gm.render_game();
  }

  TEST_F(DISABLED_GameModeTest, AddObserversToControllerAndView) {
    MockObserver o;
    MockController mc;
    MockView mv;

    GameMode gm(&mc, &mv);

    EXPECT_CALL(mc, add_observer(&o));
    EXPECT_CALL(o, handle_event(12));

    gm.add_observer(&o);
    gm.fire_event(12);

  }

} // Namespace
<commit_msg>Test cleanup.<commit_after>#include "game_mode.hpp"
#include "mock_controller.hpp"
#include "mock_observer.hpp"
#include "mock_view.hpp"

#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::Return;

#include <stdexcept>
using namespace std;

namespace {
  class GameModeTest : public ::testing::Test {
  protected:
    GameModeTest() {
    }

    virtual ~GameModeTest() {
    }

    virtual void SetUp() {
    }

    virtual void TearDown() {
    }

  };

  TEST_F(GameModeTest, GetsAndProcessEventsFromController) {

    MockController mc;
    MockView mv;
    GameMode gm(&mc, &mv);

    EXPECT_CALL(mc,check_events())
      .WillOnce(Return(false))
      .WillOnce(Return(true));
    EXPECT_CALL(mc,handle_event());

    // First call will get nothing
    gm.update_game(10);
    // Second call will get an event and process it
    gm.update_game(10);

  }

  TEST_F(GameModeTest, UsesViewToRenderTheContent) {
    MockController mc;
    MockView mv;
    GameMode gm(&mc, &mv);

    EXPECT_CALL(mv, render_game()).Times(1);

    gm.render_game();
  }

  TEST_F(GameModeTest, AddObserversToControllerAndView) {
    MockObserver o;
    MockController mc;
    MockView mv;

    GameMode gm(&mc, &mv);

    EXPECT_CALL(mc, add_observer(&o));
    EXPECT_CALL(o, handle_event(12));

    gm.add_observer(&o);
    gm.fire_event(12);

  }

} // Namespace
<|endoftext|>


<commit_before>/**
 ** \file object/system-class.cc
 ** \brief Creation of the URBI object system.
 */

//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/cstdlib>

#include <memory>
#include <sstream>

#include <kernel/userver.hh>
#include <kernel/uconnection.hh>

#include <object/code.hh>
#include <object/cxx-primitive.hh>
#include <object/dictionary.hh>
#include <object/float.hh>
#include <object/global.hh>
#include <object/lobby.hh>
#include <object/list.hh>
#include <object/system.hh>
#include <object/tag.hh>
#include <object/task.hh>
#include <parser/transform.hh>
#include <runner/at-handler.hh>
#include <runner/call.hh>
#include <runner/interpreter.hh>
#include <runner/raise.hh>
#include <runner/runner.hh>

#include <ast/nary.hh>
#include <ast/routine.hh>

namespace object
{

  rObject
  execute_parsed(runner::Runner& r,
                 parser::parse_result_type p,
                 libport::Symbol fun, std::string e)
  {
    runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);

    // Report potential errors
    {
      ast::rNary errs = new ast::Nary();
      p->process_errors(*errs);
      run(errs.get());
    }

    ast::rConstAst ast = parser::transform(p->ast_get());
    if (!ast)
      runner::raise_primitive_error(e);

    runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);
    // So that it will resist to the call to yield_until_terminated,
    // and will be reclaimed at the end of the scope.
    scheduler::rJob job = sub;
    libport::Finally finally;
    r.register_child(sub, finally);
    sub->start_job();
    try
    {
      run.yield_until_terminated(*job);
    }
    catch (const scheduler::ChildException& ce)
    {
      // Kill the sub-job and propagate.
      scheduler::rethrow(ce.child_exception_get());
    }
    return sub->result_get();
  }

  rObject system_class;

  /*--------------------.
  | System primitives.  |
  `--------------------*/

#define SERVER_FUNCTION(Function)					\
  static rObject							\
  system_class_ ## Function (runner::Runner&, objects_type args)	\
  {									\
    check_arg_count(args.size() - 1, 0);                                \
    ::urbiserver->Function();						\
    return void_class;							\
  }

  SERVER_FUNCTION(reboot)
  SERVER_FUNCTION(shutdown)

#undef SERVER_FUNCTION

  static rObject
  system_class_sleep (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);

    type_check(args[1], Float::proto);

    rFloat arg1 = args[1]->as<Float>();
    libport::utime_t deadline;
    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())
      deadline = std::numeric_limits<libport::utime_t>::max();
    else
      deadline = r.scheduler_get().get_time() +
	static_cast<libport::utime_t>(arg1->value_get() * 1000000.0);
    r.yield_until (deadline);
    return void_class;
  }

  static rObject
  system_class_time(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(r.scheduler_get().get_time() / 1000000.0);
  }

  static rObject
  system_class_shiftedTime(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float((r.scheduler_get().get_time() -
			  r.time_shift_get()) / 1000000.0);
  }

  static rObject
  system_class_assert_(runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 2);
    type_check(args[2], String::proto);
    rString arg2 = args[2]->as<String>();
    if (!is_true(args[1]))
      runner::raise_primitive_error("assertion `" + arg2->value_get() +
				    "' failed");
    return void_class;
  }

  static rObject
  system_class_eval(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    rString arg1 = args[1]->as<String>();
    return
      execute_parsed(r, parser::parse(arg1->value_get()),
                     SYMBOL(eval),
                     "error executing command: " + arg1->value_get());
  }

  static rObject
  system_class_registerAtJob (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 3);
    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),
			    args[1], args[2], args[3]);
    return object::void_class;
  }

  static rObject
  system_class_scopeTag(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    const scheduler::rTag& scope_tag =
      dynamic_cast<runner::Interpreter&>(r).scope_tag();
    return new Tag(scope_tag);
  }

  static rObject
  system_class_searchFile (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    const rString& arg1 = args[1]->as<String>();

    UServer& s = r.lobby_get()->value_get().connection.server_get();
    try
    {
      return new String(s.find_file(arg1->value_get()));
    }
    catch (libport::file_library::Not_found&)
    {
      runner::raise_primitive_error("Unable to find file: " +
				    arg1->value_get());
      // Never reached
      assertion(false);
      return 0;
    }
  }

  static rObject
  system_class_loadFile(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    const rString& arg1 = args[1]->as<String>();

    const std::string& filename = arg1->value_get();

    if (!libport::path(filename).exists())
      runner::raise_primitive_error("No such file: " + filename);
    return
      execute_parsed(r, parser::parse_file(filename),
                     SYMBOL(loadFile),
		     "error loading file: " + filename);
  }

  static rObject
  system_class_currentRunner (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return r.as_task();
  }

  static rObject
  system_class_cycle (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(r.scheduler_get ().cycle_get ());
  }

  static rObject
  system_class_fresh (runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new String(libport::Symbol::fresh());
  }

  static rObject
  system_class_lobby (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return r.lobby_get();
  }

  static rObject
  system_class_nonInterruptible (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    r.non_interruptible_set (true);
    return void_class;
  }

  static rObject
  system_class_quit (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    r.lobby_get()->value_get().connection.close();
    return void_class;
  }

  static rObject
  system_class_spawn(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    rObject arg1 = args[1]->as<Code>();
    assert(arg1);

    runner::Interpreter* new_runner =
      new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),
			       rObject(arg1));
    new_runner->copy_tags (r);
    new_runner->time_shift_set (r.time_shift_get ());

    new_runner->start_job ();

    return object::void_class;
  }

  static rObject
  system_class_stats(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    Dictionary::value_type res;
    const scheduler::scheduler_stats_type& stats =
      r.scheduler_get().stats_get();
    // The space after "Symbol(" is mandatory to avoid triggering an error in
    // symbol generation code
#define ADDSTAT(Suffix, Function, Divisor)				\
    res[libport::Symbol( "cycles" # Suffix)] = new Float(stats.Function() / Divisor)
    ADDSTAT(, size, 1);
    ADDSTAT(Max, max, 1000.0);
    ADDSTAT(Mean, mean, 1000.0);
    ADDSTAT(Min, min, 1000.0);
    ADDSTAT(StdDev, standard_deviation, 1000.0);
    ADDSTAT(Variance, variance, 1000.0);
#undef ADDSTAT
    return new Dictionary(res);
  }

  // This should give a backtrace as an urbi object.
  static rObject
  system_class_backtrace(runner::Runner& r, objects_type args)
  {
    // FIXME: This method sucks a bit, because show_backtrace sucks a
    // bit, because our channeling/message-sending system sucks a lot.
    check_arg_count(args.size() - 1, 0);
    runner::Runner::backtrace_type bt = r.backtrace_get();
    bt.pop_back();
    foreach (const runner::Runner::frame_type& elt,
	     boost::make_iterator_range(boost::rbegin(bt),
					boost::rend(bt)))
      r.send_message("backtrace", elt.first + " (" + elt.second + ")");
    return void_class;
  }

  static rObject
  system_class_jobs(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    List::value_type res;
    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())
      res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());
    return new List(res);
  }

  static rObject
  system_class_aliveJobs(runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(scheduler::Job::alive_jobs());
  }

  static rObject
  system_class_breakpoint(runner::Runner&, objects_type)
  {
    return void_class;
  }

#define SERVER_SET_VAR(Function, Variable, Value)			\
  static rObject							\
  system_class_ ## Function (runner::Runner&, objects_type args)	\
  {									\
    check_arg_count(args.size() - 1, 0);                                \
    ::urbiserver->Variable = Value;					\
    return void_class;							\
  }

  SERVER_SET_VAR(debugoff, debugOutput, false)
  SERVER_SET_VAR(debugon, debugOutput, true)
  SERVER_SET_VAR(stopall, stopall, true)

#undef SERVER_SET_VAR

  static rObject system_getenv(rObject, const std::string& name)
  {
    char* res = getenv(name.c_str());
    return res ? new String(res) : 0;
  }

  static rObject system_setenv(runner::Runner& r, rObject,
                               const std::string& name, rObject value)
  {
    rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();
    setenv(name.c_str(), v->value_get().c_str(), 1);
    return v;
  }

  static rObject system_unsetenv(rObject, const std::string& name)
  {
    rObject res = system_getenv(0, name);
    unsetenv(name.c_str());
    return res;
  }

  static libport::InstanceTracker<Lobby>::set_type system_lobbies()
  {
    return Lobby::instances_get();
  }

  void
  system_class_initialize ()
  {
#define DECLARE(Name)                                                   \
    system_class->slot_set                                              \
      (SYMBOL(Name),                                                    \
       make_primitive(&system_##Name))                                  \

    DECLARE(getenv);
    DECLARE(lobbies);
    DECLARE(setenv);
    DECLARE(unsetenv);

#undef DECLARE

    /// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(system, Name)

    DECLARE(aliveJobs);
    DECLARE(assert_);
    DECLARE(backtrace);
    DECLARE(breakpoint);
    DECLARE(currentRunner);
    DECLARE(cycle);
    DECLARE(debugoff);
    DECLARE(debugon);
    DECLARE(eval);
    DECLARE(fresh);
    DECLARE(jobs);
    DECLARE(loadFile);
    DECLARE(lobby);
    DECLARE(nonInterruptible);
    DECLARE(quit);
    DECLARE(reboot);
    DECLARE(registerAtJob);
    DECLARE(scopeTag);
    DECLARE(searchFile);
    DECLARE(shiftedTime);
    DECLARE(stats);
    DECLARE(shutdown);
    DECLARE(sleep);
    DECLARE(spawn);
    DECLARE(stopall);
    DECLARE(time);
#undef DECLARE
  }

}; // namespace object
<commit_msg>Return the platform as "POSIX" or "WIN32".<commit_after>/**
 ** \file object/system-class.cc
 ** \brief Creation of the URBI object system.
 */

//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/cstdlib>

#include <memory>
#include <sstream>

#include <kernel/userver.hh>
#include <kernel/uconnection.hh>

#include <object/code.hh>
#include <object/cxx-primitive.hh>
#include <object/dictionary.hh>
#include <object/float.hh>
#include <object/global.hh>
#include <object/lobby.hh>
#include <object/list.hh>
#include <object/system.hh>
#include <object/tag.hh>
#include <object/task.hh>
#include <parser/transform.hh>
#include <runner/at-handler.hh>
#include <runner/call.hh>
#include <runner/interpreter.hh>
#include <runner/raise.hh>
#include <runner/runner.hh>

#include <ast/nary.hh>
#include <ast/routine.hh>

namespace object
{

  rObject
  execute_parsed(runner::Runner& r,
                 parser::parse_result_type p,
                 libport::Symbol fun, std::string e)
  {
    runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);

    // Report potential errors
    {
      ast::rNary errs = new ast::Nary();
      p->process_errors(*errs);
      run(errs.get());
    }

    ast::rConstAst ast = parser::transform(p->ast_get());
    if (!ast)
      runner::raise_primitive_error(e);

    runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);
    // So that it will resist to the call to yield_until_terminated,
    // and will be reclaimed at the end of the scope.
    scheduler::rJob job = sub;
    libport::Finally finally;
    r.register_child(sub, finally);
    sub->start_job();
    try
    {
      run.yield_until_terminated(*job);
    }
    catch (const scheduler::ChildException& ce)
    {
      // Kill the sub-job and propagate.
      scheduler::rethrow(ce.child_exception_get());
    }
    return sub->result_get();
  }

  rObject system_class;

  /*--------------------.
  | System primitives.  |
  `--------------------*/

#define SERVER_FUNCTION(Function)					\
  static rObject							\
  system_class_ ## Function (runner::Runner&, objects_type args)	\
  {									\
    check_arg_count(args.size() - 1, 0);                                \
    ::urbiserver->Function();						\
    return void_class;							\
  }

  SERVER_FUNCTION(reboot)
  SERVER_FUNCTION(shutdown)

#undef SERVER_FUNCTION

  static rObject
  system_class_sleep (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);

    type_check(args[1], Float::proto);

    rFloat arg1 = args[1]->as<Float>();
    libport::utime_t deadline;
    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())
      deadline = std::numeric_limits<libport::utime_t>::max();
    else
      deadline = r.scheduler_get().get_time() +
	static_cast<libport::utime_t>(arg1->value_get() * 1000000.0);
    r.yield_until (deadline);
    return void_class;
  }

  static rObject
  system_class_time(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(r.scheduler_get().get_time() / 1000000.0);
  }

  static rObject
  system_class_shiftedTime(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float((r.scheduler_get().get_time() -
			  r.time_shift_get()) / 1000000.0);
  }

  static rObject
  system_class_assert_(runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 2);
    type_check(args[2], String::proto);
    rString arg2 = args[2]->as<String>();
    if (!is_true(args[1]))
      runner::raise_primitive_error("assertion `" + arg2->value_get() +
				    "' failed");
    return void_class;
  }

  static rObject
  system_class_eval(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    rString arg1 = args[1]->as<String>();
    return
      execute_parsed(r, parser::parse(arg1->value_get()),
                     SYMBOL(eval),
                     "error executing command: " + arg1->value_get());
  }

  static rObject
  system_class_registerAtJob (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 3);
    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),
			    args[1], args[2], args[3]);
    return object::void_class;
  }

  static rObject
  system_class_scopeTag(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    const scheduler::rTag& scope_tag =
      dynamic_cast<runner::Interpreter&>(r).scope_tag();
    return new Tag(scope_tag);
  }

  static rObject
  system_class_searchFile (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    const rString& arg1 = args[1]->as<String>();

    UServer& s = r.lobby_get()->value_get().connection.server_get();
    try
    {
      return new String(s.find_file(arg1->value_get()));
    }
    catch (libport::file_library::Not_found&)
    {
      runner::raise_primitive_error("Unable to find file: " +
				    arg1->value_get());
      // Never reached
      assertion(false);
      return 0;
    }
  }

  static rObject
  system_class_loadFile(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], String::proto);
    const rString& arg1 = args[1]->as<String>();

    const std::string& filename = arg1->value_get();

    if (!libport::path(filename).exists())
      runner::raise_primitive_error("No such file: " + filename);
    return
      execute_parsed(r, parser::parse_file(filename),
                     SYMBOL(loadFile),
		     "error loading file: " + filename);
  }

  static rObject
  system_class_currentRunner (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return r.as_task();
  }

  static rObject
  system_class_cycle (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(r.scheduler_get ().cycle_get ());
  }

  static rObject
  system_class_fresh (runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new String(libport::Symbol::fresh());
  }

  static rObject
  system_class_lobby (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return r.lobby_get();
  }

  static rObject
  system_class_nonInterruptible (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    r.non_interruptible_set (true);
    return void_class;
  }

  static rObject
  system_class_quit (runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    r.lobby_get()->value_get().connection.close();
    return void_class;
  }

  static rObject
  system_class_spawn(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 1);
    rObject arg1 = args[1]->as<Code>();
    assert(arg1);

    runner::Interpreter* new_runner =
      new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),
			       rObject(arg1));
    new_runner->copy_tags (r);
    new_runner->time_shift_set (r.time_shift_get ());

    new_runner->start_job ();

    return object::void_class;
  }

  static rObject
  system_class_stats(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    Dictionary::value_type res;
    const scheduler::scheduler_stats_type& stats =
      r.scheduler_get().stats_get();
    // The space after "Symbol(" is mandatory to avoid triggering an error in
    // symbol generation code
#define ADDSTAT(Suffix, Function, Divisor)				\
    res[libport::Symbol( "cycles" # Suffix)] = new Float(stats.Function() / Divisor)
    ADDSTAT(, size, 1);
    ADDSTAT(Max, max, 1000.0);
    ADDSTAT(Mean, mean, 1000.0);
    ADDSTAT(Min, min, 1000.0);
    ADDSTAT(StdDev, standard_deviation, 1000.0);
    ADDSTAT(Variance, variance, 1000.0);
#undef ADDSTAT
    return new Dictionary(res);
  }

  static rObject
  system_class_platform(runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
#ifdef WIN32
    return to_urbi(SYMBOL(WIN32));
#else
    return to_urbi(SYMBOL(POSIX));
#endif
  }

  // This should give a backtrace as an urbi object.
  static rObject
  system_class_backtrace(runner::Runner& r, objects_type args)
  {
    // FIXME: This method sucks a bit, because show_backtrace sucks a
    // bit, because our channeling/message-sending system sucks a lot.
    check_arg_count(args.size() - 1, 0);
    runner::Runner::backtrace_type bt = r.backtrace_get();
    bt.pop_back();
    foreach (const runner::Runner::frame_type& elt,
	     boost::make_iterator_range(boost::rbegin(bt),
					boost::rend(bt)))
      r.send_message("backtrace", elt.first + " (" + elt.second + ")");
    return void_class;
  }

  static rObject
  system_class_jobs(runner::Runner& r, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    List::value_type res;
    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())
      res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());
    return new List(res);
  }

  static rObject
  system_class_aliveJobs(runner::Runner&, objects_type args)
  {
    check_arg_count(args.size() - 1, 0);
    return new Float(scheduler::Job::alive_jobs());
  }

  static rObject
  system_class_breakpoint(runner::Runner&, objects_type)
  {
    return void_class;
  }

#define SERVER_SET_VAR(Function, Variable, Value)			\
  static rObject							\
  system_class_ ## Function (runner::Runner&, objects_type args)	\
  {									\
    check_arg_count(args.size() - 1, 0);                                \
    ::urbiserver->Variable = Value;					\
    return void_class;							\
  }

  SERVER_SET_VAR(debugoff, debugOutput, false)
  SERVER_SET_VAR(debugon, debugOutput, true)
  SERVER_SET_VAR(stopall, stopall, true)

#undef SERVER_SET_VAR

  static rObject system_getenv(rObject, const std::string& name)
  {
    char* res = getenv(name.c_str());
    return res ? new String(res) : 0;
  }

  static rObject system_setenv(runner::Runner& r, rObject,
                               const std::string& name, rObject value)
  {
    rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();
    setenv(name.c_str(), v->value_get().c_str(), 1);
    return v;
  }

  static rObject system_unsetenv(rObject, const std::string& name)
  {
    rObject res = system_getenv(0, name);
    unsetenv(name.c_str());
    return res;
  }

  static libport::InstanceTracker<Lobby>::set_type system_lobbies()
  {
    return Lobby::instances_get();
  }

  void
  system_class_initialize ()
  {
#define DECLARE(Name)                                                   \
    system_class->slot_set                                              \
      (SYMBOL(Name),                                                    \
       make_primitive(&system_##Name))                                  \

    DECLARE(getenv);
    DECLARE(lobbies);
    DECLARE(setenv);
    DECLARE(unsetenv);

#undef DECLARE

    /// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(system, Name)

    DECLARE(aliveJobs);
    DECLARE(assert_);
    DECLARE(backtrace);
    DECLARE(breakpoint);
    DECLARE(currentRunner);
    DECLARE(cycle);
    DECLARE(debugoff);
    DECLARE(debugon);
    DECLARE(eval);
    DECLARE(fresh);
    DECLARE(jobs);
    DECLARE(loadFile);
    DECLARE(lobby);
    DECLARE(nonInterruptible);
    DECLARE(quit);
    DECLARE(reboot);
    DECLARE(registerAtJob);
    DECLARE(scopeTag);
    DECLARE(searchFile);
    DECLARE(shiftedTime);
    DECLARE(stats);
    DECLARE(shutdown);
    DECLARE(sleep);
    DECLARE(spawn);
    DECLARE(stopall);
    DECLARE(platform);
    DECLARE(time);
#undef DECLARE
  }

}; // namespace object
<|endoftext|>


<commit_before><commit_msg>Revert "fix for fdo#47907"<commit_after><|endoftext|>


<commit_before>//===- DiagnosticEngine.h - Diagnostic Display Engine -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines the DiagnosticEngine class, which manages any diagnostics
//  emitted by Swift.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Module.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;

struct StoredDiagnosticInfo {
  /// \brief The kind of diagnostic we're dealing with.
  DiagnosticKind Kind;

  // FIXME: Category

  /// \brief Text associated with the diagnostic
  const char *Text;
};

static StoredDiagnosticInfo StoredDiagnosticInfos[] = {
#define ERROR(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Error, Text },
#define WARNING(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Warning, Text },
#define NOTE(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Note, Text },
#include "swift/AST/Diagnostics.def"
  { DiagnosticKind::Error, "<not a diagnostic>" }
};

void InFlightDiagnostic::flush() {
  if (!IsActive)
    return;

  IsActive = false;
  if (Engine)
    Engine->flushActiveDiagnostic();
}

/// \brief Skip forward to one of the given delimiters.
///
/// \param Text The text to search through, which will be updated to point
/// just after the delimiter.
///
/// \param Delim1 The first character delimiter to search for.
///
/// \param Delim2 The second character delimiter to search for.
///
/// \returns The string leading up to the delimiter, or the empty string
/// if no delimiter is found.
static StringRef
skipToDelimiter(StringRef &Text, char Delim1, char Delim2 = 0) {
  unsigned Depth = 0;

  unsigned I = 0;
  for (unsigned N = Text.size(); I != N; ++I) {
    if (Depth == 0 && Text[I] == '{') {
      ++Depth;
      continue;
    }
    if (Depth > 0 && Text[I] == '}') {
      --Depth;
      continue;
    }

    if (Text[I] == Delim1 || Text[I] == Delim2)
      break;
  }

  assert(Depth == 0 && "Unbalanced {} set in diagnostic text");
  StringRef Result = Text.substr(0, I);
  Text = Text.substr(I + 1);
  return Result;
}

static void formatDiagnosticText(StringRef InText,
                                 ArrayRef<DiagnosticArgument> Args,
                                 llvm::raw_ostream &Out);

/// \brief Format a selection argument and write it to the given stream.
static void formatSelectionArgument(StringRef ModifierArguments,
                                    ArrayRef<DiagnosticArgument> Args,
                                    unsigned SelectedIndex,
                                    llvm::raw_ostream &Out) {
  do {
    StringRef Text = skipToDelimiter(ModifierArguments, '|');
    if (SelectedIndex == 0) {
      formatDiagnosticText(Text, Args, Out);
      break;
    }
    --SelectedIndex;
  } while (true);

}

/// \brief Format a single diagnostic argument and write it to the given
/// stream.
static void formatDiagnosticArgument(StringRef Modifier,
                                     StringRef ModifierArguments,
                                     ArrayRef<DiagnosticArgument> Args,
                                     unsigned ArgIndex,
                                     llvm::raw_ostream &Out) {
  const DiagnosticArgument &Arg = Args[ArgIndex];
  switch (Arg.getKind()) {
  case DiagnosticArgumentKind::Integer:
    if (Modifier == "select") {
      assert(Arg.getAsInteger() >= 0 && "Negative selection index");
      formatSelectionArgument(ModifierArguments, Args, Arg.getAsInteger(),
                              Out);
    } else {
      assert(Modifier.empty() && "Improper modifier for integer argument");
      Out << Arg.getAsInteger();
    }
    break;

  case DiagnosticArgumentKind::Unsigned:
    if (Modifier == "select") {
      formatSelectionArgument(ModifierArguments, Args, Arg.getAsUnsigned(),
                              Out);
    } else {
      assert(Modifier.empty() && "Improper modifier for unsigned argument");
      Out << Arg.getAsUnsigned();
    }
    break;

  case DiagnosticArgumentKind::String:
    assert(Modifier.empty() && "Improper modifier for string argument");
    Out << Arg.getAsString();
    break;

  case DiagnosticArgumentKind::Identifier:
    assert(Modifier.empty() && "Improper modifier for identifier argument");
    Out << '\'' << Arg.getAsIdentifier() << '\'';
    break;
  case DiagnosticArgumentKind::Type:
    assert(Modifier.empty() && "Improper modifier for Type argument");
    Out << '\'' << Arg.getAsType() << '\'';
    break;
  case DiagnosticArgumentKind::TypeRepr:
    assert(Modifier.empty() && "Improper modifier for TypeRepr argument");
    Out << '\'' << Arg.getAsTypeRepr() << '\'';
    break;
  case DiagnosticArgumentKind::PatternKind:
    assert(Modifier.empty() && "Improper modifier for PatternKind argument");
    Out << Arg.getAsPatternKind();
  }
}

/// \brief Format the given diagnostic text and place the result in the given
/// buffer.
static void formatDiagnosticText(StringRef InText,
                                 ArrayRef<DiagnosticArgument> Args,
                                 llvm::raw_ostream &Out) {
  while (!InText.empty()) {
    size_t Percent = InText.find('%');
    if (Percent == StringRef::npos) {
      // Write the rest of the string; we're done.
      Out.write(InText.data(), InText.size());
      break;
    }

    // Write the string up to (but not including) the %, then drop that text
    // (including the %).
    Out.write(InText.data(), Percent);
    InText = InText.substr(Percent + 1);

    // '%%' -> '%'.
    if (InText[0] == '%') {
      Out.write('%');
      InText = InText.substr(1);
      continue;
    }

    // Parse an optional modifier.
    StringRef Modifier;
    {
      unsigned Length = 0;
      while (isalpha(InText[Length]))
        ++Length;
      Modifier = InText.substr(0, Length);
      InText = InText.substr(Length);
    }

    // Parse the optional argument list for a modifier, which is brace-enclosed.
    StringRef ModifierArguments;
    if (InText[0] == '{') {
      InText = InText.substr(1);
      ModifierArguments = skipToDelimiter(InText, '}');
    }

    // Find the digit sequence.
    unsigned Length = 0;
    for (size_t N = InText.size(); Length != N; ++Length) {
      if (!isdigit(InText[Length]))
        break;
    }

    // Parse the digit sequence into an argument index.
    unsigned ArgIndex;
    bool Result = InText.substr(0, Length).getAsInteger(10, ArgIndex);
    assert(!Result && "Unparseable argument index value?");
    (void)Result;
    assert(ArgIndex < Args.size() && "Out-of-range argument index");
    InText = InText.substr(Length);

    // Convert the argument to a string.
    formatDiagnosticArgument(Modifier, ModifierArguments, Args, ArgIndex, Out);
  }
}

void DiagnosticEngine::flushActiveDiagnostic() {
  assert(ActiveDiagnostic && "No active diagnostic to flush");
  const StoredDiagnosticInfo &StoredInfo
    = StoredDiagnosticInfos[(unsigned)ActiveDiagnostic->getID()];

  // Check whether this is an error.
  switch (StoredInfo.Kind) {
  case DiagnosticKind::Error:
    HadAnyError = true;
    break;

  case DiagnosticKind::Note:
  case DiagnosticKind::Warning:
    break;
  }

  // Figure out the source location.
  SourceLoc loc = ActiveDiagnosticLoc;
  if (loc.isInvalid() && ActiveDiagnosticDecl) {
    // If a declaration was provided instead of a location, and that declaration
    // has a location we can point to, use that location.
    if (!ActiveDiagnosticDecl->hasClangNode() &&
        ActiveDiagnosticDecl->getLoc().isValid()) {
      loc = ActiveDiagnosticDecl->getLoc();
    } else {
      // There is no location we can point to. Pretty-print the declaration
      // so we can point to it.
      SourceLoc ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];
      if (ppLoc.isInvalid()) {
        SmallVector<std::pair<Decl *, uint64_t>, 8> entries;
        llvm::SmallString<128> buffer;
        llvm::SmallString<128> bufferName;
        {
          // Figure out which declaration to print. It's the top-most
          // declaration (not a module).
          Decl *ppDecl = ActiveDiagnosticDecl;
          auto dc = ActiveDiagnosticDecl->getDeclContext();
          while (!dc->isModuleContext()) {
            switch (dc->getContextKind()) {
            case DeclContextKind::BuiltinModule:
            case DeclContextKind::ClangModule:
            case DeclContextKind::SerializedModule:
            case DeclContextKind::TranslationUnit:
            case DeclContextKind::TopLevelCodeDecl:
              llvm_unreachable("Not in a module context!");
              break;

            case DeclContextKind::ExtensionDecl:
              ppDecl = cast<ExtensionDecl>(dc);
              break;

            case DeclContextKind::NominalTypeDecl:
              ppDecl = cast<NominalTypeDecl>(dc);
              break;

            case DeclContextKind::CapturingExpr:
            case DeclContextKind::ConstructorDecl:
            case DeclContextKind::DestructorDecl:
              break;
            }

            dc = dc->getParent();
          }

          // Build the module name path (in reverse), which we use to
          // build the name of the buffer.
          SmallVector<StringRef, 4> nameComponents;
          while (dc) {
            nameComponents.push_back(cast<Module>(dc)->Name.str());
            dc = dc->getParent();
          }

          for (unsigned i = nameComponents.size(); i; --i) {
            bufferName += nameComponents[i-1];
            bufferName += '.';
          }

          if (auto value = dyn_cast<ValueDecl>(ppDecl)) {
            bufferName += value->getName().str();
          } else if (auto ext = dyn_cast<ExtensionDecl>(ppDecl)) {
            bufferName += ext->getExtendedType().getString();
          }

          // Pretty-print the declaration we've picked.
          llvm::raw_svector_ostream out(buffer);
          ppDecl->print(out, PrintOptions::printEverything(), &entries);
        }

        // Build a buffer with the pretty-printed declaration.
        auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(buffer,
                                                              bufferName);
        SourceMgr->AddNewSourceBuffer(memBuffer, llvm::SMLoc());

        // Go through all of the pretty-printed entries and record their
        // locations.
        for (auto entry : entries) {
          PrettyPrintedDeclarations[entry.first]
            = SourceLoc(llvm::SMLoc::getFromPointer(memBuffer->getBufferStart()
                                                    + entry.second));
        }

        // Grab the pretty-printed location.
        ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];
      }

      loc = ppLoc;
    }
  }

  // Actually substitute the diagnostic arguments into the diagnostic text.
  llvm::SmallString<256> Text;
  {
    llvm::raw_svector_ostream Out(Text);
    formatDiagnosticText(StoredInfo.Text, ActiveDiagnostic->getArgs(), Out);
  }

  // Pass the diagnostic off to the consumer.
  DiagnosticInfo Info;
  Info.Ranges = ActiveDiagnostic->getRanges();
  Info.FixIts = ActiveDiagnostic->getFixIts();
  for (auto &Consumer : Consumers)
    Consumer->handleDiagnostic(SourceMgr, loc, StoredInfo.Kind, Text, Info);

  // Reset the active diagnostic.
  ActiveDiagnostic.reset();
}
<commit_msg>Omit bodies from module-scope decls in pretty-printed synthetic sources.<commit_after>//===- DiagnosticEngine.h - Diagnostic Display Engine -----------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines the DiagnosticEngine class, which manages any diagnostics
//  emitted by Swift.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Module.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;

struct StoredDiagnosticInfo {
  /// \brief The kind of diagnostic we're dealing with.
  DiagnosticKind Kind;

  // FIXME: Category

  /// \brief Text associated with the diagnostic
  const char *Text;
};

static StoredDiagnosticInfo StoredDiagnosticInfos[] = {
#define ERROR(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Error, Text },
#define WARNING(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Warning, Text },
#define NOTE(ID,Category,Options,Text,Signature) \
  { DiagnosticKind::Note, Text },
#include "swift/AST/Diagnostics.def"
  { DiagnosticKind::Error, "<not a diagnostic>" }
};

void InFlightDiagnostic::flush() {
  if (!IsActive)
    return;

  IsActive = false;
  if (Engine)
    Engine->flushActiveDiagnostic();
}

/// \brief Skip forward to one of the given delimiters.
///
/// \param Text The text to search through, which will be updated to point
/// just after the delimiter.
///
/// \param Delim1 The first character delimiter to search for.
///
/// \param Delim2 The second character delimiter to search for.
///
/// \returns The string leading up to the delimiter, or the empty string
/// if no delimiter is found.
static StringRef
skipToDelimiter(StringRef &Text, char Delim1, char Delim2 = 0) {
  unsigned Depth = 0;

  unsigned I = 0;
  for (unsigned N = Text.size(); I != N; ++I) {
    if (Depth == 0 && Text[I] == '{') {
      ++Depth;
      continue;
    }
    if (Depth > 0 && Text[I] == '}') {
      --Depth;
      continue;
    }

    if (Text[I] == Delim1 || Text[I] == Delim2)
      break;
  }

  assert(Depth == 0 && "Unbalanced {} set in diagnostic text");
  StringRef Result = Text.substr(0, I);
  Text = Text.substr(I + 1);
  return Result;
}

static void formatDiagnosticText(StringRef InText,
                                 ArrayRef<DiagnosticArgument> Args,
                                 llvm::raw_ostream &Out);

/// \brief Format a selection argument and write it to the given stream.
static void formatSelectionArgument(StringRef ModifierArguments,
                                    ArrayRef<DiagnosticArgument> Args,
                                    unsigned SelectedIndex,
                                    llvm::raw_ostream &Out) {
  do {
    StringRef Text = skipToDelimiter(ModifierArguments, '|');
    if (SelectedIndex == 0) {
      formatDiagnosticText(Text, Args, Out);
      break;
    }
    --SelectedIndex;
  } while (true);

}

/// \brief Format a single diagnostic argument and write it to the given
/// stream.
static void formatDiagnosticArgument(StringRef Modifier,
                                     StringRef ModifierArguments,
                                     ArrayRef<DiagnosticArgument> Args,
                                     unsigned ArgIndex,
                                     llvm::raw_ostream &Out) {
  const DiagnosticArgument &Arg = Args[ArgIndex];
  switch (Arg.getKind()) {
  case DiagnosticArgumentKind::Integer:
    if (Modifier == "select") {
      assert(Arg.getAsInteger() >= 0 && "Negative selection index");
      formatSelectionArgument(ModifierArguments, Args, Arg.getAsInteger(),
                              Out);
    } else {
      assert(Modifier.empty() && "Improper modifier for integer argument");
      Out << Arg.getAsInteger();
    }
    break;

  case DiagnosticArgumentKind::Unsigned:
    if (Modifier == "select") {
      formatSelectionArgument(ModifierArguments, Args, Arg.getAsUnsigned(),
                              Out);
    } else {
      assert(Modifier.empty() && "Improper modifier for unsigned argument");
      Out << Arg.getAsUnsigned();
    }
    break;

  case DiagnosticArgumentKind::String:
    assert(Modifier.empty() && "Improper modifier for string argument");
    Out << Arg.getAsString();
    break;

  case DiagnosticArgumentKind::Identifier:
    assert(Modifier.empty() && "Improper modifier for identifier argument");
    Out << '\'' << Arg.getAsIdentifier() << '\'';
    break;
  case DiagnosticArgumentKind::Type:
    assert(Modifier.empty() && "Improper modifier for Type argument");
    Out << '\'' << Arg.getAsType() << '\'';
    break;
  case DiagnosticArgumentKind::TypeRepr:
    assert(Modifier.empty() && "Improper modifier for TypeRepr argument");
    Out << '\'' << Arg.getAsTypeRepr() << '\'';
    break;
  case DiagnosticArgumentKind::PatternKind:
    assert(Modifier.empty() && "Improper modifier for PatternKind argument");
    Out << Arg.getAsPatternKind();
  }
}

/// \brief Format the given diagnostic text and place the result in the given
/// buffer.
static void formatDiagnosticText(StringRef InText,
                                 ArrayRef<DiagnosticArgument> Args,
                                 llvm::raw_ostream &Out) {
  while (!InText.empty()) {
    size_t Percent = InText.find('%');
    if (Percent == StringRef::npos) {
      // Write the rest of the string; we're done.
      Out.write(InText.data(), InText.size());
      break;
    }

    // Write the string up to (but not including) the %, then drop that text
    // (including the %).
    Out.write(InText.data(), Percent);
    InText = InText.substr(Percent + 1);

    // '%%' -> '%'.
    if (InText[0] == '%') {
      Out.write('%');
      InText = InText.substr(1);
      continue;
    }

    // Parse an optional modifier.
    StringRef Modifier;
    {
      unsigned Length = 0;
      while (isalpha(InText[Length]))
        ++Length;
      Modifier = InText.substr(0, Length);
      InText = InText.substr(Length);
    }

    // Parse the optional argument list for a modifier, which is brace-enclosed.
    StringRef ModifierArguments;
    if (InText[0] == '{') {
      InText = InText.substr(1);
      ModifierArguments = skipToDelimiter(InText, '}');
    }

    // Find the digit sequence.
    unsigned Length = 0;
    for (size_t N = InText.size(); Length != N; ++Length) {
      if (!isdigit(InText[Length]))
        break;
    }

    // Parse the digit sequence into an argument index.
    unsigned ArgIndex;
    bool Result = InText.substr(0, Length).getAsInteger(10, ArgIndex);
    assert(!Result && "Unparseable argument index value?");
    (void)Result;
    assert(ArgIndex < Args.size() && "Out-of-range argument index");
    InText = InText.substr(Length);

    // Convert the argument to a string.
    formatDiagnosticArgument(Modifier, ModifierArguments, Args, ArgIndex, Out);
  }
}

void DiagnosticEngine::flushActiveDiagnostic() {
  assert(ActiveDiagnostic && "No active diagnostic to flush");
  const StoredDiagnosticInfo &StoredInfo
    = StoredDiagnosticInfos[(unsigned)ActiveDiagnostic->getID()];

  // Check whether this is an error.
  switch (StoredInfo.Kind) {
  case DiagnosticKind::Error:
    HadAnyError = true;
    break;

  case DiagnosticKind::Note:
  case DiagnosticKind::Warning:
    break;
  }

  // Figure out the source location.
  SourceLoc loc = ActiveDiagnosticLoc;
  if (loc.isInvalid() && ActiveDiagnosticDecl) {
    // If a declaration was provided instead of a location, and that declaration
    // has a location we can point to, use that location.
    if (!ActiveDiagnosticDecl->hasClangNode() &&
        ActiveDiagnosticDecl->getLoc().isValid()) {
      loc = ActiveDiagnosticDecl->getLoc();
    } else {
      // There is no location we can point to. Pretty-print the declaration
      // so we can point to it.
      SourceLoc ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];
      if (ppLoc.isInvalid()) {
        SmallVector<std::pair<Decl *, uint64_t>, 8> entries;
        llvm::SmallString<128> buffer;
        llvm::SmallString<128> bufferName;
        {
          // Figure out which declaration to print. It's the top-most
          // declaration (not a module).
          Decl *ppDecl = ActiveDiagnosticDecl;
          auto dc = ActiveDiagnosticDecl->getDeclContext();
          while (!dc->isModuleContext()) {
            switch (dc->getContextKind()) {
            case DeclContextKind::BuiltinModule:
            case DeclContextKind::ClangModule:
            case DeclContextKind::SerializedModule:
            case DeclContextKind::TranslationUnit:
            case DeclContextKind::TopLevelCodeDecl:
              llvm_unreachable("Not in a module context!");
              break;

            case DeclContextKind::ExtensionDecl:
              ppDecl = cast<ExtensionDecl>(dc);
              break;

            case DeclContextKind::NominalTypeDecl:
              ppDecl = cast<NominalTypeDecl>(dc);
              break;

            case DeclContextKind::CapturingExpr:
            case DeclContextKind::ConstructorDecl:
            case DeclContextKind::DestructorDecl:
              break;
            }

            dc = dc->getParent();
          }

          // Build the module name path (in reverse), which we use to
          // build the name of the buffer.
          SmallVector<StringRef, 4> nameComponents;
          while (dc) {
            nameComponents.push_back(cast<Module>(dc)->Name.str());
            dc = dc->getParent();
          }

          for (unsigned i = nameComponents.size(); i; --i) {
            bufferName += nameComponents[i-1];
            bufferName += '.';
          }

          if (auto value = dyn_cast<ValueDecl>(ppDecl)) {
            bufferName += value->getName().str();
          } else if (auto ext = dyn_cast<ExtensionDecl>(ppDecl)) {
            bufferName += ext->getExtendedType().getString();
          }

          // Don't print bodies if we're looking at a top-level decl.
          PrintOptions options;
          if (ActiveDiagnosticDecl->getDeclContext()->isModuleContext())
            options = PrintOptions();
          else
            options = PrintOptions::printEverything();

          // Pretty-print the declaration we've picked.
          llvm::raw_svector_ostream out(buffer);
          ppDecl->print(out, options, &entries);
        }

        // Build a buffer with the pretty-printed declaration.
        auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(buffer,
                                                              bufferName);
        SourceMgr->AddNewSourceBuffer(memBuffer, llvm::SMLoc());

        // Go through all of the pretty-printed entries and record their
        // locations.
        for (auto entry : entries) {
          PrettyPrintedDeclarations[entry.first]
            = SourceLoc(llvm::SMLoc::getFromPointer(memBuffer->getBufferStart()
                                                    + entry.second));
        }

        // Grab the pretty-printed location.
        ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];
      }

      loc = ppLoc;
    }
  }

  // Actually substitute the diagnostic arguments into the diagnostic text.
  llvm::SmallString<256> Text;
  {
    llvm::raw_svector_ostream Out(Text);
    formatDiagnosticText(StoredInfo.Text, ActiveDiagnostic->getArgs(), Out);
  }

  // Pass the diagnostic off to the consumer.
  DiagnosticInfo Info;
  Info.Ranges = ActiveDiagnostic->getRanges();
  Info.FixIts = ActiveDiagnostic->getFixIts();
  for (auto &Consumer : Consumers)
    Consumer->handleDiagnostic(SourceMgr, loc, StoredInfo.Kind, Text, Info);

  // Reset the active diagnostic.
  ActiveDiagnostic.reset();
}
<|endoftext|>


<commit_before>#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h>
#include <NeuralNetwork/NeuralLayer/ConvolutionLayer.h>
#include <NeuralNetwork/NeuralLayer/NeuralLayer.h>
#include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h>
#include <NeuralNetwork/Neuron/Neuron.h>
#include <NeuralNetwork/Perceptron/Perceptron.h>
//#include <NeuralNetwork/NeuralLayer/OpenCLNeuralLayer.h>
#include <NeuralNetwork/Config.h>

#include <Utilities/MPL/Tuple.h>

#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#include <boost/filesystem.hpp>
#undef BOOST_SYSTEM_NO_DEPRECATED
#endif

#define png_infopp_NULL (png_infopp) NULL
#define int_p_NULL (int*)NULL

#if defined(NN_CC_MSVC)
#pragma warning(push)
// This function or variable may be unsafe
#pragma warning(disable : 4996)
#endif

#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/channel.hpp>
#include <boost/gil/extension/dynamic_image/any_image.hpp>
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
#include <boost/gil/extension/io/dynamic_io.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <boost/gil/gil_all.hpp>
#include <boost/gil/image.hpp>

#include "gil/extension/numeric/sampler.hpp"
#include "gil/extension/numeric/resample.hpp"

#include <cereal/archives/xml.hpp>
#include <cereal/types/array.hpp>
#include <cereal/types/tuple.hpp>
#include <cereal/types/vector.hpp>

#if defined(NN_CC_MSVC)
#pragma warning(pop)
#endif

#include "Var.h"

#include <tuple>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>

typedef long double VarType;

namespace {
    using namespace boost::gil;
    using namespace boost::gil::detail;
    const std::string alphabet("0123456789");
    constexpr std::size_t width = 49;
    constexpr std::size_t height = 67;
    constexpr std::size_t inputsNumber = width * height;
    constexpr std::size_t margin = 15;
    constexpr std::size_t stride = 10;
} // namespace

using ConvolutionGrid =
 typename nn::ConvolutionGrid< width, height, stride, margin >::define;

using Perceptron =
 nn::Perceptron< VarType,
                 nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::SigmoidFunction, inputsNumber, ConvolutionGrid >,
                 nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >;

using Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >;

template< typename Out >
struct halfdiff_cast_channels {
    template< typename T >
    Out operator()(const T& in1, const T& in2) const {
        return Out((in1 - in2) / 2);
    }
};

template< typename SrcView, typename DstView >
void convert_color(const SrcView& src, const DstView& dst) {
    typedef typename channel_type< DstView >::type d_channel_t;
    typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t;
    typedef pixel< channel_t, gray_layout_t > gray_pixel_t;

    copy_pixels(color_converted_view< gray_pixel_t >(src), dst);
}

template< typename Iterator >
void readImage(std::string fileName, Iterator out) {
    using namespace boost::gil;
    using namespace nn;
    using namespace nn::bp;

    rgb8_image_t srcImg;
    png_read_image(fileName.c_str(), srcImg);

    gray8_image_t dstImg(srcImg.dimensions());
    gray8_pixel_t white(255);
    fill_pixels(view(dstImg), white);

    gray8_image_t grayImage(srcImg.dimensions());
    convert_color(view(srcImg), view(grayImage));
    auto grayView = view(grayImage);

    gray8_image_t scaledImage(width, height);
    resize_view(grayView, view(scaledImage), bilinear_sampler());
    auto srcView = view(scaledImage);

    for(int y = 0; y < srcView.height(); ++y) {
        gray8c_view_t::x_iterator src_it(srcView.row_begin(y));
        for(int x = 0; x < srcView.width(); ++x) {
            *out = src_it[x] < 130 ? 1.f : -1.f; // 255.f;
            out++;
        }
    }
}

Perceptron readPerceptron(std::string fileName) {
    Perceptron perceptron;
    if(boost::filesystem::exists(fileName.c_str())) {
        std::ifstream file(fileName);
        if(file.good()) {
            Perceptron::Memento memento;
            cereal::XMLInputArchive ia(file);
            ia >> memento;

            perceptron.setMemento(memento);
        } else {
            throw std::logic_error("Invalid perceptron file name");
        }
    }

    return perceptron;
}

void recognize(std::string perceptron, std::string image) {
    try {
        std::array< VarType, inputsNumber > inputs = {0};
        readImage(image, inputs.begin());
        std::vector< VarType > result(alphabet.length(), VarType(0.f));
        readPerceptron(perceptron)
         .calculate(inputs.begin(), inputs.end(), result.begin());
        for(unsigned int i = 0; i < result.size(); i++) {
            std::cout << "Symbol: " << alphabet[i] << " " << result[i] << std::endl;
        }
    } catch(const std::exception& e) {
        std::cout << e.what() << std::endl;
    } catch(...) {
        std::cout << "Unknown error" << std::endl;
    }
}

template< typename Perc >
void save(const Perc& perc, std::string name) {
    typename Perc::Memento memento = perc.getMemento();
    std::ofstream strm(name);
    cereal::XMLOutputArchive oa(strm);
    oa << memento;
    strm.flush();
}

void calculateWeights(std::string imagesPath) {
    using namespace boost::filesystem;
    path directory(imagesPath);
    directory_iterator end_iter;

    std::vector< std::string > files;
    if(exists(directory) && is_directory(directory)) {
        for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) {
            if(is_regular_file(dir_iter->status())) {
                files.push_back(dir_iter->path().string());
            }
        }
    }

    std::cout << "Perceptron calculation started" << std::endl;
    static Perceptron tmp = readPerceptron("perceptron.xml");
    static Algo algorithm(0.003f);
    algorithm.setMemento(tmp.getMemento());

    std::vector< Algo::Prototype > prototypes;
    for(auto image : files) {
        if(!boost::filesystem::is_directory(image)) {
            try {
                Algo::Prototype proto;
                readImage(image, std::get< 0 >(proto).begin());
                std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f);
                char ch = path(image).filename().string()[0];
                size_t pos = alphabet.find(ch);
                std::get< 1 >(proto)[pos] = 1.0f;
                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    auto errorFunc = [](unsigned int epoch, VarType error) {
        // if(epoch % 100 == 0) {
        std::cout << "Epoch:" << epoch << " error:" << error << std::endl;
        // }

        return error > 0.001f;
    };

    static Perceptron perceptron =
     algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc);

    save(perceptron, "perceptron.xml");
}

int main(int argc, char** argv) {
    int result = -1;
    if(argc == 3) {
        recognize(argv[1], argv[2]);
        result = 0;
    } else if(argc == 2) {
        calculateWeights(argv[1]);
        result = 0;
    } else {
        std::cout << std::endl << "Usage : " << std::endl << std::endl;
        std::cout << "./ocr [folder] where  [folder] is a directory with your "
                     "samples, this command will generate a perceptron.xml file"
                  << std::endl
                  << std::endl;
        std::cout << "./ocr perceptron.xml [file] where [file] is a png image "
                     "which has to be recognized"
                  << std::endl
                  << std::endl;
    }

    return result;
}
<commit_msg>Fix ocr switch to new boost<commit_after>#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h>
#include <NeuralNetwork/NeuralLayer/ConvolutionLayer.h>
#include <NeuralNetwork/NeuralLayer/NeuralLayer.h>
#include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h>
#include <NeuralNetwork/Neuron/Neuron.h>
#include <NeuralNetwork/Perceptron/Perceptron.h>
//#include <NeuralNetwork/NeuralLayer/OpenCLNeuralLayer.h>
#include <NeuralNetwork/Config.h>

#include <Utilities/MPL/Tuple.h>

#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#include <boost/filesystem.hpp>
#undef BOOST_SYSTEM_NO_DEPRECATED
#endif

#define png_infopp_NULL (png_infopp) NULL
#define int_p_NULL (int*)NULL

#if defined(NN_CC_MSVC)
#pragma warning(push)
// This function or variable may be unsafe
#pragma warning(disable : 4996)
#endif

#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/channel.hpp>

#include <boost/gil/gil_all.hpp>
#include <boost/gil/image.hpp>

#include <boost/gil/extension/io/png/old.hpp>
#include <boost/gil/extension/numeric/sampler.hpp>
#include <boost/gil/extension/numeric/resample.hpp>
#include <boost/gil/extension/dynamic_image/any_image.hpp>
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>

#include <cereal/archives/xml.hpp>
#include <cereal/types/array.hpp>
#include <cereal/types/tuple.hpp>
#include <cereal/types/vector.hpp>

#if defined(NN_CC_MSVC)
#pragma warning(pop)
#endif

#include "Var.h"

#include <tuple>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>

typedef long double VarType;

namespace {
    using namespace boost::gil;
    using namespace boost::gil::detail;
    const std::string alphabet("0123456789");
    constexpr std::size_t width = 49;
    constexpr std::size_t height = 67;
    constexpr std::size_t inputsNumber = width * height;
    constexpr std::size_t margin = 15;
    constexpr std::size_t stride = 10;
} // namespace

using ConvolutionGrid =
 typename nn::ConvolutionGrid< width, height, stride, margin >::define;

using Perceptron =
 nn::Perceptron< VarType,
                 nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::SigmoidFunction, inputsNumber, ConvolutionGrid >,
                 nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >;

using Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >;

template< typename Out >
struct halfdiff_cast_channels {
    template< typename T >
    Out operator()(const T& in1, const T& in2) const {
        return Out((in1 - in2) / 2);
    }
};

template< typename SrcView, typename DstView >
void convert_color(const SrcView& src, const DstView& dst) {
    typedef typename channel_type< DstView >::type d_channel_t;
    typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t;
    typedef pixel< channel_t, gray_layout_t > gray_pixel_t;

    copy_pixels(color_converted_view< gray_pixel_t >(src), dst);
}

template< typename Iterator >
void readImage(std::string fileName, Iterator out) {
    using namespace boost::gil;
    using namespace nn;
    using namespace nn::bp;

    rgb8_image_t srcImg;
    png_read_image(fileName.c_str(), srcImg);

    gray8_image_t dstImg(srcImg.dimensions());
    gray8_pixel_t white(255);
    fill_pixels(view(dstImg), white);

    gray8_image_t grayImage(srcImg.dimensions());
    convert_color(view(srcImg), view(grayImage));
    auto grayView = view(grayImage);

    gray8_image_t scaledImage(width, height);
    resize_view(grayView, view(scaledImage), bilinear_sampler());
    auto srcView = view(scaledImage);

    for(int y = 0; y < srcView.height(); ++y) {
        gray8c_view_t::x_iterator src_it(srcView.row_begin(y));
        for(int x = 0; x < srcView.width(); ++x) {
            *out = src_it[x] < 130 ? 1.f : -1.f; // 255.f;
            out++;
        }
    }
}

Perceptron readPerceptron(std::string fileName) {
    Perceptron perceptron;
    if(boost::filesystem::exists(fileName.c_str())) {
        std::ifstream file(fileName);
        if(file.good()) {
            Perceptron::Memento memento;
            cereal::XMLInputArchive ia(file);
            ia >> memento;

            perceptron.setMemento(memento);
        } else {
            throw std::logic_error("Invalid perceptron file name");
        }
    }

    return perceptron;
}

void recognize(std::string perceptron, std::string image) {
    try {
        std::array< VarType, inputsNumber > inputs = {0};
        readImage(image, inputs.begin());
        std::vector< VarType > result(alphabet.length(), VarType(0.f));
        readPerceptron(perceptron)
         .calculate(inputs.begin(), inputs.end(), result.begin());
        for(unsigned int i = 0; i < result.size(); i++) {
            std::cout << "Symbol: " << alphabet[i] << " " << result[i] << std::endl;
        }
    } catch(const std::exception& e) {
        std::cout << e.what() << std::endl;
    } catch(...) {
        std::cout << "Unknown error" << std::endl;
    }
}

template< typename Perc >
void save(const Perc& perc, std::string name) {
    typename Perc::Memento memento = perc.getMemento();
    std::ofstream strm(name);
    cereal::XMLOutputArchive oa(strm);
    oa << memento;
    strm.flush();
}

void calculateWeights(std::string imagesPath) {
    using namespace boost::filesystem;
    path directory(imagesPath);
    directory_iterator end_iter;

    std::vector< std::string > files;
    if(exists(directory) && is_directory(directory)) {
        for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) {
            if(is_regular_file(dir_iter->status())) {
                files.push_back(dir_iter->path().string());
            }
        }
    }

    std::cout << "Perceptron calculation started" << std::endl;
    static Perceptron tmp = readPerceptron("perceptron.xml");
    static Algo algorithm(0.003f);
    algorithm.setMemento(tmp.getMemento());

    std::vector< Algo::Prototype > prototypes;
    for(auto image : files) {
        if(!boost::filesystem::is_directory(image)) {
            try {
                Algo::Prototype proto;
                readImage(image, std::get< 0 >(proto).begin());
                std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f);
                char ch = path(image).filename().string()[0];
                size_t pos = alphabet.find(ch);
                std::get< 1 >(proto)[pos] = 1.0f;
                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    auto errorFunc = [](unsigned int epoch, VarType error) {
        // if(epoch % 100 == 0) {
        std::cout << "Epoch:" << epoch << " error:" << error << std::endl;
        // }

        return error > 0.001f;
    };

    static Perceptron perceptron =
     algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc);

    save(perceptron, "perceptron.xml");
}

int main(int argc, char** argv) {
    int result = -1;
    if(argc == 3) {
        recognize(argv[1], argv[2]);
        result = 0;
    } else if(argc == 2) {
        calculateWeights(argv[1]);
        result = 0;
    } else {
        std::cout << std::endl << "Usage : " << std::endl << std::endl;
        std::cout << "./ocr [folder] where  [folder] is a directory with your "
                     "samples, this command will generate a perceptron.xml file"
                  << std::endl
                  << std::endl;
        std::cout << "./ocr perceptron.xml [file] where [file] is a png image "
                     "which has to be recognized"
                  << std::endl
                  << std::endl;
    }

    return result;
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTextBox.h"
#include "../core/SkGlyphCache.h"
#include "SkUtils.h"
#include "SkAutoKern.h"

static inline int is_ws(int c)
{
    return !((c - 1) >> 5);
}

static size_t linebreak(const char text[], const char stop[], const SkPaint& paint, SkScalar margin)
{
    const char* start = text;

    SkAutoGlyphCache    ac(paint, NULL);
    SkGlyphCache*       cache = ac.getCache();
    SkFixed             w = 0;
    SkFixed             limit = SkScalarToFixed(margin);
    SkAutoKern          autokern;

    const char* word_start = text;
    int         prevWS = true;

    while (text < stop)
    {
        const char* prevText = text;
        SkUnichar   uni = SkUTF8_NextUnichar(&text);
        int         currWS = is_ws(uni);
        const SkGlyph&  glyph = cache->getUnicharMetrics(uni);

        if (!currWS && prevWS)
            word_start = prevText;
        prevWS = currWS;

        w += autokern.adjust(glyph) + glyph.fAdvanceX;
        if (w > limit)
        {
            if (currWS) // eat the rest of the whitespace
            {
                while (text < stop && is_ws(SkUTF8_ToUnichar(text)))
                    text += SkUTF8_CountUTF8Bytes(text);
            }
            else    // backup until a whitespace (or 1 char)
            {
                if (word_start == start)
                {
                    if (prevText > start)
                        text = prevText;
                }
                else
                    text = word_start;
            }
            break;
        }
    }
    return text - start;
}

int SkTextLineBreaker::CountLines(const char text[], size_t len, const SkPaint& paint, SkScalar width)
{
    const char* stop = text + len;
    int         count = 0;

    if (width > 0)
    {
        do {
            count += 1;
            text += linebreak(text, stop, paint, width);
        } while (text < stop);
    }
    return count;
}

//////////////////////////////////////////////////////////////////////////////

SkTextBox::SkTextBox()
{
    fBox.setEmpty();
    fSpacingMul = SK_Scalar1;
    fSpacingAdd = 0;
    fMode = kLineBreak_Mode;
    fSpacingAlign = kStart_SpacingAlign;
}

void SkTextBox::setMode(Mode mode)
{
    SkASSERT((unsigned)mode < kModeCount);
    fMode = SkToU8(mode);
}

void SkTextBox::setSpacingAlign(SpacingAlign align)
{
    SkASSERT((unsigned)align < kSpacingAlignCount);
    fSpacingAlign = SkToU8(align);
}

void SkTextBox::getBox(SkRect* box) const
{
    if (box)
        *box = fBox;
}

void SkTextBox::setBox(const SkRect& box)
{
    fBox = box;
}

void SkTextBox::setBox(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom)
{
    fBox.set(left, top, right, bottom);
}

void SkTextBox::getSpacing(SkScalar* mul, SkScalar* add) const
{
    if (mul)
        *mul = fSpacingMul;
    if (add)
        *add = fSpacingAdd;
}

void SkTextBox::setSpacing(SkScalar mul, SkScalar add)
{
    fSpacingMul = mul;
    fSpacingAdd = add;
}

/////////////////////////////////////////////////////////////////////////////////////////////

void SkTextBox::draw(SkCanvas* canvas, const char text[], size_t len, const SkPaint& paint)
{
    SkASSERT(canvas && &paint && (text || len == 0));

    SkScalar marginWidth = fBox.width();

    if (marginWidth <= 0 || len == 0)
        return;

    const char* textStop = text + len;

    SkScalar                x, y, scaledSpacing, height, fontHeight;
    SkPaint::FontMetrics    metrics;

    switch (paint.getTextAlign()) {
    case SkPaint::kLeft_Align:
        x = 0;
        break;
    case SkPaint::kCenter_Align:
        x = SkScalarHalf(marginWidth);
        break;
    default:
        x = marginWidth;
        break;
    }
    x += fBox.fLeft;

    fontHeight = paint.getFontMetrics(&metrics);
    scaledSpacing = SkScalarMul(fontHeight, fSpacingMul) + fSpacingAdd;
    height = fBox.height();

    //  compute Y position for first line
    {
        SkScalar textHeight = fontHeight;

        if (fMode == kLineBreak_Mode && fSpacingAlign != kStart_SpacingAlign)
        {
            int count = SkTextLineBreaker::CountLines(text, textStop - text, paint, marginWidth);
            SkASSERT(count > 0);
            textHeight += scaledSpacing * (count - 1);
        }

        switch (fSpacingAlign) {
        case kStart_SpacingAlign:
            y = 0;
            break;
        case kCenter_SpacingAlign:
            y = SkScalarHalf(height - textHeight);
            break;
        default:
            SkASSERT(fSpacingAlign == kEnd_SpacingAlign);
            y = height - textHeight;
            break;
        }
        y += fBox.fTop - metrics.fAscent;
    }

    for (;;)
    {
        len = linebreak(text, textStop, paint, marginWidth);
        if (y + metrics.fDescent + metrics.fLeading > 0)
            canvas->drawText(text, len, x, y, paint);
        text += len;
        if (text >= textStop)
            break;
        y += scaledSpacing;
        if (y + metrics.fAscent >= height)
            break;
    }
}

///////////////////////////////////////////////////////////////////////////////

void SkTextBox::setText(const char text[], size_t len, const SkPaint& paint) {
    fText = text;
    fLen = len;
    fPaint = &paint;
}

void SkTextBox::draw(SkCanvas* canvas) {
    this->draw(canvas, fText, fLen, *fPaint);
}

int SkTextBox::countLines() const {
    return SkTextLineBreaker::CountLines(fText, fLen, *fPaint, fBox.width());
}

SkScalar SkTextBox::getTextHeight() const {
    SkScalar spacing = SkScalarMul(fPaint->getTextSize(), fSpacingMul) + fSpacingAdd;
    return this->countLines() * spacing;
}

<commit_msg>SkTextBox to use public interfaces for line layout. https://codereview.appspot.com/6438044/<commit_after>/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTextBox.h"
#include "SkUtils.h"

static inline int is_ws(int c)
{
    return !((c - 1) >> 5);
}

static size_t linebreak(const char text[], const char stop[], const SkPaint& paint, SkScalar margin)
{
    return paint.breakText(text, stop - text, margin);
}

int SkTextLineBreaker::CountLines(const char text[], size_t len, const SkPaint& paint, SkScalar width)
{
    const char* stop = text + len;
    int         count = 0;

    if (width > 0)
    {
        do {
            count += 1;
            text += linebreak(text, stop, paint, width);
        } while (text < stop);
    }
    return count;
}

//////////////////////////////////////////////////////////////////////////////

SkTextBox::SkTextBox()
{
    fBox.setEmpty();
    fSpacingMul = SK_Scalar1;
    fSpacingAdd = 0;
    fMode = kLineBreak_Mode;
    fSpacingAlign = kStart_SpacingAlign;
}

void SkTextBox::setMode(Mode mode)
{
    SkASSERT((unsigned)mode < kModeCount);
    fMode = SkToU8(mode);
}

void SkTextBox::setSpacingAlign(SpacingAlign align)
{
    SkASSERT((unsigned)align < kSpacingAlignCount);
    fSpacingAlign = SkToU8(align);
}

void SkTextBox::getBox(SkRect* box) const
{
    if (box)
        *box = fBox;
}

void SkTextBox::setBox(const SkRect& box)
{
    fBox = box;
}

void SkTextBox::setBox(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom)
{
    fBox.set(left, top, right, bottom);
}

void SkTextBox::getSpacing(SkScalar* mul, SkScalar* add) const
{
    if (mul)
        *mul = fSpacingMul;
    if (add)
        *add = fSpacingAdd;
}

void SkTextBox::setSpacing(SkScalar mul, SkScalar add)
{
    fSpacingMul = mul;
    fSpacingAdd = add;
}

/////////////////////////////////////////////////////////////////////////////////////////////

void SkTextBox::draw(SkCanvas* canvas, const char text[], size_t len, const SkPaint& paint)
{
    SkASSERT(canvas && &paint && (text || len == 0));

    SkScalar marginWidth = fBox.width();

    if (marginWidth <= 0 || len == 0)
        return;

    const char* textStop = text + len;

    SkScalar                x, y, scaledSpacing, height, fontHeight;
    SkPaint::FontMetrics    metrics;

    switch (paint.getTextAlign()) {
    case SkPaint::kLeft_Align:
        x = 0;
        break;
    case SkPaint::kCenter_Align:
        x = SkScalarHalf(marginWidth);
        break;
    default:
        x = marginWidth;
        break;
    }
    x += fBox.fLeft;

    fontHeight = paint.getFontMetrics(&metrics);
    scaledSpacing = SkScalarMul(fontHeight, fSpacingMul) + fSpacingAdd;
    height = fBox.height();

    //  compute Y position for first line
    {
        SkScalar textHeight = fontHeight;

        if (fMode == kLineBreak_Mode && fSpacingAlign != kStart_SpacingAlign)
        {
            int count = SkTextLineBreaker::CountLines(text, textStop - text, paint, marginWidth);
            SkASSERT(count > 0);
            textHeight += scaledSpacing * (count - 1);
        }

        switch (fSpacingAlign) {
        case kStart_SpacingAlign:
            y = 0;
            break;
        case kCenter_SpacingAlign:
            y = SkScalarHalf(height - textHeight);
            break;
        default:
            SkASSERT(fSpacingAlign == kEnd_SpacingAlign);
            y = height - textHeight;
            break;
        }
        y += fBox.fTop - metrics.fAscent;
    }

    for (;;)
    {
        len = linebreak(text, textStop, paint, marginWidth);
        if (y + metrics.fDescent + metrics.fLeading > 0)
            canvas->drawText(text, len, x, y, paint);
        text += len;
        if (text >= textStop)
            break;
        y += scaledSpacing;
        if (y + metrics.fAscent >= height)
            break;
    }
}

///////////////////////////////////////////////////////////////////////////////

void SkTextBox::setText(const char text[], size_t len, const SkPaint& paint) {
    fText = text;
    fLen = len;
    fPaint = &paint;
}

void SkTextBox::draw(SkCanvas* canvas) {
    this->draw(canvas, fText, fLen, *fPaint);
}

int SkTextBox::countLines() const {
    return SkTextLineBreaker::CountLines(fText, fLen, *fPaint, fBox.width());
}

SkScalar SkTextBox::getTextHeight() const {
    SkScalar spacing = SkScalarMul(fPaint->getTextSize(), fSpacingMul) + fSpacingAdd;
    return this->countLines() * spacing;
}

<|endoftext|>


<commit_before><commit_msg>Fix crash when download bz2 from http<commit_after><|endoftext|>


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

#include "StaticStrings.h"

using namespace arangodb;

// constants
std::string const StaticStrings::N1800("1800");

// system attribute names
std::string const StaticStrings::IdString("_id");
std::string const StaticStrings::KeyString("_key");
std::string const StaticStrings::RevString("_rev");
std::string const StaticStrings::FromString("_from");
std::string const StaticStrings::ToString("_to");

// HTTP headers
std::string const StaticStrings::Accept("accept");
std::string const StaticStrings::AccessControlAllowCredentials("access-control-allow-credentials");
std::string const StaticStrings::AccessControlAllowHeaders("access-control-allow-headers");
std::string const StaticStrings::AccessControlAllowMethods("access-control-allow-methods");
std::string const StaticStrings::AccessControlAllowOrigin("access-control-allow-origin");
std::string const StaticStrings::AccessControlExposeHeaders("access-control-expose-headers");
std::string const StaticStrings::AccessControlMaxAge("access-control-max-age");
std::string const StaticStrings::AccessControlRequestHeaders("access-control-request-headers");
std::string const StaticStrings::Allow("allow");
std::string const StaticStrings::Close("Close");
std::string const StaticStrings::Connection("connection");
std::string const StaticStrings::ContentTypeHeader("content-type");
std::string const StaticStrings::KeepAlive("Close");
std::string const StaticStrings::Location("location");
std::string const StaticStrings::WwwAuthenticate("www-authenticate");

// mime types
std::string const StaticStrings::MimeTypeJson("application/json; charset=utf-8");
std::string const StaticStrings::MimeTypeVPack("application/x-velocypack");

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

#include "StaticStrings.h"

using namespace arangodb;

// constants
std::string const StaticStrings::N1800("1800");

// system attribute names
std::string const StaticStrings::IdString("_id");
std::string const StaticStrings::KeyString("_key");
std::string const StaticStrings::RevString("_rev");
std::string const StaticStrings::FromString("_from");
std::string const StaticStrings::ToString("_to");

// HTTP headers
std::string const StaticStrings::Accept("accept");
std::string const StaticStrings::AccessControlAllowCredentials("access-control-allow-credentials");
std::string const StaticStrings::AccessControlAllowHeaders("access-control-allow-headers");
std::string const StaticStrings::AccessControlAllowMethods("access-control-allow-methods");
std::string const StaticStrings::AccessControlAllowOrigin("access-control-allow-origin");
std::string const StaticStrings::AccessControlExposeHeaders("access-control-expose-headers");
std::string const StaticStrings::AccessControlMaxAge("access-control-max-age");
std::string const StaticStrings::AccessControlRequestHeaders("access-control-request-headers");
std::string const StaticStrings::Allow("allow");
std::string const StaticStrings::Close("Close");
std::string const StaticStrings::Connection("connection");
std::string const StaticStrings::ContentTypeHeader("content-type");
std::string const StaticStrings::KeepAlive("Keep-Alive");
std::string const StaticStrings::Location("location");
std::string const StaticStrings::WwwAuthenticate("www-authenticate");

// mime types
std::string const StaticStrings::MimeTypeJson("application/json; charset=utf-8");
std::string const StaticStrings::MimeTypeVPack("application/x-velocypack");

<|endoftext|>