<commit_before>/**
 * These codes are licensed under the Unlicense.
 * http://unlicense.org
 */

#include <iomanip>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

#include <commata/text_error.hpp>

#include "BaseTest.hpp"
#include "tracking_allocator.hpp"

using namespace commata;
using namespace commata::test;

static_assert(
    std::is_nothrow_move_constructible<text_error>::value,
    "text_error shall be nothrow-move-constructible");
static_assert(
    std::is_nothrow_copy_constructible<text_error>::value,
    "text_error shall be nothrow-copy-constructible");
static_assert(
    std::is_nothrow_move_assignable<text_error>::value,
    "text_error shall be nothrow-move-assignable");
static_assert(
    std::is_nothrow_copy_assignable<text_error>::value,
    "text_error shall be nothrow-copy-assignable");

struct TestTextError : BaseTest
{};

TEST_F(TestTextError, Ctors)
{
    const char* message = "Some error occurred";

    text_error e1(message);
    ASSERT_STREQ(message, e1.what());

    auto e2(e1);
    auto e3(std::move(e1));
    ASSERT_STREQ(message, e2.what());
    ASSERT_STREQ(message, e3.what());
}

TEST_F(TestTextError, AssignmentOps)
{
    const char* message1 = "Some error occurred";
    const char* message2 = "One more error occurred";
    const char* message3 = "No message";

    text_error e1(message1);
    text_error e2(message2);
    text_error e3(message3);

    e2 = e1;
    e3 = std::move(e1);
    ASSERT_STREQ(message1, e2.what());
    ASSERT_STREQ(message1, e3.what());
}

TEST_F(TestTextError, Info)
{
    text_error e("Some error occurred");
    {
        std::stringstream s;
        s << e.info();
        ASSERT_EQ(e.what(), s.str());
    }

    e.set_physical_position(12345);
    {
        std::stringstream s;
        s << e.info();
        std::string i = s.str();
        ASSERT_NE(s.str(), e.what());
        const auto lpos = i.find(
            std::to_string(e.get_physical_position()->first + 1));
        const auto cpos = i.find("n/a");
        ASSERT_NE(lpos, std::string::npos);
        ASSERT_NE(cpos, std::string::npos);
        ASSERT_GT(cpos, lpos);
    }

    // info()'s string contains positions
    e.set_physical_position(text_error::npos - 1, text_error::npos - 2);
    std::string is;
    {
        std::stringstream s;
        s << e.info();
        is = s.str();
    }
    ASSERT_NE(is, e.what());
    {
        const auto lpos = is.find(
            std::to_string(e.get_physical_position()->first + 1));
        const auto cpos = is.find(
            std::to_string(e.get_physical_position()->second + 1));
        ASSERT_NE(lpos, std::string::npos);
        ASSERT_NE(cpos, std::string::npos);
        ASSERT_GT(cpos, lpos);
    }
    ASSERT_EQ(is, to_string(e.info()));

    // info()'s string is aligned to right
    std::string is2;
    {
        std::stringstream s;
        s << std::setw(is.size() + 20) << std::setfill('_') << e.info();
        is2 = s.str();
    }
    ASSERT_EQ(is.size() + 20, is2.size());
    ASSERT_EQ(std::string(20, '_'), is2.substr(0, 20));
    ASSERT_EQ(is, is2.substr(20));

    // info()'s string is aligned to left
    std::string is3;
    {
        std::stringstream s;
        s << std::left;
        s << std::setw(is.size() + 10) << std::setfill('#') << e.info();
        is3 = s.str();
    }
    ASSERT_EQ(is.size() + 10, is3.size());
    ASSERT_EQ(is, is3.substr(0, is.size()));
    ASSERT_EQ(std::string(10, '#'), is3.substr(is.size()));

    // info() can be written into wide streams
    std::wstring isw;
    {
        std::wstringstream s;
        s << is.c_str();
        isw = s.str();
    }
    std::wstring is4;
    {
        std::wstringstream s;
        s << e.info();
        is4 = s.str();
    }
    ASSERT_EQ(isw, is4);
    ASSERT_EQ(isw, to_wstring(e.info()));
}

TEST_F(TestTextError, Allocators)
{
    std::vector<std::pair<char*, char*>> allocated;
    tracking_allocator<std::allocator<char>> a(allocated);

    const char* message = "A certain very lengthy message that tells "
                          "the details of the text error";

    using traits_t = std::char_traits<char>;
    using string_t = std::basic_string<char, traits_t, decltype(a)>;
    text_error e1(string_t(message, a));
    ASSERT_STREQ(message, e1.what());
    ASSERT_TRUE(a.tracks(e1.what()));

    auto e2(e1);
    auto e3(std::move(e1));
    ASSERT_TRUE(a.tracks(e2.what()));
    ASSERT_TRUE(a.tracks(e3.what()));

    // Short strings might be stored string's internal structure
    // so a short-string case seems worthy of a test

    string_t message2("!", a);
    text_error e4(message2);
    ASSERT_STREQ(message2.c_str(), e4.what());
    ASSERT_TRUE(a.tracks(e4.what()));
}
<commit_msg>Add a comment to tests of errors<commit_after>/**
 * These codes are licensed under the Unlicense.
 * http://unlicense.org
 */

#include <iomanip>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

#include <commata/text_error.hpp>

#include "BaseTest.hpp"
#include "tracking_allocator.hpp"

using namespace commata;
using namespace commata::test;

static_assert(
    std::is_nothrow_move_constructible<text_error>::value,
    "text_error shall be nothrow-move-constructible");
static_assert(
    std::is_nothrow_copy_constructible<text_error>::value,
    "text_error shall be nothrow-copy-constructible");
static_assert(
    std::is_nothrow_move_assignable<text_error>::value,
    "text_error shall be nothrow-move-assignable");
static_assert(
    std::is_nothrow_copy_assignable<text_error>::value,
    "text_error shall be nothrow-copy-assignable");

struct TestTextError : BaseTest
{};

TEST_F(TestTextError, Ctors)
{
    const char* message = "Some error occurred";

    text_error e1(message);
    ASSERT_STREQ(message, e1.what());

    auto e2(e1);
    auto e3(std::move(e1));
    ASSERT_STREQ(message, e2.what());
    ASSERT_STREQ(message, e3.what());
}

TEST_F(TestTextError, AssignmentOps)
{
    const char* message1 = "Some error occurred";
    const char* message2 = "One more error occurred";
    const char* message3 = "No message";

    text_error e1(message1);
    text_error e2(message2);
    text_error e3(message3);

    e2 = e1;
    e3 = std::move(e1);
    ASSERT_STREQ(message1, e2.what());
    ASSERT_STREQ(message1, e3.what());
}

TEST_F(TestTextError, Info)
{
    text_error e("Some error occurred");
    {
        std::stringstream s;
        s << e.info();
        ASSERT_EQ(e.what(), s.str());
    }

    e.set_physical_position(12345);
    {
        std::stringstream s;
        s << e.info();
        std::string i = s.str();
        ASSERT_NE(s.str(), e.what());
        const auto lpos = i.find(
            std::to_string(e.get_physical_position()->first + 1));
        const auto cpos = i.find("n/a");
        ASSERT_NE(lpos, std::string::npos);
        ASSERT_NE(cpos, std::string::npos);
        ASSERT_GT(cpos, lpos);
    }

    // info()'s string contains positions
    e.set_physical_position(text_error::npos - 1, text_error::npos - 2);
    std::string is;
    {
        std::stringstream s;
        s << e.info();
        is = s.str();
    }
    ASSERT_NE(is, e.what());
    {
        const auto lpos = is.find(
            std::to_string(e.get_physical_position()->first + 1));
        const auto cpos = is.find(
            std::to_string(e.get_physical_position()->second + 1));
        ASSERT_NE(lpos, std::string::npos);
        ASSERT_NE(cpos, std::string::npos);
        ASSERT_GT(cpos, lpos);
    }
    ASSERT_EQ(is, to_string(e.info()));

    // info()'s string is aligned to right
    std::string is2;
    {
        std::stringstream s;
        s << std::setw(is.size() + 20) << std::setfill('_') << e.info();
        is2 = s.str();
    }
    ASSERT_EQ(is.size() + 20, is2.size());
    ASSERT_EQ(std::string(20, '_'), is2.substr(0, 20));
    ASSERT_EQ(is, is2.substr(20));

    // info()'s string is aligned to left
    std::string is3;
    {
        std::stringstream s;
        s << std::left;
        s << std::setw(is.size() + 10) << std::setfill('#') << e.info();
        is3 = s.str();
    }
    ASSERT_EQ(is.size() + 10, is3.size());
    ASSERT_EQ(is, is3.substr(0, is.size()));
    ASSERT_EQ(std::string(10, '#'), is3.substr(is.size()));

    // info() can be written into wide streams
    std::wstring isw;
    {
        std::wstringstream s;
        s << is.c_str();
        isw = s.str();
    }
    std::wstring is4;
    {
        std::wstringstream s;
        s << e.info();
        is4 = s.str();
    }
    ASSERT_EQ(isw, is4);
    ASSERT_EQ(isw, to_wstring(e.info()));
}

TEST_F(TestTextError, Allocators)
{
    // std::allocate_shared which comes with Visual Studio 2015 does not seem
    // to support fancy pointers, so we do not test the fancy cases

    std::vector<std::pair<char*, char*>> allocated;
    tracking_allocator<std::allocator<char>> a(allocated);

    const char* message = "A certain very lengthy message that tells "
                          "the details of the text error";

    using traits_t = std::char_traits<char>;
    using string_t = std::basic_string<char, traits_t, decltype(a)>;
    text_error e1(string_t(message, a));
    ASSERT_STREQ(message, e1.what());
    ASSERT_TRUE(a.tracks(e1.what()));

    auto e2(e1);
    auto e3(std::move(e1));
    ASSERT_TRUE(a.tracks(e2.what()));
    ASSERT_TRUE(a.tracks(e3.what()));

    // Short strings might be stored string's internal structure
    // so a short-string case seems worthy of a test

    string_t message2("!", a);
    text_error e4(message2);
    ASSERT_STREQ(message2.c_str(), e4.what());
    ASSERT_TRUE(a.tracks(e4.what()));
}
<|endoftext|>


<commit_before>#include "server.h"
#include "wsgi.h"
#include "base/memory.hpp"

#include <uv.h>
#include <memory.h>

// ----------------------------------------------
//  UV Variants
// ----------------------------------------------
#define HYDRUS_SERVER_BACKLOG 128

#define _STREAM(p) ((uv_stream_t*)(p))
#define _TCP(p) ((uv_tcp_t*)(p))
#define _WSGI(p) ((hydrus::WSGIApplication*)(p->data))

static uv_loop_t   * sEventLoop     = nullptr;
static uv_tcp_t      sHttpServer;
static sockaddr_in   sIPAddress;
static const char  * sBindAddress   = nullptr;
static int           sBindPort      = 0;

#ifndef HY_SMALL_BUFFER
static hydrus::FixedMemoryPool<65535> sReadBuffer;
#else
static hydrus::FixedMemoryPool<4096>  sReadBuffer;
#endif

// ----------------------------------------------
//  HTTP callbacks
// ----------------------------------------------
static void
http_on_allocate(uv_handle_t * handle, size_t suggest, uv_buf_t * buf)
{
    buf->base = sReadBuffer.data();
    buf->len = sReadBuffer.size();
}

static void
http_on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
    // NOTICE: WSGI object will be deleted after it write (execute / raise)
    auto wsgi = _WSGI(stream);

    if (nread < 0)
    {
        delete wsgi;
    }
    else if (nread < (ssize_t)buf->len)
    {
        if (nread > 0)
        {
            wsgi->append(buf->base, nread);
        }
        else if (!wsgi->hasBuffer())
        {
            delete wsgi;
            return;
        }
        if (wsgi->parse())
        {
            wsgi->execute();
        }
        else
        {
            wsgi->raiseUp(400);
            delete wsgi;
        }
    }
    else
    {
        wsgi->append(buf->base, nread);
        uv_read_start(stream, http_on_allocate, http_on_read);
    }
}

static void
http_on_connection(uv_stream_t *server, int status)
{
    static int failCounter = 0;
    if (status != 0)
        return;

    hydrus::WSGIApplication * app = new hydrus::WSGIApplication();
    if (uv_accept((uv_stream_t*)&sHttpServer, _STREAM(app->connection())) != 0)
    {
        delete app;
    }
    else
    {
        uv_read_start((uv_stream_t*)app->connection(), http_on_allocate, http_on_read);
    }
}

// ----------------------------------------------
//  Server Class Implementation
// ----------------------------------------------

NS(hydrus) // namespace hydrus {

Server::ServerStatus
Server::listen(const char * address, int port)
{
    int err;
    if (sEventLoop)
        goto SERVER_READY;

    sEventLoop = uv_default_loop();
    uv_tcp_init(sEventLoop, &sHttpServer);
    uv_ip4_addr(address, port, &sIPAddress);

    err = uv_tcp_bind(&sHttpServer, (sockaddr*)&sIPAddress, 0);
    if (err)
    {
        return hydrus::Server::INUSED;
    }
    uv_listen((uv_stream_t*)&sHttpServer, HYDRUS_SERVER_BACKLOG, http_on_connection);

SERVER_READY:
    sBindAddress = address;
    sBindPort = port;
    return hydrus::Server::READY;
}

void
Server::run()
{
    uv_run(sEventLoop, UV_RUN_DEFAULT);
}

const char *
Server::host()
{
    return sBindAddress;
}

int
Server::port()
{
    return sBindPort;
}

NS_END    // }
<commit_msg>add signal handler<commit_after>#include "server.h"
#include "wsgi.h"
#include "base/memory.hpp"

#include <uv.h>
#include <memory.h>

// ----------------------------------------------
//  UV Variants
// ----------------------------------------------
#define HYDRUS_SERVER_BACKLOG 128

#define _STREAM(p) ((uv_stream_t*)(p))
#define _TCP(p) ((uv_tcp_t*)(p))
#define _WSGI(p) ((hydrus::WSGIApplication*)(p->data))

static uv_loop_t   * sEventLoop     = nullptr;
static uv_tcp_t      sHttpServer;
static sockaddr_in   sIPAddress;
static const char  * sBindAddress   = nullptr;
static int           sBindPort      = 0;
static uv_signal_t   sKeyboardIntep;

#ifndef HY_SMALL_BUFFER
static hydrus::FixedMemoryPool<65535> sReadBuffer;
#else
static hydrus::FixedMemoryPool<4096>  sReadBuffer;
#endif

// ----------------------------------------------
//  HTTP callbacks
// ----------------------------------------------
static void
http_on_allocate(uv_handle_t * handle, size_t suggest, uv_buf_t * buf)
{
    buf->base = sReadBuffer.data();
    buf->len = sReadBuffer.size();
}

static void
http_on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
    // NOTICE: WSGI object will be deleted after it write (execute / raise)
    auto wsgi = _WSGI(stream);

    if (nread < 0)
    {
        delete wsgi;
    }
    else if (nread < (ssize_t)buf->len)
    {
        if (nread > 0)
        {
            wsgi->append(buf->base, nread);
        }
        else if (!wsgi->hasBuffer())
        {
            delete wsgi;
            return;
        }
        if (wsgi->parse())
        {
            wsgi->execute();
        }
        else
        {
            wsgi->raiseUp(400);
            delete wsgi;
        }
    }
    else
    {
        wsgi->append(buf->base, nread);
        uv_read_start(stream, http_on_allocate, http_on_read);
    }
}

static void
http_on_connection(uv_stream_t *server, int status)
{
    static int failCounter = 0;
    if (status != 0)
        return;

    hydrus::WSGIApplication * app = new hydrus::WSGIApplication();
    if (uv_accept((uv_stream_t*)&sHttpServer, _STREAM(app->connection())) != 0)
    {
        delete app;
    }
    else
    {
        uv_read_start((uv_stream_t*)app->connection(), http_on_allocate, http_on_read);
    }
}

static void
signal_on_terminate(uv_signal_t* handle, int signum)
{
    if (signum == SIGTERM)
    {
        fprintf(stdout, "Good bye :-)\n");
        uv_signal_stop(handle);
        uv_stop(sEventLoop);
    }
}

// ----------------------------------------------
//  Server Class Implementation
// ----------------------------------------------

NS(hydrus) // namespace hydrus {

Server::ServerStatus
Server::listen(const char * address, int port)
{
    int err;
    if (sEventLoop)
        goto SERVER_READY;

    sEventLoop = uv_default_loop();
    uv_tcp_init(sEventLoop, &sHttpServer);
    uv_ip4_addr(address, port, &sIPAddress);

    err = uv_tcp_bind(&sHttpServer, (sockaddr*)&sIPAddress, 0);
    if (err)
    {
        return hydrus::Server::INUSED;
    }
    uv_listen((uv_stream_t*)&sHttpServer, HYDRUS_SERVER_BACKLOG, http_on_connection);

SERVER_READY:
    sBindAddress = address;
    sBindPort = port;
    return hydrus::Server::READY;
}

void
Server::run()
{
    uv_signal_init(sEventLoop, &sKeyboardIntep);
    uv_signal_start(&sKeyboardIntep, signal_on_terminate, SIGTERM);

    uv_run(sEventLoop, UV_RUN_DEFAULT);
}

const char *
Server::host()
{
    return sBindAddress;
}

int
Server::port()
{
    return sBindPort;
}

NS_END    // }
<|endoftext|>


<commit_before>#ifndef _SHAPE_HPP
#define _SHAPE_HPP

#include <utility>

#include "data_structures.hpp"
#include "bounding_shape.hpp"

/**
 * Provides an implementation for all objects present in the scene.
 */
class Shape {
protected:
    float index_of_refraction, ambient_coef, diffuse_coef, specular_coef;
    Color color; // Will need to be replaced with advanced method
    BoundingShape *boundary;
    Shape(Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef);
public:
    /**
     * @return Returns the index of refraction.
     */
    float getIndexOfRefraction() const;

    /**
     * @return Returns the color of the shape.
     */
    Color getColor() const;

    /**
     * Calculates the intersection between a ray and the object.
     *
     * @param ray The ray in question.
     * @return A unit normal ray at the point of intersection, or FIXME
     * null.
     */
    virtual Ray* getIntersection(const Ray& ray) const = 0;
};

/**
 * Represents a sphere primitive.
 */
class Sphere : public Shape {
private:
    Point center;
    float radius;
public:

    /**
     * Creates a sphere primitive with the given parameters.
     *
     * @param center The origin of the sphere.
     * @param radius The radius of the sphere.
     * @param index_of_refraction Index of refraction, specific to the
     * material of the sphere.
     *
     * @return a pointer to the Ray normal to the intersection,
     * or NULL if no intersection. Remember to delete the Ray when done!
     */
    Sphere(Point center, float radius, Color color, float index_of_refraction);

    virtual Ray* getIntersection(const Ray& ray) const;
};

/**
 * Represents an infinite plane.
 */
class Plane : public Shape {

private:
    Point center;
    Vector normal;
public:
    /**
     * Creates a plane primitive with the given parameters.
     *
     * @param center The origin of the plane (any point on the plane.
     * @param normal The vector normal to the plane.
     * @param index_of_refraction Index of refraction, specific to the
     * material of the plane.
     *
     * @return a pointer to the Ray normal to the intersection,
     * or NULL if no intersection. Remember to delete the Ray when done!
     */
    Plane(Point center, Vector normal, Color color, float index_of_refraction);

    virtual Ray* getIntersection(const Ray& ray) const;
};

#endif
<commit_msg>Added lighting coefficients.<commit_after>#ifndef _SHAPE_HPP
#define _SHAPE_HPP

#include <utility>

#include "data_structures.hpp"
#include "bounding_shape.hpp"

/**
 * Provides an implementation for all objects present in the scene.
 */
class Shape {
protected:
    float index_of_refraction, ambient_coef, diffuse_coef, specular_coef;
    Color color; // Will need to be replaced with advanced method
    BoundingShape *boundary;
    Shape(Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef);
public:
    /**
     * @return Returns the index of refraction.
     */
    float getIndexOfRefraction() const;

    /**
     * @return Returns the color of the shape.
     */
    Color getColor() const;

    /**
     * Calculates the intersection between a ray and the object.
     *
     * @param ray The ray in question.
     * @return A unit normal ray at the point of intersection, or FIXME
     * null.
     */
    virtual Ray* getIntersection(const Ray& ray) const = 0;
};

/**
 * Represents a sphere primitive.
 */
class Sphere : public Shape {
private:
    Point center;
    float radius;
public:

    /**
     * Creates a sphere primitive with the given parameters.
     *
     * @param center The origin of the sphere.
     * @param radius The radius of the sphere.
     * @param index_of_refraction Index of refraction, specific to the
     * material of the sphere.
     * @param ambient_coef The coefficient for ambient light effects.
     * @param diffuse_coef The coefficient for diffuse light effects.
     * @param specular_coef The coefficient for specular light effects.
     *
     * @return a pointer to the Ray normal to the intersection,
     * or NULL if no intersection. Remember to delete the Ray when done!
     */
    Sphere(Point center, float radius, Color color, float index_of_refraction,
           float ambient_coef, float diffuse_coef, float specular_coef);

    virtual Ray* getIntersection(const Ray& ray) const;
};

/**
 * Represents an infinite plane.
 */
class Plane : public Shape {

private:
    Point center;
    Vector normal;
public:
    /**
     * Creates a plane primitive with the given parameters.
     *
     * @param center The origin of the plane (any point on the plane.
     * @param normal The vector normal to the plane.
     * @param index_of_refraction Index of refraction, specific to the
     * material of the plane.
     * @param ambient_coef The coefficient for ambient light effects.
     * @param diffuse_coef The coefficient for diffuse light effects.
     * @param specular_coef The coefficient for specular light effects.
     *
     * @return a pointer to the Ray normal to the intersection,
     * or NULL if no intersection. Remember to delete the Ray when done!
     */
    Plane(Point center, Vector normal, Color color, float index_of_refraction,
          float ambient_coef, float diffuse_coef, float specular_coef);

    virtual Ray* getIntersection(const Ray& ray) const;
};

#endif
<|endoftext|>


<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skirt.h"
#include "support.h"

namespace cura
{

void generateSkirt(SliceDataStorage& storage, int distance, int extrusionWidth, int count, int minLength)
{
    if (count == 0) return;

    bool externalOnly = (distance > 0);

    Polygons support;
    if (storage.support.generated)
        support = storage.support.supportLayers[0].supportAreas;
    { // get support polygons
        for(SliceMeshStorage& mesh : storage.meshes)
        {
            if (mesh.layers.size() < 1) continue;
            SliceLayer* layer = &mesh.layers[0];
            for(unsigned int i=0; i<layer->parts.size(); i++)
                support = support.difference(layer->parts[i].outline);
        }

        // expand and contract to smooth the final polygon
        if (count == 1 && distance > 0)
        {
            int dist = extrusionWidth * 5;
            support = support.offset(dist).offset(-dist);
        }
    }

    for(int skirtNr=0; skirtNr<count;skirtNr++)
    {
        int offsetDistance = distance + extrusionWidth * skirtNr + extrusionWidth / 2;

        Polygons skirtPolygons(storage.wipeTower.offset(offsetDistance));
        for(SliceMeshStorage& mesh : storage.meshes)
        {
            if (mesh.layers.size() < 1) continue;
            for(SliceLayerPart& part : mesh.layers[0].parts)
            {
                if (externalOnly)
                {
                    Polygons p;
                    p.add(part.outline.outerPolygon());
                    skirtPolygons = skirtPolygons.unionPolygons(p.offset(offsetDistance, ClipperLib::jtRound));
                }
                else
                {
                    skirtPolygons = skirtPolygons.unionPolygons(part.outline.offset(offsetDistance, ClipperLib::jtRound));
                }
            }
        }

        skirtPolygons = skirtPolygons.unionPolygons(support.offset(offsetDistance, ClipperLib::jtRound));
        //Remove small inner skirt holes. Holes have a negative area, remove anything smaller then 100x extrusion "area"
        for(unsigned int n=0; n<skirtPolygons.size(); n++)
        {
            double area = skirtPolygons[n].area();
            if (area < 0 && area > -extrusionWidth * extrusionWidth * 100)
                skirtPolygons.remove(n--);
        }

        storage.skirt.add(skirtPolygons);

        int lenght = storage.skirt.polygonLength();
        if (skirtNr + 1 >= count && lenght > 0 && lenght < minLength) // make brim have more lines when total length is too small
            count++;
    }

    //Add a skirt under the wipetower to make it stick better.
    Polygons wipe_tower = storage.wipeTower.offset(-extrusionWidth / 2);
    while(wipe_tower.size() > 0)
    {
        storage.skirt.add(wipe_tower);
        wipe_tower = wipe_tower.offset(-extrusionWidth);
    }

    if (count == 1 && distance > 0)
    {
        storage.skirt = storage.skirt.convexHull();
    }
}

}//namespace cura
<commit_msg>reverse the print order of the wipe tower skirt to inward<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skirt.h"
#include "support.h"

#include <queue>

namespace cura
{

void generateSkirt(SliceDataStorage& storage, int distance, int extrusionWidth, int count, int minLength)
{
    if (count == 0) return;

    bool externalOnly = (distance > 0);

    Polygons support;
    if (storage.support.generated)
        support = storage.support.supportLayers[0].supportAreas;
    { // get support polygons
        for(SliceMeshStorage& mesh : storage.meshes)
        {
            if (mesh.layers.size() < 1) continue;
            SliceLayer* layer = &mesh.layers[0];
            for(unsigned int i=0; i<layer->parts.size(); i++)
                support = support.difference(layer->parts[i].outline);
        }

        // expand and contract to smooth the final polygon
        if (count == 1 && distance > 0)
        {
            int dist = extrusionWidth * 5;
            support = support.offset(dist).offset(-dist);
        }
    }

    for(int skirtNr=0; skirtNr<count;skirtNr++)
    {
        int offsetDistance = distance + extrusionWidth * skirtNr + extrusionWidth / 2;

        Polygons skirtPolygons(storage.wipeTower.offset(offsetDistance));
        for(SliceMeshStorage& mesh : storage.meshes)
        {
            if (mesh.layers.size() < 1) continue;
            for(SliceLayerPart& part : mesh.layers[0].parts)
            {
                if (externalOnly)
                {
                    Polygons p;
                    p.add(part.outline.outerPolygon());
                    skirtPolygons = skirtPolygons.unionPolygons(p.offset(offsetDistance, ClipperLib::jtRound));
                }
                else
                {
                    skirtPolygons = skirtPolygons.unionPolygons(part.outline.offset(offsetDistance, ClipperLib::jtRound));
                }
            }
        }

        skirtPolygons = skirtPolygons.unionPolygons(support.offset(offsetDistance, ClipperLib::jtRound));
        //Remove small inner skirt holes. Holes have a negative area, remove anything smaller then 100x extrusion "area"
        for(unsigned int n=0; n<skirtPolygons.size(); n++)
        {
            double area = skirtPolygons[n].area();
            if (area < 0 && area > -extrusionWidth * extrusionWidth * 100)
                skirtPolygons.remove(n--);
        }

        storage.skirt.add(skirtPolygons);

        int lenght = storage.skirt.polygonLength();
        if (skirtNr + 1 >= count && lenght > 0 && lenght < minLength) // make brim have more lines when total length is too small
            count++;
    }

    //Add a skirt under the wipetower to make it stick better.
    Polygons wipe_tower = storage.wipeTower.offset(-extrusionWidth / 2);
    std::queue<Polygons> wipe_tower_insets;
    while(wipe_tower.size() > 0)
    {
        wipe_tower_insets.emplace(wipe_tower);
        wipe_tower = wipe_tower.offset(-extrusionWidth);
    }
    while (wipe_tower_insets.empty())
    {
        Polygons& inset = wipe_tower_insets.back();
        storage.skirt.add(inset);
        wipe_tower_insets.pop();
    }

    if (count == 1 && distance > 0)
    {
        storage.skirt = storage.skirt.convexHull();
    }
}

}//namespace cura
<|endoftext|>


<commit_before>// (The MIT License)

// Copyright (c) 2012 Thomas Blobaum <tblobaum@gmail.com>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <v8.h>
#include <node.h>
#include <syslog.h>
#include <string>

using namespace std;
using namespace node;
using namespace v8;

char title[1024];

static v8::Handle<v8::Value> open(const v8::Arguments& args) {
  args[0]->ToString()->WriteAscii((char*) &title);
  int facility = args[1]->ToInteger()->Int32Value();
  int log_upto = args[2]->ToInteger()->Int32Value();
  setlogmask(LOG_UPTO(log_upto));
  openlog(title, LOG_PID | LOG_NDELAY, facility);

  return String::New("true");
}

static v8::Handle<v8::Value> exit(const v8::Arguments& args) {
  closelog();

  return String::New("true");
}

static v8::Handle<v8::Value> log(const v8::Arguments& args) {
  int severity = args[0]->ToInteger()->Int32Value();
  v8::String::Utf8Value message(args[1]->ToString());
  syslog(severity, "%s", *message );

  return String::New("true");
}

void init(v8::Handle<v8::Object> target) {
  NODE_SET_METHOD(target, "open", open);
  NODE_SET_METHOD(target, "exit", exit);
  NODE_SET_METHOD(target, "log", log);
}

NODE_MODULE(syslog, init)<commit_msg>updated v8 bindings for node 0.12<commit_after>// (The MIT License)

// Copyright (c) 2012 Thomas Blobaum <tblobaum@gmail.com>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include <v8.h>
#include <node.h>
#include <syslog.h>
#include <string>

using namespace std;
using namespace node;
using namespace v8;

char title[1024];

void open(const FunctionCallbackInfo<v8::Value>& args) {
  args[0]->ToString()->WriteUtf8((char*) &title);
  int facility = args[1]->ToInteger()->Int32Value();
  int log_upto = args[2]->ToInteger()->Int32Value();
  setlogmask(LOG_UPTO(log_upto));
  openlog(title, LOG_PID | LOG_NDELAY, facility);

  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "true"));
}

void exit(const FunctionCallbackInfo<v8::Value>& args) {
  closelog();

  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "true"));
}

void log(const FunctionCallbackInfo<v8::Value>& args) {
  int severity = args[0]->ToInteger()->Int32Value();
  v8::String::Utf8Value message(args[1]->ToString());
  syslog(severity, "%s", *message );

  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "true"));
}

void init(v8::Handle<v8::Object> target) {
  NODE_SET_METHOD(target, "open", open);
  NODE_SET_METHOD(target, "exit", exit);
  NODE_SET_METHOD(target, "log", log);
}

NODE_MODULE(syslog, init)
<|endoftext|>


<commit_before>#include "../include/token.h"

//Declaracao do construtor da classe Token
Token::Token(std::string a){
    this -> nome = a;
    this -> type = token_type::undefined;
};

//Analisa se um determinado Token eh rotulo, tambem recebe a linha que esse token esta contido pra possiveis analises
bool Token::isRotulo(std::string token, std::string linha, std::vector<Mnemonic> instructionList){
    if (Token::have2points(token)){
        return true;
    }

    //algumas strings que queremos comparar, esta sendo feito assim pq de outras maneiras nao poderiamos ter um rotulo
    std::stringstream Line (linha);
    std::string aux;

    //pega o primeiro elemento da linha
    Line >> aux;

    //ve se a linha eh uma linha do tipo section
    if (aux == "section"){
        Line >> aux;
        if((aux == "data") || (aux == "text")){
            return false;
        }
    }

    //testa se eh uma instrucao
    for (int i = 0; i < instructionList.size(); i++){
        if (token == instructionList[i].nome){
            return false;
        }
    }

    //testa outros comandos que nao podem ser rotulos
    if ((token == "equ") || (token == "if") || (token == "macro") || (token == "end") ||
        (token == "space") || (token == "const") || (isInteger(token))){
        return false;
    }

    return true;
}

//Retorna 1 para rotulos de declaracao e 2 para chamadas de rotulo
//Se essa funcao for chamada, ja sabemos que se trata de um rotulo, portanto faz apenas o teste de ser declaracao
//se nao for,eh pq eh chamada
int Token::KindOfRotulo(std::string token){
    if (Token::have2points(token)){
        return 1;
    } else {
        return 2;
    }

}

//testa se o ultimo char da string eh ':', pois isso indica que ele eh uma declaracao de rotulo
bool Token::have2points(std::string token){
    char* ptr;
    ptr = &(token[0]);
    int tam = strlen(ptr);

    for(int i = 0; i < tam; i++){
        if ((token[i] == ':') &&(tam - i == 1)){
            return true;
        }
    }
    return false;
}

bool Token::isInteger(const std::string & aux)
{
   if(aux.empty() || ((!isdigit(aux[0])) && (aux[0] != '-') && (aux[0] != '+'))){
    return false;
   }

   char* ptr;
   strtol(aux.c_str(), &ptr, 10);

   return (*ptr == 0) ;
}<commit_msg>Deorecated function da classe token estão comentadas<commit_after>#include "../include/token.h"

//Declaracao do construtor da classe Token
Token::Token(std::string a){
    this -> nome = a;
    this -> type = token_type::undefined;
};

//Analisa se um determinado Token eh rotulo, tambem recebe a linha que esse token esta contido pra possiveis analises
bool Token::isRotulo(std::string token, std::string linha, std::vector<Mnemonic> instructionList){
    if (Token::have2points(token)){
        return true;
    }

    //algumas strings que queremos comparar, esta sendo feito assim pq de outras maneiras nao poderiamos ter um rotulo
    std::stringstream Line (linha);
    std::string aux;

    //pega o primeiro elemento da linha
    Line >> aux;

    //ve se a linha eh uma linha do tipo section
    if (aux == "section"){
        Line >> aux;
        if((aux == "data") || (aux == "text")){
            return false;
        }
    }

    //testa se eh uma instrucao
    for (int i = 0; i < instructionList.size(); i++){
        if (token == instructionList[i].nome){
            return false;
        }
    }

    //testa outros comandos que nao podem ser rotulos
    if ((token == "equ") || (token == "if") || (token == "macro") || (token == "end") ||
        (token == "space") || (token == "const") || (isInteger(token))){
        return false;
    }

    return true;
}

//Retorna 1 para rotulos de declaracao e 2 para chamadas de rotulo
//Se essa funcao for chamada, ja sabemos que se trata de um rotulo, portanto faz apenas o teste de ser declaracao
//se nao for,eh pq eh chamada
int Token::KindOfRotulo(std::string token){
    if (Token::have2points(token)){
        return 1;
    } else {
        return 2;
    }

}

//testa se o ultimo char da string eh ':', pois isso indica que ele eh uma declaracao de rotulo
bool Token::have2points(std::string token){
    char* ptr;
    ptr = &(token[0]);
    int tam = strlen(ptr);

    for(int i = 0; i < tam; i++){
        if ((token[i] == ':') &&(tam - i == 1)){
            return true;
        }
    }
    return false;
}

bool Token::isInteger(const std::string & aux)
{
   if(aux.empty() || ((!isdigit(aux[0])) && (aux[0] != '-') && (aux[0] != '+'))){
    return false;
   }

   char* ptr;
   strtol(aux.c_str(), &ptr, 10);

   return (*ptr == 0) ;
}

/* Podem ser úteis */
// // Função teste: extrair cada token do arquivo de entrada e escrevê-los de forma padrão na saída
// void Montador::tokenizar()
// {
//     //string de suporte para capturar os tokens
//     std::string aux;
//     //Loop para ler todas as linhas do codigo aberto e "tokenizar" elas (o token leva o : em consideracao ainda)
//     while (getline(this->fileText, aux)){
//         char* ptr;  //ponteiro de suporte para o funcionamento do strlen dentro da funcao minuscula
//         ptr = &(aux[0]);  //ponteiro apontando pro primeiro caracter da string
//         aux = Montador::minuscula (ptr);
//
//
//         std::stringstream lineStream (aux);
//         Token token(aux);
//
//         while (lineStream >> token.nome){
//             this->tokensList.push_back(token);
//         }
//     }
// }
//
// /* Imprime Tokens guardades em tokensList */
// void Montador::printTokens()
// {
//     if(this->tokensList.empty())
//     {
//         std::cout << "Token list empty" << '\n';
//         return;
//     }
//     for(size_t i = 0; i < tokensList.size(); i++)
//     {
//         std::cout << tokensList[i].nome << " " << '\n';
//     }
//     std::cout << '\n';
// }
//
// /* Escreve um arquivo de saida a partir de tokensList */
// void Montador::writeTokensToOutput()
// {
//     for(size_t i = 0; i < tokensList.size(); i++)
//     {
//         this->fileOutput << tokensList[i].nome << '\n';
//     }
//     this->fileOutput << std::endl;
// }
//
// //transforma toda a string em letras minusculas
// std::string Montador::minuscula (char* aux){
//     int tam = strlen (aux);
//
//     for (int i = 0; i < tam; i++){
//         aux[i] = (char) std::tolower(aux[i]);
//     }
//
//     return aux;
// }
<|endoftext|>


<commit_before>// Copyright (c) 2013 Plenluno All rights reserved.

#include <libj/trace.h>
#include <libj/glue/regexp.h>

#include <assert.h>
#include <cxxabi.h>
#include <dlfcn.h>
#include <stdio.h>

#include <vector>

static bool isEnabled = false;
static bool wasEnabled = false;

static void resume() {
    isEnabled = wasEnabled;
}

static void stop() {
    wasEnabled = isEnabled;
    isEnabled = false;
}

static std::string convert(const char* s) {
    assert(libj::glue::RegExp::encoding() == libj::glue::RegExp::UTF16);
    std::basic_string<uint16_t> s16;
    for (size_t i = 0; s[i]; i++) {
        s16 += static_cast<uint16_t>(s[i]);
    }
    return std::string(
        reinterpret_cast<const char*>(s16.c_str()),
        s16.length() << 1);
}

static libj::glue::RegExp* createRegExp(const char* pattern) {
    if (!isEnabled || !pattern) {
        return NULL;
    } else {
        return libj::glue::RegExp::create(convert(pattern), 0);
    }
}

static std::vector<libj::glue::RegExp*>* whiteList() {
    static std::vector<libj::glue::RegExp*> patterns;
    return &patterns;
}

static std::vector<libj::glue::RegExp*>* blackList() {
    static std::vector<libj::glue::RegExp*> patterns;
    return &patterns;
}

static void clear() {
    std::vector<libj::glue::RegExp*>::iterator itr;
    for (itr = whiteList()->begin(); itr != whiteList()->end(); itr++) {
        delete *itr;
    }
    whiteList()->clear();

    for (itr = blackList()->begin(); itr != blackList()->end(); itr++) {
        delete *itr;
    }
    blackList()->clear();
}

static bool isPrintable(const char* funcName) {
    if (!funcName) return false;

    std::string name = convert(funcName);
    std::vector<int> captures;
    std::vector<libj::glue::RegExp*>::const_iterator itr;

    for (itr = blackList()->begin(); itr != blackList()->end(); itr++) {
        if ((*itr)->execute(name, 0, captures)) {
            return false;
        }
    }

    for (itr = whiteList()->begin(); itr != whiteList()->end(); itr++) {
        if ((*itr)->execute(name, 0, captures)) {
            return true;
        }
    }

    return false;
}

static const char* addrToName(void* address) {
    Dl_info dli;
    if (dladdr(address, &dli)) {
        int status;
        return abi::__cxa_demangle(dli.dli_sname, 0, 0, &status);
    } else {
        return "<unknown>";
    }
}

extern "C" {
    void __cyg_profile_func_enter(void* funcAddress, void* callSite);
    void __cyg_profile_func_exit(void* funcAddress, void* callSite);
}

void __cyg_profile_func_enter(void* funcAddress, void* callSite) {
    if (!isEnabled || whiteList()->empty()) return;

    stop();

    const char* funcName = addrToName(funcAddress);
    if (isPrintable(funcName)) {
        printf("[LIBJ TRACE] enter: %s\n", funcName);
    }

    resume();
}

void __cyg_profile_func_exit(void* funcAddress, void* callSite) {
    if (!isEnabled || whiteList()->empty()) return;

    stop();

    const char* funcName = addrToName(funcAddress);
    if (isPrintable(funcName)) {
        printf("[LIBJ TRACE] exit:  %s\n", funcName);
    }

    resume();
}

namespace libj {
namespace trace {

void on() {
    if (!isEnabled) {
        assert(whiteList()->empty());
        assert(blackList()->empty());
        isEnabled = true;
    }
}

void off() {
    if (isEnabled) {
        isEnabled = false;
        clear();
    }
}

bool include(const char* pattern) {
    libj::glue::RegExp* re = createRegExp(pattern);
    if (re) {
        whiteList()->push_back(re);
        return true;
    } else {
        return false;
    }
}

bool exclude(const char* pattern) {
    libj::glue::RegExp* re = createRegExp(pattern);
    if (re) {
        blackList()->push_back(re);
        return true;
    } else {
        return false;
    }
}

}  // namespace trance
}  // namespace libj
<commit_msg>fix cppcheck errors<commit_after>// Copyright (c) 2013 Plenluno All rights reserved.

#include <libj/trace.h>
#include <libj/glue/regexp.h>

#include <assert.h>
#include <cxxabi.h>
#include <dlfcn.h>
#include <stdio.h>

#include <vector>

static bool isEnabled = false;
static bool wasEnabled = false;

static void resume() {
    isEnabled = wasEnabled;
}

static void stop() {
    wasEnabled = isEnabled;
    isEnabled = false;
}

static std::string convert(const char* s) {
    assert(libj::glue::RegExp::encoding() == libj::glue::RegExp::UTF16);
    std::basic_string<uint16_t> s16;
    for (size_t i = 0; s[i]; i++) {
        s16 += static_cast<uint16_t>(s[i]);
    }
    return std::string(
        reinterpret_cast<const char*>(s16.c_str()),
        s16.length() << 1);
}

static libj::glue::RegExp* createRegExp(const char* pattern) {
    if (!isEnabled || !pattern) {
        return NULL;
    } else {
        return libj::glue::RegExp::create(convert(pattern), 0);
    }
}

static std::vector<libj::glue::RegExp*>* whiteList() {
    static std::vector<libj::glue::RegExp*> patterns;
    return &patterns;
}

static std::vector<libj::glue::RegExp*>* blackList() {
    static std::vector<libj::glue::RegExp*> patterns;
    return &patterns;
}

static void clear() {
    std::vector<libj::glue::RegExp*>::iterator itr;
    for (itr = whiteList()->begin(); itr != whiteList()->end(); ++itr) {
        delete *itr;
    }
    whiteList()->clear();

    for (itr = blackList()->begin(); itr != blackList()->end(); ++itr) {
        delete *itr;
    }
    blackList()->clear();
}

static bool isPrintable(const char* funcName) {
    if (!funcName) return false;

    std::string name = convert(funcName);
    std::vector<int> captures;
    std::vector<libj::glue::RegExp*>::const_iterator itr;

    for (itr = blackList()->begin(); itr != blackList()->end(); ++itr) {
        if ((*itr)->execute(name, 0, captures)) {
            return false;
        }
    }

    for (itr = whiteList()->begin(); itr != whiteList()->end(); ++itr) {
        if ((*itr)->execute(name, 0, captures)) {
            return true;
        }
    }

    return false;
}

static const char* addrToName(void* address) {
    Dl_info dli;
    if (dladdr(address, &dli)) {
        int status;
        return abi::__cxa_demangle(dli.dli_sname, 0, 0, &status);
    } else {
        return "<unknown>";
    }
}

extern "C" {
    void __cyg_profile_func_enter(void* funcAddress, void* callSite);
    void __cyg_profile_func_exit(void* funcAddress, void* callSite);
}

void __cyg_profile_func_enter(void* funcAddress, void* callSite) {
    if (!isEnabled || whiteList()->empty()) return;

    stop();

    const char* funcName = addrToName(funcAddress);
    if (isPrintable(funcName)) {
        printf("[LIBJ TRACE] enter: %s\n", funcName);
    }

    resume();
}

void __cyg_profile_func_exit(void* funcAddress, void* callSite) {
    if (!isEnabled || whiteList()->empty()) return;

    stop();

    const char* funcName = addrToName(funcAddress);
    if (isPrintable(funcName)) {
        printf("[LIBJ TRACE] exit:  %s\n", funcName);
    }

    resume();
}

#ifdef LIBJ_DEBUG

namespace libj {
namespace trace {

void on() {
    if (!isEnabled) {
        assert(whiteList()->empty());
        assert(blackList()->empty());
        isEnabled = true;
    }
}

void off() {
    if (isEnabled) {
        isEnabled = false;
        clear();
    }
}

bool include(const char* pattern) {
    libj::glue::RegExp* re = createRegExp(pattern);
    if (re) {
        whiteList()->push_back(re);
        return true;
    } else {
        return false;
    }
}

bool exclude(const char* pattern) {
    libj::glue::RegExp* re = createRegExp(pattern);
    if (re) {
        blackList()->push_back(re);
        return true;
    } else {
        return false;
    }
}

#endif  // LIBJ_DEBUG

}  // namespace trance
}  // namespace libj
<|endoftext|>


<commit_before>#include <cv.h>
// #include <highgui.h>
#include "opencv2/highgui/highgui.hpp"

IplImage* imgTracking;
int lastX = -1;
int lastY = -1;

//This function threshold the HSV image and create a binary image
IplImage* GetThresholdedImage(IplImage* imgHSV) {
    IplImage* imgThresh=cvCreateImage(cvGetSize(imgHSV),IPL_DEPTH_8U, 1);
    cvInRangeS(imgHSV, cvScalar(170,160,60), cvScalar(180,2556,256), imgThresh);
    return imgThresh;
}

void trackObject(IplImage* imgThresh) {
    // Calculate the moments of 'imgThresh'
    CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
    cvMoments(imgThresh, moments, 1);
    double moment10 = cvGetSpatialMoment(moments, 1, 0);
    double moment01 = cvGetSpatialMoment(moments, 0, 1);
    double area = cvGetCentralMoment(moments, 0, 0);

     // if the area<1000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
    if(area>1000) {
        // calculate the position of the ball
        int posX = moment10/area;
        int posY = moment01/area;

       if(lastX>=0 && lastY>=0 && posX>=0 && posY>=0) {
            // Draw a yellow line from the previous point to the current point
            cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,0,255), 4);
        }

        lastX = posX;
        lastY = posY;
    }

     free(moments);
}

int main() {
    CvCapture* capture =0;
    capture = cvCaptureFromCAM(0);
    if(!capture) {
       printf("Capture failure\n");
       return -1;
    }

    IplImage* frame=0;
    frame = cvQueryFrame(capture);
    if(!frame) return -1;

   //create a blank image and assigned to 'imgTracking' which has the same size of original video
   imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
   cvZero(imgTracking); //covert the image, 'imgTracking' to black

   cvNamedWindow("Video");
   cvNamedWindow("Ball");

      //iterate through each frames of the video
   while(true) {
      frame = cvQueryFrame(capture);
      if(!frame) break;
      frame=cvCloneImage(frame);

      cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

      IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
      cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
      IplImage* imgThresh = GetThresholdedImage(imgHSV);

      cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

      //track the possition of the ball
      trackObject(imgThresh);

      // Add the tracking image and the frame
      cvAdd(frame, imgTracking, frame);

      cvShowImage("Ball", imgThresh);
      cvShowImage("Video", frame);

         //Clean up used images
      cvReleaseImage(&imgHSV);
      cvReleaseImage(&imgThresh);
      cvReleaseImage(&frame);

      //Wait 10mS
      int c = cvWaitKey(10);
      //If 'ESC' is pressed, break the loop
      if((char)c==27 ) break;
    }

    cvDestroyAllWindows();
    cvReleaseImage(&imgTracking);
    cvReleaseCapture(&capture);

    return 0;
}
<commit_msg>tracker<commit_after>#include <cv.h>
// #include <highgui.h>
#include <opencv2/highgui/highgui.hpp>

// g++ track.cpp -I /usr/include/opencv `pkg-config --cflags --libs opencv`

IplImage* imgTracking;
int lastX = -1;
int lastY = -1;

//This function threshold the HSV image and create a binary image
IplImage* GetThresholdedImage(IplImage* imgHSV) {
    IplImage* imgThresh=cvCreateImage(cvGetSize(imgHSV),IPL_DEPTH_8U, 1);
    cvInRangeS(imgHSV, cvScalar(170,160,60), cvScalar(180,2556,256), imgThresh);
    return imgThresh;
}

void trackObject(IplImage* imgThresh) {
    // Calculate the moments of 'imgThresh'
    CvMoments *moments = (CvMoments*)malloc(sizeof(CvMoments));
    cvMoments(imgThresh, moments, 1);
    double moment10 = cvGetSpatialMoment(moments, 1, 0);
    double moment01 = cvGetSpatialMoment(moments, 0, 1);
    double area = cvGetCentralMoment(moments, 0, 0);

     // if the area<1000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
    if(area>1000) {
        // calculate the position of the ball
        int posX = moment10/area;
        int posY = moment01/area;

       if(lastX>=0 && lastY>=0 && posX>=0 && posY>=0) {
            // Draw a yellow line from the previous point to the current point
            cvLine(imgTracking, cvPoint(posX, posY), cvPoint(lastX, lastY), cvScalar(0,0,255), 4);
        }

        lastX = posX;
        lastY = posY;
    }

     free(moments);
}

int main() {
    CvCapture* capture =0;
    capture = cvCaptureFromCAM(0);
    if(!capture) {
       printf("Capture failure\n");
       return -1;
    }

    IplImage* frame=0;
    frame = cvQueryFrame(capture);
    if(!frame) return -1;

   //create a blank image and assigned to 'imgTracking' which has the same size of original video
   imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3);
   cvZero(imgTracking); //covert the image, 'imgTracking' to black

   cvNamedWindow("Video");
   cvNamedWindow("Ball");

      //iterate through each frames of the video
   while(true) {
      frame = cvQueryFrame(capture);
      if(!frame) break;
      frame=cvCloneImage(frame);

      cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel

      IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3);
      cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV
      IplImage* imgThresh = GetThresholdedImage(imgHSV);

      cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel

      //track the possition of the ball
      trackObject(imgThresh);

      // Add the tracking image and the frame
      cvAdd(frame, imgTracking, frame);

      cvShowImage("Ball", imgThresh);
      cvShowImage("Video", frame);

         //Clean up used images
      cvReleaseImage(&imgHSV);
      cvReleaseImage(&imgThresh);
      cvReleaseImage(&frame);

      //Wait 10mS
      int c = cvWaitKey(10);
      //If 'ESC' is pressed, break the loop
      if((char)c==27 ) break;
    }

    cvDestroyAllWindows();
    cvReleaseImage(&imgTracking);
    cvReleaseCapture(&capture);

    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file uncle.cpp
 * @brief Purpose: Contains uncle's methods.
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 */

#include "../include/uncle.hpp"
#include "../include/platform.hpp"
#include "../include/little_girl.hpp"
#include <stdlib.h>

using namespace mindscape;

/**
 * @brief Initializes Uncle enemy.
 *
 * Constructor responsible to initialize Uncle in game.
 *
 * @param name Object's name.
 * @param position X and Y axis positions.
 * @param priority Rendering priority object.
 */

Uncle::Uncle(
  		std::string name,
  		std::pair<int, int> position,
  		int priority
	):Enemy(
    	name,
    	position,
    	priority,
    	100
  	){
    	initialize_state_map();
    	initialize_hitboxes();
    	initialize_animations();
    	initialize_audio_effects();
	};

/**
 * @brief Initialize uncle's audio effects.
 *
 * Not implemented.
 *
 * @return void.
 */

void Uncle::initialize_audio_effects() {
}

/**
 * @brief Initialize Uncle's animations.
 *
 * Define Uncle's movement and attack animation.
 *
 * @return void.
 */

void Uncle::initialize_animations() {
  	engine::Animation* idle_animation = nullptr;
    idle_animation = create_animation(
      	"../assets/images/sprites/enemies/uncle/uncle_idle.png",
      	1, 4, 3.0, "LEFT"
    );

  	idle_animation->set_values(
      	std::make_pair(665, 484),
      	std::make_pair(665, 484),
      	std::make_pair(0, 0)
    );

  	engine::Animation* attacking_animation = nullptr;
    attacking_animation = create_animation(
     	"../assets/images/sprites/enemies/uncle/uncle_attacking.png",
      	1, 1, 3.0, "LEFT"
    );

  	attacking_animation->set_values(
      	std::make_pair(719, 523),
      	std::make_pair(719, 523),
      	std::make_pair(0, 0)
    );

  	attacking_animation->in_loop = false;

  	add_animation("idle_animation",idle_animation);
 	add_animation("attacking_animation",attacking_animation);
  	idle_animation->activate();
  	set_actual_animation(idle_animation);
}

/**
 * @brief Creates Uncle's animation.
 *
 * Creates an animation to Uncle enemy.
 *
 * @param path Path to the image which contains the sprite sheet.
 * @param sprite_lines Number of the lines on the sprite sheet.
 * @param sprite_colums Number of colums on the sprite sheet.
 * @param duration Time duration of animation.
 * @param direction Direction of animation.
 * @return This method returns Uncle's animation.
 */

engine::Animation* Uncle::create_animation(
	std::string path,
  	int sprite_lines,
  	int sprite_columns,
  	double duration,
  	std::string direction) {

  	engine::Game& game = engine::Game::get_instance();

    engine::Animation* animation = nullptr;
    animation = new engine::Animation(
    	game.get_renderer(),
    	path,
    	false,
    	std::make_pair(0, 0),
    	1,
    	sprite_lines,
    	sprite_columns,
    	duration,
    	true,
    	direction
  	);

  	animation->set_values(
    	std::make_pair(320, 320),
    	std::make_pair(320, 320),
    	std::make_pair(0, 0)
  	);

  	return animation;
}

/**
 * @brief Initialize Uncle's hitboxes.
 *
 * Initializes Uncle instance hitboxes.
 *
 * @return void.
 */

void Uncle::initialize_hitboxes() {
  	engine::Game& game = engine::Game::get_instance();

    engine::Hitbox* head_hitbox = nullptr;
    head_hitbox = new engine::Hitbox(
    	"head_hitbox",
    	this->get_position(),
    	std::make_pair(160, 380),
    	std::make_pair(180,20),
    	game.get_renderer()
  	);

  	add_component(head_hitbox);
}

/**
 * @brief Initialize Uncle's state map.
 *
 * Initialize all possibles states for the Uncle.
 *
 * @return void.
 */

void Uncle::initialize_state_map() {
  	states.set_state("ACTION_STATE","NORMAL");
}

/**
 * @brief Register game events.
 *
 * Register an event to Uncle.
 *
 * @param game_event Triggering in-game events.
 * @return void.
 */

void Uncle::on_event(GameEvent game_event) {
  	std::string event_name = "";
    event_name = game_event.game_event_name;

  	if (event_name == "MOVE_LEFT"
  		&& !engine::GameObject::on_limit_of_level) {

    	set_position_x(get_position_x() + 10);
  	}
  	else if (event_name == "MOVE_RIGHT"
  		&& !engine::GameObject::on_limit_of_level) {

    	set_position_x(get_position_x() - 10);
  	}
}

/**
 * @brief Notify if the object is in the range.
 *
 * Notify if there is an object in the Uncle's range.
 *
 * @param game_object The game object passed in notification, in this case,
 * the girl.
 * @return void.
 */

void Uncle::notify(engine::Observable *game_object) {
  	LittleGirl* little_girl = nullptr;
    little_girl = dynamic_cast<LittleGirl *>(game_object);

    if (little_girl) {
    	attack(little_girl);
  	}
}

/**
 * @brief Uncle's attack.
 *
 * This method define Uncle's state while is attacking, is on attack or
 * while is dying.
 *
 * @param little_girl Object to be attacked.
 * @return void.
 */

void Uncle::attack(engine::GameObject* little_girl) {
  	std::string actual_action_state = "";
    actual_action_state = get_state("ACTION_STATE");

  	if (actual_action_state == "DYING") {
  		return;
  	}

  	if (actual_action_state == "ON_ATTACK"
  		|| actual_action_state == "ATTACKING") {

    	if (get_actual_animation()->is_finished) {
      		states.set_state("ACTION_STATE","NORMAL");
      		set_actual_animation(animations["idle_animation"]);
    	}
    	else {
      		return;
    	}
  	}
}

/**
 * @brief Define a basic attack.
 *
 * Method not implemented.
 *
 * @return void.
 */

void Uncle::basic_attack(){
}

/**
 * @brief Define action when is on attack.
 *
 * Event called when Uncle is attacking.
 *
 * @param game_object Object to be attacked.
 * @return void.
 */

void Uncle::on_attack(engine::GameObject *game_object) {
  	states.set_state("ACTION_STATE","ON_ATTACK");

  	hit(game_object, 1);
  	if (is_alive()) {
    	set_actual_animation(animations["on_attack_animation"]);
    	//play_song("hit_me");
  	}
}

/**
 * @brief Death method.
 *
 * This method define an animation when Uncle is dead.
 *
 * @param game_object Uncle.
 * @return void.
 */

void Uncle::die(engine::GameObject *game_object) {
  	std::string actual_x_state = "";
    actual_x_state = get_state("X_STATE");

    states.set_state("ACTION_STATE", "DYING");
  	set_actual_animation(animations["dying_animation"]);
  	//play_song("hit_me");
}

/**
 * @brief Event for the collision.
 *
 * Method called everytime when two game objects collides.
 *
 * @param other Other game object that collides.
 * @param p_my_hitbox Hitbox that receives the collision.
 * @param p_other_hitbox Hitbox that collided.
 * @return void.
 */

void Uncle::on_collision(
	engine::GameObject* other,
	engine::Hitbox* p_my_hitbox,
	engine::Hitbox* p_other_hitbox) {

  	LittleGirl* little_girl = nullptr;
    little_girl = dynamic_cast<LittleGirl *>(other);

  	engine::Hitbox* my_hitbox = nullptr;
    my_hitbox = dynamic_cast<engine::Hitbox *>(p_my_hitbox);

  	engine::Hitbox* other_hitbox = nullptr;
    other_hitbox = dynamic_cast<engine::Hitbox *>(p_other_hitbox);

  	if (little_girl
  		&& little_girl->get_state("ACTION_STATE") == "ATTACKING"
  		&& my_hitbox->get_name() == "head_hitbox"
  		&& little_girl->get_actual_animation()->actual_column == 2
     	&& get_state("X_STATE") != little_girl->get_state("X_STATE")) {

      	if(get_state("ACTION_STATE") == "ON_ATTACK") {
      		return;
      	}
	    else {
	    	on_attack(other);
  		}
  	}
}<commit_msg>[LOG] Applies log technique in Uncle.cpp<commit_after>/**
 * @file uncle.cpp
 * @brief Purpose: Contains uncle's methods.
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 */

#include "../include/uncle.hpp"
#include "../include/platform.hpp"
#include "../include/little_girl.hpp"
#include <stdlib.h>

using namespace mindscape;

/**
 * @brief Initializes Uncle enemy.
 *
 * Constructor responsible to initialize Uncle in game.
 *
 * @param name Object's name.
 * @param position X and Y axis positions.
 * @param priority Rendering priority object.
 */

Uncle::Uncle(
  		std::string name,
  		std::pair<int, int> position,
  		int priority
	):Enemy(
    	name,
    	position,
    	priority,
    	100
  	){
        /* Initialize all the characterists of the Uncle's boss. */
    	initialize_state_map();
    	initialize_hitboxes();
    	initialize_animations();
    	initialize_audio_effects();
	};

/**
 * @brief Initialize uncle's audio effects.
 *
 * Not implemented.
 *
 * @return void.
 */

void Uncle::initialize_audio_effects() {
}

/**
 * @brief Initialize Uncle's animations.
 *
 * Define Uncle's movement and attack animation.
 *
 * @return void.
 */

void Uncle::initialize_animations() {
    /* Starts debugger to accompany the method's development. */
    DEBUG("Initializing animations.");

  	engine::Animation* idle_animation = nullptr; /**< Animation.
    Animation that represents uncle's in a idle state.s */

    /* Creates uncle's idle animation. */
    idle_animation = create_animation(
      	"../assets/images/sprites/enemies/uncle/uncle_idle.png",
      	1, 4, 3.0, "LEFT"
    );

    /* Sets uncle's idle animation to define when its stopped. */
  	idle_animation->set_values(
      	std::make_pair(665, 484),
      	std::make_pair(665, 484),
      	std::make_pair(0, 0)
    );

    add_animation("idle_animation",idle_animation);

    idle_animation->activate();
  	set_actual_animation(idle_animation);

  	engine::Animation* attacking_animation = nullptr; /**< Animation.
    Animation that represents uncle's attacking. */

    /* Creates uncle's attack animation. */
    attacking_animation = create_animation(
     	"../assets/images/sprites/enemies/uncle/uncle_attacking.png",
      	1, 1, 3.0, "LEFT"
    );

    /* Sets uncle's attacking animation to define when its attacking. */
  	attacking_animation->set_values(
      	std::make_pair(719, 523),
      	std::make_pair(719, 523),
      	std::make_pair(0, 0)
    );

  	attacking_animation->in_loop = false;

 	add_animation("attacking_animation",attacking_animation);

    /* Ends debugger that represents the end of the method. */
    DEBUG("Animations initializated.");
}

/**
 * @brief Creates Uncle's animation.
 *
 * Creates an animation to Uncle enemy.
 *
 * @param path Path to the image which contains the sprite sheet.
 * @param sprite_lines Number of the lines on the sprite sheet.
 * @param sprite_colums Number of colums on the sprite sheet.
 * @param duration Time duration of animation.
 * @param direction Direction of animation.
 * @return This method returns Uncle's animation.
 */

engine::Animation* Uncle::create_animation(
	std::string path,
  	int sprite_lines,
  	int sprite_columns,
  	double duration,
  	std::string direction) {
    DEBUG("Creating animations.");

  	engine::Game& game = engine::Game::get_instance(); /**< Game.
    Gets an instance of a game just initializated. */

    engine::Animation* animation = nullptr; /**< Animation.
    Can represents all functions about uncle's animation. */

    /* Initializes uncle's animation object. */
    animation = new engine::Animation(
    	game.get_renderer(),
    	path,
    	false,
    	std::make_pair(0, 0),
    	1,
    	sprite_lines,
    	sprite_columns,
    	duration,
    	true,
    	direction
  	);

    /* Sets values to init a initial position of animation on the screen.*/
  	animation->set_values(
    	std::make_pair(320, 320),
    	std::make_pair(320, 320),
    	std::make_pair(0, 0)
  	);

    DEBUG("Animations created.");
  	return animation;
}

/**
 * @brief Initialize Uncle's hitboxes.
 *
 * Initializes Uncle instance hitboxes.
 *
 * @return void.
 */

void Uncle::initialize_hitboxes() {
    /* Starts debugger to accompany the method's development. */
    DEBUG("Initializing uncle's hitbox.");

  	engine::Game& game = engine::Game::get_instance(); /**< Game.
    Gets an instance of a game just initializated. */

    engine::Hitbox* head_hitbox = nullptr; /**< Hitbox.
    Initialize uncle's head hitbox. */

    head_hitbox = new engine::Hitbox(
    	"head_hitbox",
    	this->get_position(),
    	std::make_pair(160, 380),
    	std::make_pair(180,20),
    	game.get_renderer()
  	);

    /* Add hitbox component into the game object. */
  	add_component(head_hitbox);

    /* Ends debugger that represents the end of the method. */
    DEBUG("Uncle's hitbox initialized");
}

/**
 * @brief Initialize Uncle's state map.
 *
 * Initialize all possibles states for the Uncle.
 *
 * @return void.
 */

void Uncle::initialize_state_map() {
    /* Starts debugger to accompany the method's development. */
    DEBUG("Initializing uncle's state.");
  	states.set_state("ACTION_STATE","NORMAL");
    /* Ends debugger that represents the end of the method. */
    DEBUG("Uncle's state initialized.");
}

/**
 * @brief Register game events.
 *
 * Register an event to Uncle.
 *
 * @param game_event Triggering in-game events.
 * @return void.
 */

void Uncle::on_event(GameEvent game_event) {
  	std::string event_name = "";
    event_name = game_event.game_event_name;

  	if (event_name == "MOVE_LEFT"
  		&& !engine::GameObject::on_limit_of_level) {

    	set_position_x(get_position_x() + 10);
  	}
  	else if (event_name == "MOVE_RIGHT"
  		&& !engine::GameObject::on_limit_of_level) {

    	set_position_x(get_position_x() - 10);
  	}
}

/**
 * @brief Notify if the object is in the range.
 *
 * Notify if there is an object in the Uncle's range.
 *
 * @param game_object The game object passed in notification, in this case,
 * the girl.
 * @return void.
 */

void Uncle::notify(engine::Observable *game_object) {
  	LittleGirl* little_girl = nullptr;
    little_girl = dynamic_cast<LittleGirl *>(game_object);

    if (little_girl) {
    	attack(little_girl);
  	}
}

/**
 * @brief Uncle's attack.
 *
 * This method define Uncle's state while is attacking, is on attack or
 * while is dying.
 *
 * @param little_girl Object to be attacked.
 * @return void.
 */

void Uncle::attack(engine::GameObject* little_girl) {
    DEBUG("The uncle is attacking.");

  	std::string actual_action_state = ""; /**< String.
    Gets the actual state of the uncle. */
    actual_action_state = get_state("ACTION_STATE");

  	if (actual_action_state == "DYING") {
        INFO("The Uncle is dying.");
  		return;
  	}

  	if (actual_action_state == "ON_ATTACK"
  		|| actual_action_state == "ATTACKING") {

    	if (get_actual_animation()->is_finished) {
      		states.set_state("ACTION_STATE","NORMAL");
      		set_actual_animation(animations["idle_animation"]);
    	}
    	else {
      		return;
    	}
  	}
}

/**
 * @brief Define a basic attack.
 *
 * Method not implemented.
 *
 * @return void.
 */

void Uncle::basic_attack(){
}

/**
 * @brief Define action when is on attack.
 *
 * Event called when Uncle is attacking.
 *
 * @param game_object Object to be attacked.
 * @return void.
 */

void Uncle::on_attack(engine::GameObject *game_object) {
  	states.set_state("ACTION_STATE","ON_ATTACK");

  	hit(game_object, 1);
  	if (is_alive()) {
    	set_actual_animation(animations["on_attack_animation"]);
    	//play_song("hit_me");
  	}
}

/**
 * @brief Death method.
 *
 * This method define an animation when Uncle is dead.
 *
 * @param game_object Uncle.
 * @return void.
 */

void Uncle::die(engine::GameObject *game_object) {
    DEBUG("The uncle is dying.");
  	std::string actual_x_state = ""; /**< String.
    Gets the actual state of the uncle. */
    actual_x_state = get_state("X_STATE");

    /* Sets a state that represents when uncle is dead. */
    states.set_state("ACTION_STATE", "DYING");
    /* Initiates the animation that show the uncle dying.*/
  	set_actual_animation(animations["dying_animation"]);
  	//play_song("hit_me");
    DEBUG("The uncle died.");
}

/**
 * @brief Event for the collision.
 *
 * Method called everytime when two game objects collides.
 *
 * @param other Other game object that collides.
 * @param p_my_hitbox Hitbox that receives the collision.
 * @param p_other_hitbox Hitbox that collided.
 * @return void.
 */

void Uncle::on_collision(
	engine::GameObject* other,
	engine::Hitbox* p_my_hitbox,
	engine::Hitbox* p_other_hitbox) {

  	LittleGirl* little_girl = nullptr;
    little_girl = dynamic_cast<LittleGirl *>(other);

  	engine::Hitbox* my_hitbox = nullptr;
    my_hitbox = dynamic_cast<engine::Hitbox *>(p_my_hitbox);

  	engine::Hitbox* other_hitbox = nullptr;
    other_hitbox = dynamic_cast<engine::Hitbox *>(p_other_hitbox);

  	if (little_girl
  		&& little_girl->get_state("ACTION_STATE") == "ATTACKING"
  		&& my_hitbox->get_name() == "head_hitbox"
  		&& little_girl->get_actual_animation()->actual_column == 2
     	&& get_state("X_STATE") != little_girl->get_state("X_STATE")) {

      	if(get_state("ACTION_STATE") == "ON_ATTACK") {
      		return;
      	}
	    else {
	    	on_attack(other);
  		}
  	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "utils.hpp"

#include <boost/filesystem.hpp>
#include <cctype>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <qi/os.hpp>
#include <qi/qi.hpp>

static char rand_alnum()
{
  unsigned char c;
  while (!std::isalnum(c = static_cast<unsigned char>(std::rand())))
    ;
  return c;
}

std::string randomstr(std::string::size_type sz) {

  std::string s;
  s.reserve(sz);
  //need to have different seeds to avoid DDOS attack
  qi::os::timeval tv;
  qi::os::gettimeofday(&tv);
  srand(tv.tv_sec + tv.tv_usec);
  generate_n(std::back_inserter(s), sz, rand_alnum);
  return s;
}

std::wstring wrandomstr(std::wstring::size_type sz) {
  std::wstring s;
  s.reserve(sz);
  //need to have different seeds to avoid DDOS attack
  qi::os::timeval tv;
  qi::os::gettimeofday(&tv);
  srand(tv.tv_sec + tv.tv_usec);
  generate_n(std::back_inserter(s), sz, rand_alnum);
  return s;
}

std::string fsconcat(const std::string &p0,
                     const std::string &p1,
                     const std::string &p2,
                     const std::string &p3,
                     const std::string &p4,
                     const std::string &p5)
{
  boost::filesystem::path p(p0, qi::unicodeFacet());
  p.append(p1, qi::unicodeFacet());
  p.append(p2, qi::unicodeFacet());
  p.append(p3, qi::unicodeFacet());
  p.append(p4, qi::unicodeFacet());
  p.append(p5, qi::unicodeFacet());

  return p.make_preferred().string(qi::unicodeFacet());
}
<commit_msg>Fix isalnum not depending of the locale<commit_after>/*
 * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include "utils.hpp"

#include <boost/filesystem.hpp>
#include <cctype>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <qi/os.hpp>
#include <qi/qi.hpp>

static char rand_alnum()
{
  unsigned char c;
  while (true)
  {
    c = static_cast<unsigned char>(std::rand());
    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
      return c;
  }
}

std::string randomstr(std::string::size_type sz) {

  std::string s;
  s.reserve(sz);
  //need to have different seeds to avoid DDOS attack
  qi::os::timeval tv;
  qi::os::gettimeofday(&tv);
  srand(tv.tv_sec + tv.tv_usec);
  generate_n(std::back_inserter(s), sz, rand_alnum);
  return s;
}

std::wstring wrandomstr(std::wstring::size_type sz) {
  std::wstring s;
  s.reserve(sz);
  //need to have different seeds to avoid DDOS attack
  qi::os::timeval tv;
  qi::os::gettimeofday(&tv);
  srand(tv.tv_sec + tv.tv_usec);
  generate_n(std::back_inserter(s), sz, rand_alnum);
  return s;
}

std::string fsconcat(const std::string &p0,
                     const std::string &p1,
                     const std::string &p2,
                     const std::string &p3,
                     const std::string &p4,
                     const std::string &p5)
{
  boost::filesystem::path p(p0, qi::unicodeFacet());
  p.append(p1, qi::unicodeFacet());
  p.append(p2, qi::unicodeFacet());
  p.append(p3, qi::unicodeFacet());
  p.append(p4, qi::unicodeFacet());
  p.append(p5, qi::unicodeFacet());

  return p.make_preferred().string(qi::unicodeFacet());
}
<|endoftext|>


<commit_before>#ifndef VOLE_VALUE
#define VOLE_VALUE

#include "slice.hpp"

namespace Vole {

  struct Value;
  using String = Slice<char>;
  using Vector = Slice<Value>;

  struct Value {
    enum Type {
      BOOLEAN,
      NUMBER,
      // SYMBOL,
      STRING,
      // REGEXP,
      VECTOR,
      // MAPPING
    } type;

    union Content {
      bool    boolean;
      double  number;
      // wrapper around a String, every symbol with a name is unique
      // Symbol  symbol;
      String  string;
      // Regexp regexp;
      Vector  vector;
      // Mapping mapping;

      Content()                       { }
      Content(bool b)    : boolean(b) { }
      Content(double d)  : number(d)  { }
      // Content(Symbol s)  : symbol(s)  { }
      Content(String s)  : string(s)  { }
      Content(Vector v)  : vector(v)  { }
      // Content(Mapping m) : mapping(m) { }
    } content;

    Value() { }

    template <typename T>
    Value(T thing, Color c = BLACK);

    template <typename IOS>
    IOS& serialize(IOS& ios);

    operator std::string();
  };

  template <>
  Value::Value(bool b, Color c)
  : type(BOOLEAN), color(c), content(b)
  { }

  template <>
  Value::Value(double d, Color c)
  : type(NUMBER), color(c), content(d)
  { }

  template <>
  Value::Value(String s, Color c)
  : type(STRING), color(c), content(s)
  { }

  template <>
  Value::Value(Vector v, Color c)
  : type(VECTOR), color(c), content(v)
  { }

  template <typename IOS>
  IOS& Value::serialize(IOS& ios) {
    switch (type) {
      case BOOLEAN: {
        ios << (content.boolean ? "#t" : "#f");
      } break;
      case NUMBER: {
        ios << content.number;
      } break;
      case STRING: {
        ios << content.string;
      } break;
      case VECTOR: {
        ios << content.vector;
      } break;
    }
    return ios;
  }

  template <typename IOS>
  IOS& operator<<(IOS& ios, Value val) {
    return val.serialize(ios);
  }

  Value::operator std::string() {
    std::stringstream ss;
    serialize(ss);
    return ss.str();
  }

}

#endif<commit_msg>whoops, forgot one<commit_after>#ifndef VOLE_VALUE
#define VOLE_VALUE

#include "slice.hpp"

namespace Vole {

  struct Value;
  using String = Slice<char>;
  using Vector = Slice<Value>;

  struct Value {
    enum Type {
      BOOLEAN,
      NUMBER,
      // SYMBOL,
      STRING,
      // REGEXP,
      VECTOR,
      // MAPPING
    } type;

    union Content {
      bool    boolean;
      double  number;
      // wrapper around a String, every symbol with a name is unique
      // Symbol  symbol;
      String  string;
      // Regexp regexp;
      Vector  vector;
      // Mapping mapping;

      Content()                       { }
      Content(bool b)    : boolean(b) { }
      Content(double d)  : number(d)  { }
      // Content(Symbol s)  : symbol(s)  { }
      Content(String s)  : string(s)  { }
      // Content(Regexp r)  : regexp(r)  { }
      Content(Vector v)  : vector(v)  { }
      // Content(Mapping m) : mapping(m) { }
    } content;

    Value() { }

    template <typename T>
    Value(T thing, Color c = BLACK);

    template <typename IOS>
    IOS& serialize(IOS& ios);

    operator std::string();
  };

  template <>
  Value::Value(bool b, Color c)
  : type(BOOLEAN), color(c), content(b)
  { }

  template <>
  Value::Value(double d, Color c)
  : type(NUMBER), color(c), content(d)
  { }

  template <>
  Value::Value(String s, Color c)
  : type(STRING), color(c), content(s)
  { }

  template <>
  Value::Value(Vector v, Color c)
  : type(VECTOR), color(c), content(v)
  { }

  template <typename IOS>
  IOS& Value::serialize(IOS& ios) {
    switch (type) {
      case BOOLEAN: {
        ios << (content.boolean ? "#t" : "#f");
      } break;
      case NUMBER: {
        ios << content.number;
      } break;
      case STRING: {
        ios << content.string;
      } break;
      case VECTOR: {
        ios << content.vector;
      } break;
    }
    return ios;
  }

  template <typename IOS>
  IOS& operator<<(IOS& ios, Value val) {
    return val.serialize(ios);
  }

  Value::operator std::string() {
    std::stringstream ss;
    serialize(ss);
    return ss.str();
  }

}

#endif<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif

#include "config.h"

#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>

#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"

VideoProperties::VideoProperties()
    : id(""),          link(""),      host(""),    domain(""),
      formats("flv"),  title(""),     length(0),   initial(0),
      contentType(""), suffix("flv"), filename(""),pageLink("")
{
}

void
VideoProperties::setId(const std::string& id) {
    this->id = id;
}

void
VideoProperties::setLink(std::string link) {
    this->link = curlmgr.unescape(link);
}

void
VideoProperties::setHost(const std::string& host) {
    this->host = host;
}

void
VideoProperties::setDomain(const std::string& domain) {
    this->domain = domain;
}

void
VideoProperties::setFormats(const std::string& formats) {
    this->formats = formats;
}

void
VideoProperties::setLength(const double length) {
    this->length = length;
}

void
VideoProperties::setPageLink(const std::string& link) {
    this->pageLink = link;
}

void
VideoProperties::setContentType(const std::string& contentType) {
    this->contentType = contentType;

    std::string::size_type pos = contentType.find("/");

    if (pos != std::string::npos) {
        suffix = contentType.substr(pos+1);
        // set to "flv" for these:
        if (suffix.find("octet") != std::string::npos
            || suffix.find("plain") != std::string::npos)
        {
            suffix = "flv";
        }
        Util::subStrReplace(suffix, "x-", "");
    }
}

void
VideoProperties::setInitial(const double initial) {
    this->initial = initial;
}

void
VideoProperties::setTitle(const std::string& title) {
    this->title = title;
}

const std::string&
VideoProperties::getId() const {
    return id;
}

const std::string&
VideoProperties::getLink() const {
    return link;
}

const std::string&
VideoProperties::getHost() const {
    return host;
}

const std::string&
VideoProperties::getDomain() const {
    return domain;
}

const std::string&
VideoProperties::getFormats() const {
    return formats;
}

const std::string&
VideoProperties::getTitle() const {
    return title;
}

const double
VideoProperties::getLength() const {
    return length;
}

const std::string&
VideoProperties::getPageLink() const {
    return pageLink;
}

const double
VideoProperties::getInitial() const {
    return initial;
}

const std::string&
VideoProperties::getContentType() const {
    return contentType;
}

const std::string&
VideoProperties::getFilename() const {
    return filename;
}

static int video_num;

void
VideoProperties::formatOutputFilename() {

    Options opts = optsmgr.getOptions();

    if (!opts.output_video_given) {
        std::stringstream b;

        if (opts.number_videos_given) {
            b << std::setw(4)
              << std::setfill('0')
              << ++video_num
              << "_";
        }

        if (!opts.filename_format_given)
            defaultOutputFilenameFormatter(b);
        else
            customOutputFilenameFormatter(b);

        filename = b.str();

        for (register int i=1; i<INT_MAX; ++i) {
            initial = Util::fileExists(filename);

            if (initial == 0)
                break;
            else if (initial == length)
                throw NothingToDoException();
            else {
                if (opts.continue_given)
                    break;
            }
            std::stringstream tmp;
            tmp << b.str() << "." << i;
            filename = tmp.str();
        }
    }
    else {
        initial = Util::fileExists(opts.output_video_arg);
        if (initial == length)
            throw NothingToDoException();
        filename = opts.output_video_arg;
    }

    if (!opts.continue_given)
        initial = 0;
}

void
VideoProperties::defaultOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    if (opts.title_given && title.length() > 0)
        b << title;
    else {
        Util::subStrReplace(id, "-", "_");
        b << host << "_" << id;
    }

    b << "." << suffix;
}

void
VideoProperties::customOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    std::string fmt = opts.filename_format_arg;
    std::string _title = id;
#ifdef WITH_PERL
    if (opts.title_given && title.length() > 0)
        _title = title;
#endif
    Util::subStrReplace(fmt, "%t", _title);
    Util::subStrReplace(fmt, "%i", id);
    Util::subStrReplace(fmt, "%h", host);
    Util::subStrReplace(fmt, "%s", suffix);

    b << fmt;
}

VideoProperties::
    NothingToDoException::NothingToDoException()
    : RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<commit_msg>Fix: swf -> flv file suffix.<commit_after>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * cclive is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif

#include "config.h"

#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>

#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"

VideoProperties::VideoProperties()
    : id(""),          link(""),      host(""),    domain(""),
      formats("flv"),  title(""),     length(0),   initial(0),
      contentType(""), suffix("flv"), filename(""),pageLink("")
{
}

void
VideoProperties::setId(const std::string& id) {
    this->id = id;
}

void
VideoProperties::setLink(std::string link) {
    this->link = curlmgr.unescape(link);
}

void
VideoProperties::setHost(const std::string& host) {
    this->host = host;
}

void
VideoProperties::setDomain(const std::string& domain) {
    this->domain = domain;
}

void
VideoProperties::setFormats(const std::string& formats) {
    this->formats = formats;
}

void
VideoProperties::setLength(const double length) {
    this->length = length;
}

void
VideoProperties::setPageLink(const std::string& link) {
    this->pageLink = link;
}

void
VideoProperties::setContentType(const std::string& contentType) {
    this->contentType = contentType;

    std::string::size_type pos = contentType.find("/");

    if (pos != std::string::npos) {
        suffix = contentType.substr(pos+1);
        // set to "flv" for these:
        if (suffix.find("octet") != std::string::npos
            || suffix.find("swf") != std::string::npos
            || suffix.find("plain") != std::string::npos)
        {
            suffix = "flv";
        }
        Util::subStrReplace(suffix, "x-", "");
    }
}

void
VideoProperties::setInitial(const double initial) {
    this->initial = initial;
}

void
VideoProperties::setTitle(const std::string& title) {
    this->title = title;
}

const std::string&
VideoProperties::getId() const {
    return id;
}

const std::string&
VideoProperties::getLink() const {
    return link;
}

const std::string&
VideoProperties::getHost() const {
    return host;
}

const std::string&
VideoProperties::getDomain() const {
    return domain;
}

const std::string&
VideoProperties::getFormats() const {
    return formats;
}

const std::string&
VideoProperties::getTitle() const {
    return title;
}

const double
VideoProperties::getLength() const {
    return length;
}

const std::string&
VideoProperties::getPageLink() const {
    return pageLink;
}

const double
VideoProperties::getInitial() const {
    return initial;
}

const std::string&
VideoProperties::getContentType() const {
    return contentType;
}

const std::string&
VideoProperties::getFilename() const {
    return filename;
}

static int video_num;

void
VideoProperties::formatOutputFilename() {

    Options opts = optsmgr.getOptions();

    if (!opts.output_video_given) {
        std::stringstream b;

        if (opts.number_videos_given) {
            b << std::setw(4)
              << std::setfill('0')
              << ++video_num
              << "_";
        }

        if (!opts.filename_format_given)
            defaultOutputFilenameFormatter(b);
        else
            customOutputFilenameFormatter(b);

        filename = b.str();

        for (register int i=1; i<INT_MAX; ++i) {
            initial = Util::fileExists(filename);

            if (initial == 0)
                break;
            else if (initial == length)
                throw NothingToDoException();
            else {
                if (opts.continue_given)
                    break;
            }
            std::stringstream tmp;
            tmp << b.str() << "." << i;
            filename = tmp.str();
        }
    }
    else {
        initial = Util::fileExists(opts.output_video_arg);
        if (initial == length)
            throw NothingToDoException();
        filename = opts.output_video_arg;
    }

    if (!opts.continue_given)
        initial = 0;
}

void
VideoProperties::defaultOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    if (opts.title_given && title.length() > 0)
        b << title;
    else {
        Util::subStrReplace(id, "-", "_");
        b << host << "_" << id;
    }

    b << "." << suffix;
}

void
VideoProperties::customOutputFilenameFormatter(
    std::stringstream& b)
{
    Options opts = optsmgr.getOptions();
    std::string fmt = opts.filename_format_arg;
    std::string _title = id;
#ifdef WITH_PERL
    if (opts.title_given && title.length() > 0)
        _title = title;
#endif
    Util::subStrReplace(fmt, "%t", _title);
    Util::subStrReplace(fmt, "%i", id);
    Util::subStrReplace(fmt, "%h", host);
    Util::subStrReplace(fmt, "%s", suffix);

    b << fmt;
}

VideoProperties::
    NothingToDoException::NothingToDoException()
    : RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<|endoftext|>