<commit_before>#include "isect2d.h"
#include "vec2.h"

#include <iostream>
#include <cmath>
#include <vector>
#include <memory>
#include <random>
#include <stack>

#include <GLFW/glfw3.h>
#include "../../tangram-es/core/include/glm/glm/glm.hpp"
//#include "../../tangram-es/core/include/glm/glm/gtx/norm.hpp"
#include "glm_vec.h"

//#define CIRCLES
#define N_CIRCLES 500

#define AREA
#define N_BOX 1000

GLFWwindow* window;
float width = 800;
float height = 600;
float dpiRatio = 1;

bool pause = false;

using Vec2 = glm::vec2;
//using Vec2 = isect2d::Vec2;

using OBB = isect2d::OBB<Vec2>;
using AABB = isect2d::AABB<Vec2>;

std::vector<OBB> obbs;

float rand_0_1(float scale) {
    return ((float)rand() / (float)(RAND_MAX)) * scale;
}

void update() {
    double time = glfwGetTime();

    if(!pause) {
        int i = 0;

        for (auto& obb : obbs) {
            float r1 = rand_0_1(10);
            float r2 = rand_0_1(20);
            float r3 = rand_0_1(M_PI);

            auto centroid = obb.getCentroid();

            if (++i % 2 == 0) {
                obb.move(centroid.x, centroid.y + .02 * cos(time * 0.25) * r2);
                obb.rotate(cos(r3) * 0.1 + obb.getAngle());
            } else {
                obb.move(centroid.x + 0.1 * cos(time) * r1, centroid.y);
                obb.rotate(cos(r2) * 0.1 + obb.getAngle());
            }
        }
    }
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if(key == 'P' && action == GLFW_PRESS) {
        pause = !pause;
    }
}

void initBBoxes() {

#if defined CIRCLES
    int n = N_BOX;
    float o = (2 * M_PI) / n;
    float size = 200;
    float boxSize = n / (0.4 * n);

    for (int i = 0; i < n; ++i) {
        float r = rand_0_1(20);

        obbs.push_back(OBB(cos(o * i) * size + width / 2,
                    sin(o * i) * size + height / 2, r,
                    r + boxSize * 8, r * boxSize / 3 + boxSize));
    }
#elif defined AREA
    int n = N_BOX;
    float boxSize = 5;

    std::default_random_engine generator;
    std::uniform_real_distribution<double> xDistribution(-350.0,350.0);
    std::uniform_real_distribution<double> yDistribution(-250.0,250.0);
    std::uniform_real_distribution<double> boxScaleDist(-2.0f,2.0f);
    for(int i = 0; i < n; i++) {
        float boxSizeFactorW = boxScaleDist(generator);
        float boxSizeFactorH = boxScaleDist(generator);
        float xVal = xDistribution(generator) + width/2.0f;
        float yVal = yDistribution(generator) + height/2.0f;
        float angle = yVal/(xVal+1.0f);
        obbs.push_back(OBB(xVal, yVal, angle+M_PI*i/4,
                           boxSize-boxSizeFactorW,
                           boxSize-boxSizeFactorH));
    }
#else
    int n = 4;
    float o = (2 * M_PI) / n;
    float size = 50;
    float boxSize = 15;

    for (int i = 0; i < n; ++i) {
        float r = rand_0_1(20);

        obbs.push_back(OBB(cos(o * i) * size + width / 2,
                    sin(o * i) * size + height / 2, r,
                    r + boxSize * 8, r * boxSize / 3 + boxSize));
    }
#endif

}

void init() {
    glfwInit();

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    window = glfwCreateWindow(width, height, "isect2d", NULL, NULL);

    if (!window) {
        glfwTerminate();
    }

    int fbWidth, fbHeight;
    glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
    glfwSetKeyCallback(window, keyCallback);

    dpiRatio = fbWidth / width;

    glfwMakeContextCurrent(window);

    initBBoxes();
}

void line(float sx, float sy, float ex, float ey) {
    glBegin(GL_LINES);
    glVertex2f(sx, sy);
    glVertex2f(ex, ey);
    glEnd();
}

void cross(float x, float y, float size = 3) {
    line(x - size, y, x + size, y);
    line(x, y - size, x, y + size);
}

void drawAABB(const AABB& _aabb) {
    line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMin().x, _aabb.getMax().y);
    line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMin().y);
    line(_aabb.getMax().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMax().y);
    line(_aabb.getMin().x, _aabb.getMax().y, _aabb.getMax().x, _aabb.getMax().y);
}

void drawOBB(const OBB& obb, bool isect) {
    const auto* quad = obb.getQuad();

    for(int i = 0; i < 4; ++i) {
        if(isect) {
            glColor4f(0.5, 1.0, 0.5, 1.0);
        } else {
            glColor4f(1.0, 0.5, 0.5, 1.0);
        }

        auto start = quad[i];
        auto end = quad[(i + 1) % 4];

        line(start.x, start.y, end.x, end.y);

        glColor4f(1.0, 1.0, 1.0, 0.1);
        cross(obb.getCentroid().x, obb.getCentroid().y, 2);
    }
}

void render() {

    const int n1 = 4;
    const int n2 = 16;

    ISect2D<Vec2> context({n2, n2}, {800, 600});

    while (!glfwWindowShouldClose(window)) {
        update();

        if (pause) {
            glfwPollEvents();
            continue;
        }

        glViewport(0, 0, width * dpiRatio, height * dpiRatio);
        glClearColor(0.18f, 0.18f, 0.22f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, width, 0, height, -1, 1);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        for (auto& obb : obbs) {
            drawOBB(obb, false);
        }

        float sum1 = 0, sum2 = 0;

        // grid broad phase
        std::vector<AABB> aabbs;
        std::set<std::pair<int, int>> pairs;
        {
            for (auto& obb : obbs) {
                auto aabb = obb.getExtent();
                aabb.m_userData = (void*)&obb;
                aabbs.push_back(aabb);
            }

            const clock_t beginBroadPhaseTime = clock();

            pairs = intersect(aabbs, {n1, n1}, {800, 600});

            float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;

            // narrow phase
            clock_t beginNarrowTime = clock();

            for (auto pair : pairs) {

                auto obb1 = obbs[pair.first];
                auto obb2 = obbs[pair.second];

                intersect(obb1, obb2);
            }
            float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;

            std::cout << "grid1: " << broadTime << "\t" << narrowTime <<"ms "  << "pairs: " << pairs.size() << std::endl;

            sum1 = broadTime + narrowTime;
        }

        // grid broad phase
        {
            std::vector<AABB> aabbs;
            for (auto& obb : obbs) {
                auto aabb = obb.getExtent();
                aabb.m_userData = (void*)&obb;
                aabbs.push_back(aabb);
            }

            const clock_t beginBroadPhaseTime = clock();
            context.clear();

            context.intersect(aabbs);

            float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;

            // narrow phase
            clock_t beginNarrowTime = clock();

            for (auto pair : context.pairs) {

                auto obb1 = obbs[pair.first];
                auto obb2 = obbs[pair.second];

                intersect(obb1, obb2);
            }
            float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;

            std::cout << "grid2: " << broadTime << "\t" << narrowTime <<"ms "  << "pairs: " << context.pairs.size() << std::endl;

            sum2 = broadTime + narrowTime;

        }

        std::cout << "sum: " << sum1 <<" | " << sum2 << "  diff: " << (sum1 - sum2) << "ms"<< std::endl;

        // narrow phase
        {
            clock_t narrowTime = 0;

            for (auto pair : context.pairs) {
                clock_t beginNarrowTime;

                auto obb1 = obbs[pair.first];
                auto obb2 = obbs[pair.second];

                // narrow phase
                beginNarrowTime = clock();
                bool isect = intersect(obb1, obb2);
                narrowTime += (clock() - beginNarrowTime);

                if (isect) {
                    drawOBB(obb1, true);
                    drawOBB(obb2, true);

                    line(obb1.getCentroid().x, obb1.getCentroid().y, obb2.getCentroid().x, obb2.getCentroid().y);
                }
            }

            //std::cout << " / narrowphase: " << (float(narrowTime) / CLOCKS_PER_SEC) * 1000 << "ms" << std::endl;
        }

        glfwSwapBuffers(window);

        glfwPollEvents();
    }
}

int main() {

    init();
    render();

    return 0;
}
<commit_msg>cleanups<commit_after>#include "isect2d.h"
#include "vec2.h"

#include <iostream>
#include <cmath>
#include <vector>
#include <memory>
#include <random>
#include <stack>

#include <GLFW/glfw3.h>
#include "../../tangram-es/core/include/glm/glm/glm.hpp"
#include "glm_vec.h"

//#define CIRCLES
#define N_CIRCLES 500

#define AREA
#define N_BOX 1000

GLFWwindow* window;
float width = 800;
float height = 600;
float dpiRatio = 1;

bool pause = false;

using Vec2 = glm::vec2;
//using Vec2 = isect2d::Vec2;

using OBB = isect2d::OBB<Vec2>;
using AABB = isect2d::AABB<Vec2>;

std::vector<OBB> obbs;

float rand_0_1(float scale) {
    return ((float)rand() / (float)(RAND_MAX)) * scale;
}

void update() {
    double time = glfwGetTime();

    if(!pause) {
        int i = 0;

        for (auto& obb : obbs) {
            float r1 = rand_0_1(10);
            float r2 = rand_0_1(20);
            float r3 = rand_0_1(M_PI);

            auto centroid = obb.getCentroid();

            if (++i % 2 == 0) {
                obb.move(centroid.x, centroid.y + .02 * cos(time * 0.25) * r2);
                obb.rotate(cos(r3) * 0.1 + obb.getAngle());
            } else {
                obb.move(centroid.x + 0.1 * cos(time) * r1, centroid.y);
                obb.rotate(cos(r2) * 0.1 + obb.getAngle());
            }
        }
    }
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if(key == 'P' && action == GLFW_PRESS) {
        pause = !pause;
    }
}

void initBBoxes() {

#if defined CIRCLES
    int n = N_BOX;
    float o = (2 * M_PI) / n;
    float size = 200;
    float boxSize = n / (0.4 * n);

    for (int i = 0; i < n; ++i) {
        float r = rand_0_1(20);

        obbs.push_back(OBB(cos(o * i) * size + width / 2,
                    sin(o * i) * size + height / 2, r,
                    r + boxSize * 8, r * boxSize / 3 + boxSize));
    }
#elif defined AREA
    int n = N_BOX;
    float boxWidth = 30;
    float boxHeight = 5;

    std::default_random_engine generator;
    std::uniform_real_distribution<double> xDistribution(-350.0,350.0);
    std::uniform_real_distribution<double> yDistribution(-250.0,250.0);
    std::uniform_real_distribution<double> boxScaleDist(-2.0f,2.0f);
    for(int i = 0; i < n; i++) {
        float boxSizeFactorW = boxScaleDist(generator);
        float boxSizeFactorH = boxScaleDist(generator);
        float xVal = xDistribution(generator) + width/2.0f;
        float yVal = yDistribution(generator) + height/2.0f;
        float angle = yVal/(xVal+1.0f);
        obbs.push_back(OBB(xVal, yVal, angle+M_PI*i/4,
                           boxWidth-boxSizeFactorW,
                           boxHeight-boxSizeFactorH));
    }
#else
    int n = 10;
    float o = (2 * M_PI) / n;
    float size = 50;
    float boxSize = 15;

    for (int i = 0; i < n; ++i) {
        float r = rand_0_1(20);

        obbs.push_back(OBB(cos(o * i) * size + width / 2,
                    sin(o * i) * size + height / 2, r,
                    r + boxSize * 8, r * boxSize / 3 + boxSize));
    }
#endif

}

void init() {
    glfwInit();

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    window = glfwCreateWindow(width, height, "isect2d", NULL, NULL);

    if (!window) {
        glfwTerminate();
    }

    int fbWidth, fbHeight;
    glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
    glfwSetKeyCallback(window, keyCallback);

    dpiRatio = fbWidth / width;

    glfwMakeContextCurrent(window);

    initBBoxes();
}

void line(float sx, float sy, float ex, float ey) {
    glBegin(GL_LINES);
    glVertex2f(sx, sy);
    glVertex2f(ex, ey);
    glEnd();
}

void cross(float x, float y, float size = 3) {
    line(x - size, y, x + size, y);
    line(x, y - size, x, y + size);
}

void drawAABB(const AABB& _aabb) {
    line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMin().x, _aabb.getMax().y);
    line(_aabb.getMin().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMin().y);
    line(_aabb.getMax().x, _aabb.getMin().y, _aabb.getMax().x, _aabb.getMax().y);
    line(_aabb.getMin().x, _aabb.getMax().y, _aabb.getMax().x, _aabb.getMax().y);
}

void drawOBB(const OBB& obb, bool isect) {
    const auto* quad = obb.getQuad();

    for(int i = 0; i < 4; ++i) {
        if(isect) {
            glColor4f(0.5, 1.0, 0.5, 1.0);
        } else {
            glColor4f(1.0, 0.5, 0.5, 1.0);
        }

        auto start = quad[i];
        auto end = quad[(i + 1) % 4];

        line(start.x, start.y, end.x, end.y);

        glColor4f(1.0, 1.0, 1.0, 0.1);
        cross(obb.getCentroid().x, obb.getCentroid().y, 2);
    }
}

void render() {

    const int n1 = 4;
    const int n2 = 16;

    ISect2D<Vec2> context({n2, n2}, {800, 600});

    while (!glfwWindowShouldClose(window)) {
        update();

        if (pause) {
            glfwPollEvents();
            continue;
        }

        glViewport(0, 0, width * dpiRatio, height * dpiRatio);
        glClearColor(0.18f, 0.18f, 0.22f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, width, 0, height, -1, 1);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        for (auto& obb : obbs) {
            drawOBB(obb, false);
        }

        float sum1 = 0, sum2 = 0;

        // grid broad phase
        std::vector<AABB> aabbs;
        std::set<std::pair<int, int>> pairs;
        {
            for (auto& obb : obbs) {
                auto aabb = obb.getExtent();
                aabb.m_userData = (void*)&obb;
                aabbs.push_back(aabb);
            }

            const clock_t beginBroadPhaseTime = clock();

            pairs = intersect(aabbs, {n1, n1}, {800, 600});

            float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;

            // narrow phase
            clock_t beginNarrowTime = clock();

            for (auto& pair : pairs) {
                intersect(obbs[pair.first], obbs[pair.first]);
            }
            float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;

            std::cout << "grid1: " << broadTime << "\t" << narrowTime <<"ms "
                      << "pairs: " << pairs.size() << std::endl;

            sum1 = broadTime + narrowTime;
        }

        // grid broad phase
        {
            std::vector<AABB> aabbs;
            for (auto& obb : obbs) {
                auto aabb = obb.getExtent();
                aabb.m_userData = (void*)&obb;
                aabbs.push_back(aabb);
            }

            const clock_t beginBroadPhaseTime = clock();
            context.clear();

            context.intersect(aabbs);

            float broadTime = (float(clock() - beginBroadPhaseTime) / CLOCKS_PER_SEC) * 1000;

            // narrow phase
            clock_t beginNarrowTime = clock();

            for (auto& pair : context.pairs) {
                intersect(obbs[pair.first], obbs[pair.first]);
            }
            float narrowTime = (float(clock() - beginNarrowTime) / CLOCKS_PER_SEC) * 1000;

            std::cout << "grid2: " << broadTime << "\t" << narrowTime <<"ms "
                      << "pairs: " << context.pairs.size() << std::endl;

            sum2 = broadTime + narrowTime;

        }

        std::cout << "sum: " << sum1 <<" | " << sum2 << "  diff: " << (sum1 - sum2) << "ms"<< std::endl;

        // narrow phase
        {
            for (auto& pair : context.pairs) {
                auto obb1 = obbs[pair.first];
                auto obb2 = obbs[pair.second];

                bool isect = intersect(obb1, obb2);

                if (isect) {
                    drawOBB(obb1, true);
                    drawOBB(obb2, true);

                    line(obb1.getCentroid().x, obb1.getCentroid().y,
                         obb2.getCentroid().x, obb2.getCentroid().y);
                }
            }
        }

        glfwSwapBuffers(window);

        glfwPollEvents();
    }
}

int main() {

    init();
    render();

    return 0;
}
<|endoftext|>


<commit_before>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>

using namespace uuidxx;
using namespace std;

template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
     std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
     return a;
}

bool TestEquality()
{
	bool result = true;

	uuid test1, test2;

	auto passTest = [&](bool reverse = false) {
		if ((test1.ToString() != test2.ToString()) ^ reverse)
		{
			cout << "FAIL!" << endl;
			cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
			result = false;
		}
		else
		{
			cout << "pass" << endl;
		}
	};

	cout << "Testing equality of normal GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	passTest();

	cout << "Testing equality of lower- vs upper-cased GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
	passTest();

	cout << "Testing equality of braced vs non-braced GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
	passTest();

	cout << "Testing inequality of random GUIDs... ";
	test1 = uuid::Generate();
	test2 = uuid::Generate();
	passTest(true);

	return result;
}

bool InnerTestParsing(string test, string testCase, bool &result)
{
	cout << "Testing " << test << " parsing: " << testCase << "... ";
	uuid test1(testCase);
	string strValue = test1.ToString();
	if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
	{
		cout << "FAIL!" << endl;
		cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
		result = false;
		return false;
	}

	cout << "pass" << endl;
	return true;
}

bool TestParsing()
{
	bool result = true;

	InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
	InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
	InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
	InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
	InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
	InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);

	return result;
}

bool TestStringGeneration()
{
	bool result = true;

	uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");

	cout << "Testing generation of string without braces... ";
	if (test.ToString(false) == "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C")
	{
		cout << "pass" << endl;
	}
	else
	{
		cout << "FAIL!" << endl;
		result = false;
	}

	cout << "Testing generation of string without braces... ";
	if (test.ToString(true) == "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}")
	{
		cout << "pass" << endl;
	}
	else
	{
		cout << "FAIL!" << endl;
		result = false;
	}

	return true;
}

bool TestUniqueness()
{
	int rounds = 4096;
	cout << "Generating and testing uniqueness of " << rounds << " uuids... ";

	int collisions = 0;
	std::set<uuid> uuidMap;
	for (int i = 0; i < rounds; ++i)
	{
		auto test = uuid::Generate();
		if (uuidMap.insert(test).second == false)
		{
			++collisions;
		}
	}

	if (collisions == 0)
	{
		cout << "pass" << endl;
		return true;
	}
	else
	{
		cout << collisions << " collisions. FAIL!" << endl;
		return false;
	}
}

int main (int argc, char *argv[])
{
	auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);

	int fails = 0;
	for (auto test : tests)
	{
		if (!test())
		{
			++fails;
		}
	}

	return fails;
}
<commit_msg>Expanded test cases<commit_after>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>

using namespace uuidxx;
using namespace std;

template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
     std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
     return a;
}

bool TestEquality()
{
	bool result = true;

	uuid test1, test2;

	auto passTest = [&](bool reverse = false) {
		if ((test1 != test2) ^ reverse)
		{
			cout << "FAIL!" << endl;
			cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
			result = false;
		}
		else
		{
			cout << "pass" << endl;
		}
	};

	cout << "Testing assignment... ";
	test1 = uuid::Generate();
	test2 = test1;
	passTest();

	cout << "Testing move operator... ";
	test1 = uuid::Generate();
	test2 = std::move(test1);
	passTest(false);

	cout << "Testing equality of normal GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	passTest();

	cout << "Testing equality of lower- vs upper-cased GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
	passTest();

	cout << "Testing equality of braced vs non-braced GUIDs... ";
	test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
	test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
	passTest();

	cout << "Testing inequality of random GUIDs... ";
	test1 = uuid::Generate();
	test2 = uuid::Generate();
	passTest(true);

	return result;
}

bool InnerTestParsing(string test, string testCase, bool &result)
{
	cout << "Testing " << test << " parsing: " << testCase << "... ";
	uuid test1(testCase);
	string strValue = test1.ToString();
	if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
	{
		cout << "FAIL!" << endl;
		cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
		result = false;
		return false;
	}

	cout << "pass" << endl;
	return true;
}

bool TestParsing()
{
	bool result = true;

	InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
	InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
	InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
	InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
	InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
	InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);

	return result;
}

bool TestStringGeneration()
{
	bool result = true;

	uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");

	cout << "Testing generation of string without braces... ";
	if (test.ToString(false) == "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C")
	{
		cout << "pass" << endl;
	}
	else
	{
		cout << "FAIL!" << endl;
		result = false;
	}

	cout << "Testing generation of string without braces... ";
	if (test.ToString(true) == "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}")
	{
		cout << "pass" << endl;
	}
	else
	{
		cout << "FAIL!" << endl;
		result = false;
	}

	return true;
}

bool TestUniqueness()
{
	int rounds = 4096;
	cout << "Generating and testing uniqueness of " << rounds << " uuids... ";

	int collisions = 0;
	std::set<uuid> uuidMap;
	for (int i = 0; i < rounds; ++i)
	{
		auto test = uuid::Generate();
		if (uuidMap.insert(test).second == false)
		{
			++collisions;
		}
	}

	if (collisions == 0)
	{
		cout << "pass" << endl;
		return true;
	}
	else
	{
		cout << collisions << " collisions. FAIL!" << endl;
		return false;
	}
}

int main (int argc, char *argv[])
{
	auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);

	int fails = 0;
	for (auto test : tests)
	{
		if (!test())
		{
			++fails;
		}
	}

	return fails;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "schemas.h"

using namespace cm;
using namespace fnord;

namespace cm {

msg::MessageSchema joinedSessionsSchema() {
  Vector<msg::MessageSchemaField> fields;

  msg::MessageSchemaField queries(
      16,
      "queries",
      msg::FieldType::OBJECT,
      0,
      true,
      false);

  queries.fields.emplace_back(
      18,
      "time",
      msg::FieldType::UINT32,
      0xffffffff,
      false,
      false);

  queries.fields.emplace_back(
      1,
      "page",
      msg::FieldType::UINT32,
      100,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      2,
      "language",
      msg::FieldType::UINT32,
      kMaxLanguage,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      3,
      "query_string",
      msg::FieldType::STRING,
      8192,
      false,
      true);

  queries.fields.emplace_back(
      4,
      "query_string_normalized",
      msg::FieldType::STRING,
      8192,
      false,
      true);

  queries.fields.emplace_back(
      5,
      "num_items",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      6,
      "num_items_clicked",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      7,
      "num_ad_impressions",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      8,
      "num_ad_clicks",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      9,
      "ab_test_group",
      msg::FieldType::UINT32,
      100,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      10,
      "device_type",
      msg::FieldType::UINT32,
      kMaxDeviceType,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      11,
      "page_type",
      msg::FieldType::UINT32,
      kMaxPageType,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      12,
      "category1",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      13,
      "category2",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      14,
      "category3",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  msg::MessageSchemaField query_items(
      17,
      "items",
      msg::FieldType::OBJECT,
      0,
      true,
      false);

  query_items.fields.emplace_back(
      19,
      "position",
      msg::FieldType::UINT32,
      64,
      false,
      false,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      15,
      "clicked",
      msg::FieldType::BOOLEAN,
      0,
      false,
      false);

  query_items.fields.emplace_back(
      20,
      "item_id",
      msg::FieldType::STRING,
      1024,
      false,
      false);

  query_items.fields.emplace_back(
      21,
      "shop_id",
      msg::FieldType::STRING,
      250,
      false,
      true);

  query_items.fields.emplace_back(
      21,
      "shop_name",
      msg::FieldType::STRING,
      250,
      false,
      true);

  query_items.fields.emplace_back(
      22,
      "category1",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      23,
      "category2",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      24,
      "category3",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(query_items);
  fields.emplace_back(queries);

  return msg::MessageSchema("joined_session", fields);
}

}
<commit_msg>add fields to session schema<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "schemas.h"

using namespace cm;
using namespace fnord;

namespace cm {

msg::MessageSchema joinedSessionsSchema() {
  Vector<msg::MessageSchemaField> fields;

  fields.emplace_back(
      25,
      "num_items",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  fields.emplace_back(
      26,
      "num_items_clicked",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  fields.emplace_back(
      27,
      "num_ad_impressions",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  fields.emplace_back(
      28,
      "num_ad_clicks",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  fields.emplace_back(
      29,
      "num_queries",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  fields.emplace_back(
      30,
      "num_queries_clicked",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  msg::MessageSchemaField queries(
      16,
      "queries",
      msg::FieldType::OBJECT,
      0,
      true,
      false);

  queries.fields.emplace_back(
      18,
      "time",
      msg::FieldType::UINT32,
      0xffffffff,
      false,
      false);

  queries.fields.emplace_back(
      1,
      "page",
      msg::FieldType::UINT32,
      100,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      2,
      "language",
      msg::FieldType::UINT32,
      kMaxLanguage,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      3,
      "query_string",
      msg::FieldType::STRING,
      8192,
      false,
      true);

  queries.fields.emplace_back(
      4,
      "query_string_normalized",
      msg::FieldType::STRING,
      8192,
      false,
      true);

  queries.fields.emplace_back(
      5,
      "num_items",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      6,
      "num_items_clicked",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      7,
      "num_ad_impressions",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      8,
      "num_ad_clicks",
      msg::FieldType::UINT32,
      250,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      9,
      "ab_test_group",
      msg::FieldType::UINT32,
      100,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      10,
      "device_type",
      msg::FieldType::UINT32,
      kMaxDeviceType,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      11,
      "page_type",
      msg::FieldType::UINT32,
      kMaxPageType,
      false,
      false,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      12,
      "category1",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      13,
      "category2",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(
      14,
      "category3",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  msg::MessageSchemaField query_items(
      17,
      "items",
      msg::FieldType::OBJECT,
      0,
      true,
      false);

  query_items.fields.emplace_back(
      19,
      "position",
      msg::FieldType::UINT32,
      64,
      false,
      false,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      15,
      "clicked",
      msg::FieldType::BOOLEAN,
      0,
      false,
      false);

  query_items.fields.emplace_back(
      20,
      "item_id",
      msg::FieldType::STRING,
      1024,
      false,
      false);

  query_items.fields.emplace_back(
      21,
      "shop_id",
      msg::FieldType::STRING,
      250,
      false,
      true);

  query_items.fields.emplace_back(
      21,
      "shop_name",
      msg::FieldType::STRING,
      250,
      false,
      true);

  query_items.fields.emplace_back(
      22,
      "category1",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      23,
      "category2",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  query_items.fields.emplace_back(
      24,
      "category3",
      msg::FieldType::UINT32,
      0xffff,
      false,
      true,
      msg::EncodingHint::BITPACK);

  queries.fields.emplace_back(query_items);
  fields.emplace_back(queries);

  return msg::MessageSchema("joined_session", fields);
}

}
<|endoftext|>


<commit_before>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   test_return basic_test(memcached_st *memc);
   test_return increment_test(memcached_st *memc);
   test_return basic_master_key_test(memcached_st *memc);
   test_return mget_result_function(memcached_st *memc);
   test_return mget_test(memcached_st *memc);
   void *world_create(void);
   void world_destroy(void *p);
}

test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
static memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<commit_msg>Some more updates to the C++ test file to remove solaris warnings.<commit_after>/*
  C++ interface test
*/
#include "libmemcached/memcached.hh"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "server.h"

#include "test.h"

#include <string>

using namespace std;

extern "C" {
   test_return basic_test(memcached_st *memc);
   test_return increment_test(memcached_st *memc);
   test_return basic_master_key_test(memcached_st *memc);
   test_return mget_result_function(memcached_st *memc);
   test_return mget_test(memcached_st *memc);
   memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                     memcached_result_st *result __attribute__((unused)),
                                     void *context);
   void *world_create(void);
   void world_destroy(void *p);
}

test_return basic_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("This is some data");
  string value;
  size_t value_length;

  foo.set("mine", value_set, 0, 0);
  value= foo.get("mine", &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

test_return increment_test(memcached_st *memc)
{
  Memcached mcach(memc);
  bool rc;
  const string key("inctest");
  const string inc_value("1");
  string ret_value;
  uint64_t int_inc_value;
  uint64_t int_ret_value;
  size_t value_length;

  mcach.set(key, inc_value, 0, 0);
  ret_value= mcach.get(key, &value_length);
  printf("\nretvalue %s\n",ret_value.c_str());
  int_inc_value= uint64_t(atol(inc_value.c_str()));
  int_ret_value= uint64_t(atol(ret_value.c_str()));
  assert(int_ret_value == int_inc_value);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 2);

  rc= mcach.increment(key, 1, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 3);

  rc= mcach.increment(key, 5, &int_ret_value);
  assert(rc == true);
  assert(int_ret_value == 8);

  return TEST_SUCCESS;
}

test_return basic_master_key_test(memcached_st *memc)
{
  Memcached foo(memc);
  const string value_set("Data for server A");
  const string master_key_a("server-a");
  const string master_key_b("server-b");
  const string key("xyz");
  string value;
  size_t value_length;

  foo.set_by_key(master_key_a, key, value_set, 0, 0);
  value= foo.get_by_key(master_key_a, key, &value_length);

  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  value= foo.get_by_key(master_key_b, key, &value_length);
  assert((memcmp(value.c_str(), value_set.c_str(), value_length) == 0));

  return TEST_SUCCESS;
}

/* Count the results */
memcached_return callback_counter(memcached_st *ptr __attribute__((unused)),
                                  memcached_result_st *result __attribute__((unused)),
                                  void *context)
{
  unsigned int *counter= static_cast<unsigned int *>(context);

  *counter= *counter + 1;

  return MEMCACHED_SUCCESS;
}

test_return mget_result_function(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  string key1("fudge");
  string key2("son");
  string key3("food");
  vector<string> keys;
  keys.reserve(3);
  keys.push_back(key1);
  keys.push_back(key2);
  keys.push_back(key3);
  unsigned int counter;
  memcached_execute_function callbacks[1];

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  callbacks[0]= &callback_counter;
  counter= 0;
  rc= mc.fetch_execute(callbacks, static_cast<void *>(&counter), 1);

  assert(counter == 3);

  return TEST_SUCCESS;
}

test_return mget_test(memcached_st *memc)
{
  Memcached mc(memc);
  bool rc;
  memcached_return mc_rc;
  vector<string> keys;
  keys.reserve(3);
  keys.push_back("fudge");
  keys.push_back("son");
  keys.push_back("food");
  uint32_t flags;

  string return_key;
  size_t return_key_length;
  string return_value;
  size_t return_value_length;

  /* We need to empty the server before we continue the test */
  rc= mc.flush(0);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while (mc.fetch(return_key, return_value, &return_key_length,
                  &return_value_length, &flags, &mc_rc))
  {
    assert(return_value.length() != 0);
  }
  assert(return_value_length == 0);
  assert(mc_rc == MEMCACHED_END);

  rc= mc.set_all(keys, keys, 50, 9);
  assert(rc == true);

  rc= mc.mget(keys);
  assert(rc == true);

  while ((mc.fetch(return_key, return_value, &return_key_length,
                   &return_value_length, &flags, &mc_rc)))
  {
    assert(return_value.length() != 0);
    assert(mc_rc == MEMCACHED_SUCCESS);
    assert(return_key_length == return_value_length);
    assert(!memcmp(return_value.c_str(), return_key.c_str(), return_value_length));
  }

  return TEST_SUCCESS;
}

test_st tests[] ={
  { "basic", 0, basic_test },
  { "basic_master_key", 0, basic_master_key_test },
  { "increment_test", 0, increment_test },
  { "mget", 1, mget_test },
  { "mget_result_function", 1, mget_result_function },
  {0, 0, 0}
};

collection_st collection[] ={
  {"block", 0, 0, tests},
  {0, 0, 0, 0}
};

#define SERVERS_TO_CREATE 1

extern "C" void *world_create(void)
{
  server_startup_st *construct;

  construct= (server_startup_st *)malloc(sizeof(server_startup_st));
  memset(construct, 0, sizeof(server_startup_st));

  construct->count= SERVERS_TO_CREATE;
  server_startup(construct);

  return construct;
}

void world_destroy(void *p)
{
  server_startup_st *construct= static_cast<server_startup_st *>(p);
  memcached_server_st *servers=
    static_cast<memcached_server_st *>(construct->servers);
  memcached_server_list_free(servers);

  server_shutdown(construct);
  free(construct);
}

void get_world(world_st *world)
{
  world->collections= collection;
  world->create= world_create;
  world->destroy= world_destroy;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

#include "filefinder.h"
#include "options.h"
#include "query_string.h"
#include "terminal.h"

std::vector<node> files;

std::vector<node> search(query_string qstr){
  std::vector<node> result;

  std::string str(qstr.get_str());
  if( str != ""){
    int count = 1;
    for(std::size_t i=0; i < files.size() && count <=options.number_of_result_lines; ++i){
      if(files[i].filename.find(qstr.get_str()) != std::string::npos){
        result.push_back(files[i]);
        count++;
      }
    }
  }

  return result;
}

int main(int argc, char* argv[]){
  if(!get_options(argc, argv)){
    return 1;
  }
  if(options.show_help){
    print_help();
    return 0;
  }
  if(options.show_version){
    print_version();
    return 0;
  }

  find_files(files);

  query_string qstr;

  terminal term;
  int c;

  unsigned selected = 0;
  std::vector<node> results;
  term.print_search_line(qstr.get_str(),qstr.get_pos());
  while(1){
    c = getchar();
    if(c == 27){ // esc
      c=getchar();
      if(c == '['){
        c=getchar();
        if(c == 'A'){ // up
          if(selected > 0){
            selected--;
          }
          term.print_result(term, results, selected);
          term.restore_cursor_pos();
          term.cursor_right(qstr.get_pos()+1);
        }else if(c == 'B'){ // down
          selected++;
          if(selected > results.size()-1){
            selected = results.size()-1;
          }
          term.print_result(term, results, selected);
          term.restore_cursor_pos();
          term.cursor_right(qstr.get_pos()+1);
        }else if(c == 'C'){ // right
          if(qstr.cursor_right()){
            term.cursor_right();
          }
        }else if(c == 'D'){ // left
          if(qstr.cursor_left()){
            term.cursor_left();
          }
        }
      }
    }else if(c == 9){
      // tab
    }else if(c == 10){ // enter
      fprintf(stderr,"\n");
      return 0;
    }else if(c == 127){ //backspace
      qstr.remove();
      term.print_search_line(qstr.get_str(),qstr.get_pos());
      results = search(qstr);
      term.print_result(term, results, selected);
      term.restore_cursor_pos();
      term.cursor_right(qstr.get_pos()+1);
    }else{
      qstr.add(c);
      term.print_search_line(qstr.get_str(),qstr.get_pos());
      results = search(qstr);
      term.print_result(term, results, selected);
      term.restore_cursor_pos();
      term.cursor_right(qstr.get_pos()+1);
    }
  }
}
<commit_msg>Move selection if selected is out of range.<commit_after>#include <cstdio>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

#include "filefinder.h"
#include "options.h"
#include "query_string.h"
#include "terminal.h"

std::vector<node> files;

std::vector<node> search(query_string qstr){
  std::vector<node> result;

  std::string str(qstr.get_str());
  if( str != ""){
    int count = 1;
    for(std::size_t i=0; i < files.size() && count <=options.number_of_result_lines; ++i){
      if(files[i].filename.find(qstr.get_str()) != std::string::npos){
        result.push_back(files[i]);
        count++;
      }
    }
  }

  return result;
}

int main(int argc, char* argv[]){
  if(!get_options(argc, argv)){
    return 1;
  }
  if(options.show_help){
    print_help();
    return 0;
  }
  if(options.show_version){
    print_version();
    return 0;
  }

  find_files(files);

  query_string qstr;

  terminal term;
  int c;

  unsigned selected = 0;
  std::vector<node> results;
  term.print_search_line(qstr.get_str(),qstr.get_pos());
  while(1){
    c = getchar();
    if(c == 27){ // esc
      c=getchar();
      if(c == '['){
        c=getchar();
        if(c == 'A'){ // up
          if(selected > 0){
            selected--;
          }
          term.print_result(term, results, selected);
          term.restore_cursor_pos();
          term.cursor_right(qstr.get_pos()+1);
        }else if(c == 'B'){ // down
          selected++;
          if(selected > results.size()-1){
            selected = results.size()-1;
          }
          term.print_result(term, results, selected);
          term.restore_cursor_pos();
          term.cursor_right(qstr.get_pos()+1);
        }else if(c == 'C'){ // right
          if(qstr.cursor_right()){
            term.cursor_right();
          }
        }else if(c == 'D'){ // left
          if(qstr.cursor_left()){
            term.cursor_left();
          }
        }
      }
    }else if(c == 9){
      // tab
    }else if(c == 10){ // enter
      if(results.size()!=0){

      }
      fprintf(stderr,"\n");
      return 0;
    }else if(c == 127){ //backspace
      qstr.remove();
      term.print_search_line(qstr.get_str(),qstr.get_pos());
      results = search(qstr);
      if(selected >= results.size()){
        selected = results.size()-1;
      }
      if(results.size()==0){
        selected = 0;
      }
      term.print_result(term, results, selected);
      term.restore_cursor_pos();
      term.cursor_right(qstr.get_pos()+1);
    }else{
      qstr.add(c);
      term.print_search_line(qstr.get_str(),qstr.get_pos());
      results = search(qstr);
      if(selected >= results.size()){
        selected = results.size()-1;
      }
      if(results.size()==0){
        selected = 0;
      }
      term.print_result(term, results, selected);
      term.restore_cursor_pos();
      term.cursor_right(qstr.get_pos()+1);
    }
  }
}
<|endoftext|>


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

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

#include "ldapaccess.hxx"

#include "ldapuserprof.hxx"

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif // _RTL_STRBUF_HXX_

namespace extensions { namespace config { namespace ldap {

//------------------------------------------------------------------------------
typedef int LdapErrCode;
//------------------------------------------------------------------------------
struct LdapMessageHolder
{
    LdapMessageHolder() : msg(0) {}
    ~LdapMessageHolder() { if (msg) ldap_msgfree(msg); }

    LDAPMessage * msg;

private:
    LdapMessageHolder(LdapMessageHolder const&);
    void operator=(LdapMessageHolder const&);
};
//------------------------------------------------------------------------------
LdapConnection::~LdapConnection()
{
    if (isValid()) disconnect();
}
//------------------------------------------------------------------------------

void LdapConnection::disconnect()
{
    if (mConnection != NULL)
    {
        ldap_unbind_s(mConnection) ;
        mConnection = NULL;
    }
}
//------------------------------------------------------------------------------

static void checkLdapReturnCode(const sal_Char *aOperation,
                                LdapErrCode aRetCode,
                                LDAP * /*aConnection*/)
{
    if (aRetCode == LDAP_SUCCESS) { return ; }

    static const sal_Char *kNoSpecificMessage = "No additional information" ;
    rtl::OUStringBuffer message ;

    if (aOperation != NULL)
    {
        message.appendAscii(aOperation).appendAscii(": ") ;
    }
    message.appendAscii(ldap_err2string(aRetCode)).appendAscii(" (") ;
    sal_Char *stub = NULL ;

#ifndef LDAP_OPT_SIZELIMIT // for use with OpenLDAP
    ldap_get_lderrno(aConnection, NULL, &stub) ;
#endif
    if (stub != NULL)
    {
        message.appendAscii(stub) ;
        // It would seem the message returned is actually
        // not a copy of a string but rather some static
        // string itself. At any rate freeing it seems to
        // cause some undue problems at least on Windows.
        // This call is thus disabled for the moment.
        //ldap_memfree(stub) ;
    }
    else { message.appendAscii(kNoSpecificMessage) ; }
    message.appendAscii(")") ;
    throw ldap::LdapGenericException(message.makeStringAndClear(),
                                     NULL, aRetCode) ;
}
//------------------------------------------------------------------------------
void  LdapConnection::connectSimple(const LdapDefinition& aDefinition)
   throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    OSL_ENSURE(!isValid(), "Recoonecting an LDAP connection that is already established");
    if (isValid()) disconnect();

    mLdapDefinition = aDefinition;
    connectSimple();
}
//------------------------------------------------------------------------------
void  LdapConnection::connectSimple()
   throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid())
    {
        // Connect to the server
        initConnection() ;
        // Set Protocol V3
        int version = LDAP_VERSION3;
        ldap_set_option(mConnection,
                        LDAP_OPT_PROTOCOL_VERSION,
                        &version);

#ifdef LDAP_X_OPT_CONNECT_TIMEOUT // OpenLDAP doesn't support this and the func
        /* timeout is specified in milliseconds -> 4 seconds*/
        int timeout = 4000;
        ldap_set_option( mConnection,
                        LDAP_X_OPT_CONNECT_TIMEOUT,
                        &timeout );
#endif

        // Do the bind
        LdapErrCode retCode = ldap_simple_bind_s(mConnection,
                                               mLdapDefinition.mAnonUser ,
                                               mLdapDefinition.mAnonCredentials) ;

        checkLdapReturnCode("SimpleBind", retCode, mConnection) ;
    }
}
//------------------------------------------------------------------------------
void LdapConnection::initConnection()
    throw (ldap::LdapConnectionException)
{
    if (mLdapDefinition.mServer.getLength() == 0)
    {
        rtl::OUStringBuffer message ;

        message.appendAscii("Cannot initialise connection to LDAP: No server specified.") ;
        throw ldap::LdapConnectionException(message.makeStringAndClear(), NULL) ;
    }

    if (mLdapDefinition.mPort == 0) mLdapDefinition.mPort = LDAP_PORT;

    mConnection = ldap_init(mLdapDefinition.mServer,
                            mLdapDefinition.mPort) ;
    if (mConnection == NULL)
    {
        rtl::OUStringBuffer message ;

        message.appendAscii("Cannot initialise connection to LDAP server ") ;
        message.appendAscii(mLdapDefinition.mServer) ;
        message.appendAscii(":") ;
        message.append(mLdapDefinition.mPort) ;
        throw ldap::LdapConnectionException(message.makeStringAndClear(),
                                            NULL) ;
    }
}
//------------------------------------------------------------------------------
 void LdapConnection::getUserProfile(const rtl::OUString& aUser,
                                     const LdapUserProfileMap& aUserProfileMap,
                                     LdapUserProfile& aUserProfile)
    throw (lang::IllegalArgumentException,
            ldap::LdapConnectionException, ldap::LdapGenericException)
 {
    if (!isValid()) { connectSimple(); }

    rtl::OString aUserDn =findUserDn( rtl::OUStringToOString(aUser, RTL_TEXTENCODING_ASCII_US));

    LdapMessageHolder result;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      aUserDn,
                                      LDAP_SCOPE_BASE,
                                      "(objectclass=*)",
                                      const_cast<sal_Char **>(aUserProfileMap.getLdapAttributes()),
                                      0, // Attributes + values
                                      &result.msg) ;

    checkLdapReturnCode("getUserProfile", retCode,mConnection) ;

    aUserProfileMap.ldapToUserProfile(mConnection,
                                        result.msg,
                                      aUserProfile) ;

 }
//------------------------------------------------------------------------------
 rtl::OString LdapConnection::findUserDn(const rtl::OString& aUser)
    throw (lang::IllegalArgumentException,
            ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid()) { connectSimple(); }

    if (aUser.getLength() == 0)
    {
        throw lang::IllegalArgumentException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
            ("LdapConnection::findUserDn -User id is empty")),
                NULL, 0) ;
    }

    rtl::OStringBuffer filter( "(&(objectclass=" );

    filter.append( mLdapDefinition.mUserObjectClass ).append(")(") ;
    filter.append( mLdapDefinition.mUserUniqueAttr ).append("=").append(aUser).append("))") ;

    LdapMessageHolder result;
    sal_Char * attributes [2];
    attributes[0]= const_cast<sal_Char *>(LDAP_NO_ATTRS);
    attributes[1]= NULL;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      mLdapDefinition.mBaseDN,
                                      LDAP_SCOPE_SUBTREE,
                                      filter.makeStringAndClear(), attributes, 0, &result.msg) ;

    checkLdapReturnCode("FindUserDn", retCode,mConnection) ;
    rtl::OString userDn ;
    LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;

    if (entry != NULL)
    {
        sal_Char *charsDn = ldap_get_dn(mConnection, entry) ;

        userDn = charsDn ;
        ldap_memfree(charsDn) ;
    }
    else
    {
        OSL_ENSURE( false, "LdapConnection::findUserDn-could not get DN for User ");
    }

    return userDn ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::getSingleAttribute(
    const rtl::OString& aDn,
    const rtl::OString& aAttribute)
    throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid()) { connectSimple(); }
    const sal_Char *attributes [2] ;
    rtl::OString value ;

    attributes [0] = aAttribute ;
    attributes [1] = 0 ;
    LdapMessageHolder result ;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      aDn,
                                      LDAP_SCOPE_BASE,
                                      "(objectclass=*)",
                                      const_cast<sal_Char **>(attributes),
                                      0, // Attributes + values
                                      &result.msg) ;

    if (retCode == LDAP_NO_SUCH_OBJECT)
    {
        return value ;
    }
    checkLdapReturnCode("GetSingleAttribute", retCode, mConnection) ;
    LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;

    if (entry != NULL)
    {
        sal_Char **values = ldap_get_values(mConnection, entry,
                                            aAttribute) ;

        if (values != NULL)
        {
            if (*values != NULL) { value = *values ; }
            ldap_value_free(values) ;
        }
    }
    return value ;
}

//------------------------------------------------------------------------------
} } } // extensions.config.ldap

<commit_msg>INTEGRATION: CWS changefileheader (1.8.48); FILE MERGED 2008/04/01 15:15:04 thb 1.8.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:25 rt 1.8.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ldapaccess.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "ldapaccess.hxx"

#include "ldapuserprof.hxx"
#include <rtl/ustrbuf.hxx>
#include <rtl/strbuf.hxx>

namespace extensions { namespace config { namespace ldap {

//------------------------------------------------------------------------------
typedef int LdapErrCode;
//------------------------------------------------------------------------------
struct LdapMessageHolder
{
    LdapMessageHolder() : msg(0) {}
    ~LdapMessageHolder() { if (msg) ldap_msgfree(msg); }

    LDAPMessage * msg;

private:
    LdapMessageHolder(LdapMessageHolder const&);
    void operator=(LdapMessageHolder const&);
};
//------------------------------------------------------------------------------
LdapConnection::~LdapConnection()
{
    if (isValid()) disconnect();
}
//------------------------------------------------------------------------------

void LdapConnection::disconnect()
{
    if (mConnection != NULL)
    {
        ldap_unbind_s(mConnection) ;
        mConnection = NULL;
    }
}
//------------------------------------------------------------------------------

static void checkLdapReturnCode(const sal_Char *aOperation,
                                LdapErrCode aRetCode,
                                LDAP * /*aConnection*/)
{
    if (aRetCode == LDAP_SUCCESS) { return ; }

    static const sal_Char *kNoSpecificMessage = "No additional information" ;
    rtl::OUStringBuffer message ;

    if (aOperation != NULL)
    {
        message.appendAscii(aOperation).appendAscii(": ") ;
    }
    message.appendAscii(ldap_err2string(aRetCode)).appendAscii(" (") ;
    sal_Char *stub = NULL ;

#ifndef LDAP_OPT_SIZELIMIT // for use with OpenLDAP
    ldap_get_lderrno(aConnection, NULL, &stub) ;
#endif
    if (stub != NULL)
    {
        message.appendAscii(stub) ;
        // It would seem the message returned is actually
        // not a copy of a string but rather some static
        // string itself. At any rate freeing it seems to
        // cause some undue problems at least on Windows.
        // This call is thus disabled for the moment.
        //ldap_memfree(stub) ;
    }
    else { message.appendAscii(kNoSpecificMessage) ; }
    message.appendAscii(")") ;
    throw ldap::LdapGenericException(message.makeStringAndClear(),
                                     NULL, aRetCode) ;
}
//------------------------------------------------------------------------------
void  LdapConnection::connectSimple(const LdapDefinition& aDefinition)
   throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    OSL_ENSURE(!isValid(), "Recoonecting an LDAP connection that is already established");
    if (isValid()) disconnect();

    mLdapDefinition = aDefinition;
    connectSimple();
}
//------------------------------------------------------------------------------
void  LdapConnection::connectSimple()
   throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid())
    {
        // Connect to the server
        initConnection() ;
        // Set Protocol V3
        int version = LDAP_VERSION3;
        ldap_set_option(mConnection,
                        LDAP_OPT_PROTOCOL_VERSION,
                        &version);

#ifdef LDAP_X_OPT_CONNECT_TIMEOUT // OpenLDAP doesn't support this and the func
        /* timeout is specified in milliseconds -> 4 seconds*/
        int timeout = 4000;
        ldap_set_option( mConnection,
                        LDAP_X_OPT_CONNECT_TIMEOUT,
                        &timeout );
#endif

        // Do the bind
        LdapErrCode retCode = ldap_simple_bind_s(mConnection,
                                               mLdapDefinition.mAnonUser ,
                                               mLdapDefinition.mAnonCredentials) ;

        checkLdapReturnCode("SimpleBind", retCode, mConnection) ;
    }
}
//------------------------------------------------------------------------------
void LdapConnection::initConnection()
    throw (ldap::LdapConnectionException)
{
    if (mLdapDefinition.mServer.getLength() == 0)
    {
        rtl::OUStringBuffer message ;

        message.appendAscii("Cannot initialise connection to LDAP: No server specified.") ;
        throw ldap::LdapConnectionException(message.makeStringAndClear(), NULL) ;
    }

    if (mLdapDefinition.mPort == 0) mLdapDefinition.mPort = LDAP_PORT;

    mConnection = ldap_init(mLdapDefinition.mServer,
                            mLdapDefinition.mPort) ;
    if (mConnection == NULL)
    {
        rtl::OUStringBuffer message ;

        message.appendAscii("Cannot initialise connection to LDAP server ") ;
        message.appendAscii(mLdapDefinition.mServer) ;
        message.appendAscii(":") ;
        message.append(mLdapDefinition.mPort) ;
        throw ldap::LdapConnectionException(message.makeStringAndClear(),
                                            NULL) ;
    }
}
//------------------------------------------------------------------------------
 void LdapConnection::getUserProfile(const rtl::OUString& aUser,
                                     const LdapUserProfileMap& aUserProfileMap,
                                     LdapUserProfile& aUserProfile)
    throw (lang::IllegalArgumentException,
            ldap::LdapConnectionException, ldap::LdapGenericException)
 {
    if (!isValid()) { connectSimple(); }

    rtl::OString aUserDn =findUserDn( rtl::OUStringToOString(aUser, RTL_TEXTENCODING_ASCII_US));

    LdapMessageHolder result;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      aUserDn,
                                      LDAP_SCOPE_BASE,
                                      "(objectclass=*)",
                                      const_cast<sal_Char **>(aUserProfileMap.getLdapAttributes()),
                                      0, // Attributes + values
                                      &result.msg) ;

    checkLdapReturnCode("getUserProfile", retCode,mConnection) ;

    aUserProfileMap.ldapToUserProfile(mConnection,
                                        result.msg,
                                      aUserProfile) ;

 }
//------------------------------------------------------------------------------
 rtl::OString LdapConnection::findUserDn(const rtl::OString& aUser)
    throw (lang::IllegalArgumentException,
            ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid()) { connectSimple(); }

    if (aUser.getLength() == 0)
    {
        throw lang::IllegalArgumentException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
            ("LdapConnection::findUserDn -User id is empty")),
                NULL, 0) ;
    }

    rtl::OStringBuffer filter( "(&(objectclass=" );

    filter.append( mLdapDefinition.mUserObjectClass ).append(")(") ;
    filter.append( mLdapDefinition.mUserUniqueAttr ).append("=").append(aUser).append("))") ;

    LdapMessageHolder result;
    sal_Char * attributes [2];
    attributes[0]= const_cast<sal_Char *>(LDAP_NO_ATTRS);
    attributes[1]= NULL;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      mLdapDefinition.mBaseDN,
                                      LDAP_SCOPE_SUBTREE,
                                      filter.makeStringAndClear(), attributes, 0, &result.msg) ;

    checkLdapReturnCode("FindUserDn", retCode,mConnection) ;
    rtl::OString userDn ;
    LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;

    if (entry != NULL)
    {
        sal_Char *charsDn = ldap_get_dn(mConnection, entry) ;

        userDn = charsDn ;
        ldap_memfree(charsDn) ;
    }
    else
    {
        OSL_ENSURE( false, "LdapConnection::findUserDn-could not get DN for User ");
    }

    return userDn ;
}
//------------------------------------------------------------------------------
rtl::OString LdapConnection::getSingleAttribute(
    const rtl::OString& aDn,
    const rtl::OString& aAttribute)
    throw (ldap::LdapConnectionException, ldap::LdapGenericException)
{
    if (!isValid()) { connectSimple(); }
    const sal_Char *attributes [2] ;
    rtl::OString value ;

    attributes [0] = aAttribute ;
    attributes [1] = 0 ;
    LdapMessageHolder result ;
    LdapErrCode retCode = ldap_search_s(mConnection,
                                      aDn,
                                      LDAP_SCOPE_BASE,
                                      "(objectclass=*)",
                                      const_cast<sal_Char **>(attributes),
                                      0, // Attributes + values
                                      &result.msg) ;

    if (retCode == LDAP_NO_SUCH_OBJECT)
    {
        return value ;
    }
    checkLdapReturnCode("GetSingleAttribute", retCode, mConnection) ;
    LDAPMessage *entry = ldap_first_entry(mConnection, result.msg) ;

    if (entry != NULL)
    {
        sal_Char **values = ldap_get_values(mConnection, entry,
                                            aAttribute) ;

        if (values != NULL)
        {
            if (*values != NULL) { value = *values ; }
            ldap_value_free(values) ;
        }
    }
    return value ;
}

//------------------------------------------------------------------------------
} } } // extensions.config.ldap

<|endoftext|>


<commit_before>/******************************************************************************
* IMU_Functions.cpp
*
* Runs initialization and reads files on the BNO055 IMU
******************************************************************************/
#include "Mapper.h"

/******************************************************************************
 * void start_read_imu
 *
 * Starts read_imu.py code
******************************************************************************/
void start_read_imu(void)
{
  char cmd[50];
  strcpy(cmd,"python read_imu.py & exit");
  system(cmd);
/*
  // clear fifo file //
  //std::FILE* fifo = fopen("imu.fifo","w");
  std::FILE* fifo = fopen("imu.txt","w");
  fclose(fifo);
  printf("Cleared fifo file\n");

  // Start up the Python
  std::FILE* fd = fopen("read_imu.py", "r");
  printf("Started up Python\n");
  PyRun_SimpleFile(fd,"read_imu.py");
  printf("Ran PyRun_SimpleFile\n");

  // Wait 2 seconds to let the python script start up
  usleep(2000000);

  // Check whether the python script wrote anything
  //fd = fopen("imu.fifo","r");
  fd = fopen("imu.txt","r");
  printf("Python \n");
  // Insert check here //
  fseek(fd, 0, SEEK_END); // goto end of file
  if (ftell(fd) == 0)
  {
    printf("file is empty\n");
  }
  else
  {
    printf("file is not empty\n");
  }
  fseek(fd, 0, SEEK_SET); // goto begin of file

  // if it isn't printing values, restart initialization

  fclose(fd);
//*/
  return;
}

/******************************************************************************
 * imu_t read_imu_fifo
 *
 * Reads IMU values from imu.fifo and write to the imu struct
******************************************************************************/
imu_t read_imu_fifo(void)
{
	imu_t imu;
	char buf[1000];
	FILE *fd = fopen( "imu.fifo", "r");
	fgets(buf,1000,fd);
	fclose(fd);
	sscanf(buf,"%f %f %f %f %f %f %i %i %i %i %f %f %f",
				 &imu.yaw,&imu.roll,&imu.pitch,
				 &imu.q, &imu.p, &imu.r,
				 &imu.sys,&imu.gyro,&imu.accel,
				 &imu.mag,imu.x_acc,&imu.y_acc,&imu.z_acc);

	return imu;
}
<commit_msg>added print statement to imu_functions<commit_after>/******************************************************************************
* IMU_Functions.cpp
*
* Runs initialization and reads files on the BNO055 IMU
******************************************************************************/
#include "Mapper.h"

/******************************************************************************
 * void start_read_imu
 *
 * Starts read_imu.py code
******************************************************************************/
void start_read_imu(void)
{
  char cmd[50];
  strcpy(cmd,"python read_imu.py & exit");
  printf("%s\n", "ran strcpy command");
  system(cmd);
/*
  // clear fifo file //
  //std::FILE* fifo = fopen("imu.fifo","w");
  std::FILE* fifo = fopen("imu.txt","w");
  fclose(fifo);
  printf("Cleared fifo file\n");

  // Start up the Python
  std::FILE* fd = fopen("read_imu.py", "r");
  printf("Started up Python\n");
  PyRun_SimpleFile(fd,"read_imu.py");
  printf("Ran PyRun_SimpleFile\n");

  // Wait 2 seconds to let the python script start up
  usleep(2000000);

  // Check whether the python script wrote anything
  //fd = fopen("imu.fifo","r");
  fd = fopen("imu.txt","r");
  printf("Python \n");
  // Insert check here //
  fseek(fd, 0, SEEK_END); // goto end of file
  if (ftell(fd) == 0)
  {
    printf("file is empty\n");
  }
  else
  {
    printf("file is not empty\n");
  }
  fseek(fd, 0, SEEK_SET); // goto begin of file

  // if it isn't printing values, restart initialization

  fclose(fd);
//*/
  return;
}

/******************************************************************************
 * imu_t read_imu_fifo
 *
 * Reads IMU values from imu.fifo and write to the imu struct
******************************************************************************/
imu_t read_imu_fifo(void)
{
	imu_t imu;
	char buf[1000];
	FILE *fd = fopen( "imu.fifo", "r");
	fgets(buf,1000,fd);
	fclose(fd);
	sscanf(buf,"%f %f %f %f %f %f %i %i %i %i %f %f %f",
				 &imu.yaw,&imu.roll,&imu.pitch,
				 &imu.q, &imu.p, &imu.r,
				 &imu.sys,&imu.gyro,&imu.accel,
				 &imu.mag,imu.x_acc,&imu.y_acc,&imu.z_acc);

	return imu;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2010-12-02 14:54:03 +0100 (Do, 2 Dec 2010) $
Version:   $Revision: 21147 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkExtractDirectedPlaneImageFilterNew.h"
#include "mitkImageCast.h"
#include "mitkImageTimeSelector.h"
#include "itkImageRegionIterator.h"

mitk::ExtractDirectedPlaneImageFilterNew::ExtractDirectedPlaneImageFilterNew()
:m_CurrentWorldGeometry2D(NULL)
{
}

mitk::ExtractDirectedPlaneImageFilterNew::~ExtractDirectedPlaneImageFilterNew()
{
}

void mitk::ExtractDirectedPlaneImageFilterNew::GenerateData(){

    mitk::Image::ConstPointer inputImage = ImageToImageFilter::GetInput(0);

    if ( !inputImage )
    {
        MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!" << std::endl;
        itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!");
        return;
    }

    m_ImageGeometry = inputImage->GetGeometry();

    //If no timestep is set, the lowest given will be selected
    const mitk::TimeSlicedGeometry* inputTimeGeometry = this->GetInput()->GetTimeSlicedGeometry();
    if ( !m_ActualInputTimestep )
    {
        ScalarType time = m_CurrentWorldGeometry2D->GetTimeBounds()[0];
        if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
        {
            m_ActualInputTimestep = inputTimeGeometry->MSToTimeStep( time );
        }
    }

    if ( inputImage->GetDimension() > 4 || inputImage->GetDimension() < 2)
    {
        MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew:GenerateData works only with 3D and 3D+t images, sorry." << std::endl;
        itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew works only with 3D and 3D+t images, sorry.");
        return;
    }
    else if ( inputImage->GetDimension() == 4 )
    {
        mitk::ImageTimeSelector::Pointer timeselector = mitk::ImageTimeSelector::New();
        timeselector->SetInput( inputImage );
        timeselector->SetTimeNr( m_ActualInputTimestep );
        timeselector->UpdateLargestPossibleRegion();
        inputImage = timeselector->GetOutput();
    }
    else if ( inputImage->GetDimension() == 2)
    {
        mitk::Image::Pointer resultImage = ImageToImageFilter::GetOutput();
        resultImage = const_cast<mitk::Image*>( inputImage.GetPointer() );
        ImageToImageFilter::SetNthOutput( 0, resultImage);
        return;
    }

    if ( !m_CurrentWorldGeometry2D )
    {
        MITK_ERROR<< "mitk::ExtractDirectedPlaneImageFilterNew::GenerateData has no CurrentWorldGeometry2D set" << std::endl;
        return;
    }

    AccessFixedDimensionByItk( inputImage, ItkSliceExtraction, 3 );

}//Generate Data

void mitk::ExtractDirectedPlaneImageFilterNew::GenerateOutputInformation ()
{
    Superclass::GenerateOutputInformation();
}

/*
* The desired slice is extracted by filling the image`s corresponding pixel values in an empty 2 dimensional itk::Image
* Therefor the itk image`s extent in pixel (in each direction) is doubled and its spacing (also in each direction) is divided by two
* (similar to the shannon theorem).
*/
template<typename TPixel, unsigned int VImageDimension>
void mitk::ExtractDirectedPlaneImageFilterNew::ItkSliceExtraction (itk::Image<TPixel, VImageDimension>* inputImage)
{
    typedef itk::Image<TPixel, VImageDimension> InputImageType;
    typedef itk::Image<TPixel, VImageDimension-1> SliceImageType;

    typedef itk::ImageRegionConstIterator< SliceImageType > SliceIterator;

    //Creating an itk::Image that represents the sampled slice
    typename SliceImageType::Pointer resultSlice = SliceImageType::New();

    typename SliceImageType::IndexType start;

    start[0] = 0;
    start[1] = 0;

    Point3D origin = m_CurrentWorldGeometry2D->GetOrigin();
    Vector3D right = m_CurrentWorldGeometry2D->GetAxisVector(0);
    Vector3D bottom = m_CurrentWorldGeometry2D->GetAxisVector(1);

    //Calculation the sample-spacing, i.e the half of the smallest spacing existing in the original image
    Vector3D newPixelSpacing = m_ImageGeometry->GetSpacing();
    float minSpacing = newPixelSpacing[0];
    for (unsigned int i = 1; i < newPixelSpacing.Size(); i++)
    {
        if (newPixelSpacing[i] < minSpacing )
        {
            minSpacing = newPixelSpacing[i];
        }
    }

    newPixelSpacing[0] = 0.5*minSpacing;
    newPixelSpacing[1] = 0.5*minSpacing;
    newPixelSpacing[2] = 0.5*minSpacing;

    float pixelSpacing[2];
    pixelSpacing[0] =  newPixelSpacing[0];
    pixelSpacing[1] =  newPixelSpacing[1];

    //Calculating the size of the sampled slice
    typename SliceImageType::SizeType size;
    Vector2D extentInMM;
    extentInMM[0] = m_CurrentWorldGeometry2D->GetExtentInMM(0);
    extentInMM[1] = m_CurrentWorldGeometry2D->GetExtentInMM(1);

    //The maximum extent is the lenght of the diagonal of the considered plane
    double maxExtent = sqrt(extentInMM[0]*extentInMM[0]+extentInMM[1]*extentInMM[1]);
    unsigned int xTranlation = (maxExtent-extentInMM[0]);
    unsigned int yTranlation = (maxExtent-extentInMM[1]);
    size[0] = (maxExtent+xTranlation)/newPixelSpacing[0];
    size[1] = (maxExtent+yTranlation)/newPixelSpacing[1];

    //Creating an ImageRegion Object
    typename SliceImageType::RegionType region;

    region.SetSize( size );
    region.SetIndex( start );

    //Defining the image`s extent and origin by passing the region to it and allocating memory for it
    resultSlice->SetRegions( region );
    resultSlice->SetSpacing( pixelSpacing );
    resultSlice->Allocate();

    /*
    * Here we create an new geometry so that the transformations are calculated correctly (our resulting slice has a different bounding box and spacing)
    * The original current worldgeometry must be cloned because we have to keep the directions of the axis vector which represents the rotation
    */
    right.Normalize();
    bottom.Normalize();
    //Here we translate the origin to adapt the new geometry to the previous calculated extent
    origin[0] -= xTranlation*right[0]+yTranlation*bottom[0];
    origin[1] -= xTranlation*right[1]+yTranlation*bottom[1];
    origin[2] -= xTranlation*right[2]+yTranlation*bottom[2];

    //Putting it together for the new geometry
    mitk::Geometry3D::Pointer newSliceGeometryTest = dynamic_cast<Geometry3D*>(m_CurrentWorldGeometry2D->Clone().GetPointer());
    newSliceGeometryTest->ChangeImageGeometryConsideringOriginOffset(true);

    //Workaround because of BUG (#6505)
    newSliceGeometryTest->GetIndexToWorldTransform()->SetMatrix(m_CurrentWorldGeometry2D->GetIndexToWorldTransform()->GetMatrix());
    //Workaround end

    newSliceGeometryTest->SetOrigin(origin);
    ScalarType bounds[6]={0, size[0], 0, size[1], 0, 1};
    newSliceGeometryTest->SetBounds(bounds);
    newSliceGeometryTest->SetSpacing(newPixelSpacing);
    newSliceGeometryTest->Modified();

    //Workaround because of BUG (#6505)
    itk::MatrixOffsetTransformBase<mitk::ScalarType,3,3>::MatrixType tempTransform = newSliceGeometryTest->GetIndexToWorldTransform()->GetMatrix();
    //Workaround end

    /*
    * Now we iterate over the recently created slice.
    * For each slice - pixel we check whether there is an according
    * pixel in the input - image which can be set in the slice.
    * In this way a slice is sampled out of the input - image regrading to the given PlaneGeometry
    */
    Point3D currentSliceIndexPointIn2D;
    Point3D currentImageWorldPointIn3D;
    typename InputImageType::IndexType inputIndex;

    SliceIterator sliceIterator ( resultSlice, resultSlice->GetLargestPossibleRegion() );
    sliceIterator.GoToBegin();

    while ( !sliceIterator.IsAtEnd() )
    {
        /*
        * Here we add 0.5 to to assure that the indices are correctly transformed.
        * (Because of the 0.5er Bug)
        */
        currentSliceIndexPointIn2D[0] = sliceIterator.GetIndex()[0]+0.5;
        currentSliceIndexPointIn2D[1] = sliceIterator.GetIndex()[1]+0.5;
        currentSliceIndexPointIn2D[2] = 0;

        newSliceGeometryTest->IndexToWorld( currentSliceIndexPointIn2D, currentImageWorldPointIn3D );

        m_ImageGeometry->WorldToIndex( currentImageWorldPointIn3D, inputIndex);

        if ( m_ImageGeometry->IsIndexInside( inputIndex ))
        {

            resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );

        }

        ++sliceIterator;
    }

    Image::Pointer resultImage = ImageToImageFilter::GetOutput();
    GrabItkImageMemory(resultSlice, resultImage, NULL, false);
    resultImage->SetClonedGeometry(newSliceGeometryTest);
    //Workaround because of BUG (#6505)
    resultImage->GetGeometry()->GetIndexToWorldTransform()->SetMatrix(tempTransform);
    //Workaround end
}

///**TEST** May ba a little bit more efficient but doesn`t already work/
//right.Normalize();
//bottom.Normalize();
//Point3D currentImagePointIn3D = origin /*+ bottom*newPixelSpacing*/;
//unsigned int columns ( 0 );
/**ENDE**/

/****TEST***/

//SliceImageType::IndexType index = sliceIterator.GetIndex();

//if ( columns == (extentInPixel[0]) )
//{
//If we are at the end of a row, then we have to go to the beginning of the next row
//currentImagePointIn3D = origin;
//currentImagePointIn3D += newPixelSpacing[1]*bottom*index[1];
//columns = 0;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//else
//{
////
//if ( columns != 0 )
//{
//currentImagePointIn3D += newPixelSpacing[0]*right;
//}
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}

//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//else if (currentImagePointIn3D == origin)
//{
//Point3D temp;
//temp[0] = bottom[0]*newPixelSpacing[0]*0.5;
//temp[1] = bottom[1]*newPixelSpacing[1]*0.5;
//temp[2] = bottom[2]*newPixelSpacing[2]*0.5;
//origin[0] += temp[0];
//origin[1] += temp[1];
//origin[2] += temp[2];
//currentImagePointIn3D = origin;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//}

/****TEST ENDE****/
<commit_msg>CHG (#6417): Changed the initialization of an extracted slice. Now every pixel outside of the underlying 3D image is set black. Before those pixel were not at all and therefore appeared white<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2010-12-02 14:54:03 +0100 (Do, 2 Dec 2010) $
Version:   $Revision: 21147 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkExtractDirectedPlaneImageFilterNew.h"
#include "mitkImageCast.h"
#include "mitkImageTimeSelector.h"
#include "itkImageRegionIterator.h"

mitk::ExtractDirectedPlaneImageFilterNew::ExtractDirectedPlaneImageFilterNew()
:m_CurrentWorldGeometry2D(NULL)
{
}

mitk::ExtractDirectedPlaneImageFilterNew::~ExtractDirectedPlaneImageFilterNew()
{
}

void mitk::ExtractDirectedPlaneImageFilterNew::GenerateData(){

    mitk::Image::ConstPointer inputImage = ImageToImageFilter::GetInput(0);

    if ( !inputImage )
    {
        MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!" << std::endl;
        itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew: No input available. Please set the input!");
        return;
    }

    m_ImageGeometry = inputImage->GetGeometry();

    //If no timestep is set, the lowest given will be selected
    const mitk::TimeSlicedGeometry* inputTimeGeometry = this->GetInput()->GetTimeSlicedGeometry();
    if ( !m_ActualInputTimestep )
    {
        ScalarType time = m_CurrentWorldGeometry2D->GetTimeBounds()[0];
        if ( time > ScalarTypeNumericTraits::NonpositiveMin() )
        {
            m_ActualInputTimestep = inputTimeGeometry->MSToTimeStep( time );
        }
    }

    if ( inputImage->GetDimension() > 4 || inputImage->GetDimension() < 2)
    {
        MITK_ERROR << "mitk::ExtractDirectedPlaneImageFilterNew:GenerateData works only with 3D and 3D+t images, sorry." << std::endl;
        itkExceptionMacro("mitk::ExtractDirectedPlaneImageFilterNew works only with 3D and 3D+t images, sorry.");
        return;
    }
    else if ( inputImage->GetDimension() == 4 )
    {
        mitk::ImageTimeSelector::Pointer timeselector = mitk::ImageTimeSelector::New();
        timeselector->SetInput( inputImage );
        timeselector->SetTimeNr( m_ActualInputTimestep );
        timeselector->UpdateLargestPossibleRegion();
        inputImage = timeselector->GetOutput();
    }
    else if ( inputImage->GetDimension() == 2)
    {
        mitk::Image::Pointer resultImage = ImageToImageFilter::GetOutput();
        resultImage = const_cast<mitk::Image*>( inputImage.GetPointer() );
        ImageToImageFilter::SetNthOutput( 0, resultImage);
        return;
    }

    if ( !m_CurrentWorldGeometry2D )
    {
        MITK_ERROR<< "mitk::ExtractDirectedPlaneImageFilterNew::GenerateData has no CurrentWorldGeometry2D set" << std::endl;
        return;
    }

    AccessFixedDimensionByItk( inputImage, ItkSliceExtraction, 3 );

}//Generate Data

void mitk::ExtractDirectedPlaneImageFilterNew::GenerateOutputInformation ()
{
    Superclass::GenerateOutputInformation();
}

/*
* The desired slice is extracted by filling the image`s corresponding pixel values in an empty 2 dimensional itk::Image
* Therefor the itk image`s extent in pixel (in each direction) is doubled and its spacing (also in each direction) is divided by two
* (similar to the shannon theorem).
*/
template<typename TPixel, unsigned int VImageDimension>
void mitk::ExtractDirectedPlaneImageFilterNew::ItkSliceExtraction (itk::Image<TPixel, VImageDimension>* inputImage)
{
    typedef itk::Image<TPixel, VImageDimension> InputImageType;
    typedef itk::Image<TPixel, VImageDimension-1> SliceImageType;

    typedef itk::ImageRegionConstIterator< SliceImageType > SliceIterator;

    //Creating an itk::Image that represents the sampled slice
    typename SliceImageType::Pointer resultSlice = SliceImageType::New();

    typename SliceImageType::IndexType start;

    start[0] = 0;
    start[1] = 0;

    Point3D origin = m_CurrentWorldGeometry2D->GetOrigin();
    Vector3D right = m_CurrentWorldGeometry2D->GetAxisVector(0);
    Vector3D bottom = m_CurrentWorldGeometry2D->GetAxisVector(1);

    //Calculation the sample-spacing, i.e the half of the smallest spacing existing in the original image
    Vector3D newPixelSpacing = m_ImageGeometry->GetSpacing();
    float minSpacing = newPixelSpacing[0];
    for (unsigned int i = 1; i < newPixelSpacing.Size(); i++)
    {
        if (newPixelSpacing[i] < minSpacing )
        {
            minSpacing = newPixelSpacing[i];
        }
    }

    newPixelSpacing[0] = 0.5*minSpacing;
    newPixelSpacing[1] = 0.5*minSpacing;
    newPixelSpacing[2] = 0.5*minSpacing;

    float pixelSpacing[2];
    pixelSpacing[0] =  newPixelSpacing[0];
    pixelSpacing[1] =  newPixelSpacing[1];

    //Calculating the size of the sampled slice
    typename SliceImageType::SizeType size;
    Vector2D extentInMM;
    extentInMM[0] = m_CurrentWorldGeometry2D->GetExtentInMM(0);
    extentInMM[1] = m_CurrentWorldGeometry2D->GetExtentInMM(1);

    //The maximum extent is the lenght of the diagonal of the considered plane
    double maxExtent = sqrt(extentInMM[0]*extentInMM[0]+extentInMM[1]*extentInMM[1]);
    unsigned int xTranlation = (maxExtent-extentInMM[0]);
    unsigned int yTranlation = (maxExtent-extentInMM[1]);
    size[0] = (maxExtent+xTranlation)/newPixelSpacing[0];
    size[1] = (maxExtent+yTranlation)/newPixelSpacing[1];

    //Creating an ImageRegion Object
    typename SliceImageType::RegionType region;

    region.SetSize( size );
    region.SetIndex( start );

    //Defining the image`s extent and origin by passing the region to it and allocating memory for it
    resultSlice->SetRegions( region );
    resultSlice->SetSpacing( pixelSpacing );
    resultSlice->Allocate();

    /*
    * Here we create an new geometry so that the transformations are calculated correctly (our resulting slice has a different bounding box and spacing)
    * The original current worldgeometry must be cloned because we have to keep the directions of the axis vector which represents the rotation
    */
    right.Normalize();
    bottom.Normalize();
    //Here we translate the origin to adapt the new geometry to the previous calculated extent
    origin[0] -= xTranlation*right[0]+yTranlation*bottom[0];
    origin[1] -= xTranlation*right[1]+yTranlation*bottom[1];
    origin[2] -= xTranlation*right[2]+yTranlation*bottom[2];

    //Putting it together for the new geometry
    mitk::Geometry3D::Pointer newSliceGeometryTest = dynamic_cast<Geometry3D*>(m_CurrentWorldGeometry2D->Clone().GetPointer());
    newSliceGeometryTest->ChangeImageGeometryConsideringOriginOffset(true);

    //Workaround because of BUG (#6505)
    newSliceGeometryTest->GetIndexToWorldTransform()->SetMatrix(m_CurrentWorldGeometry2D->GetIndexToWorldTransform()->GetMatrix());
    //Workaround end

    newSliceGeometryTest->SetOrigin(origin);
    ScalarType bounds[6]={0, size[0], 0, size[1], 0, 1};
    newSliceGeometryTest->SetBounds(bounds);
    newSliceGeometryTest->SetSpacing(newPixelSpacing);
    newSliceGeometryTest->Modified();

    //Workaround because of BUG (#6505)
    itk::MatrixOffsetTransformBase<mitk::ScalarType,3,3>::MatrixType tempTransform = newSliceGeometryTest->GetIndexToWorldTransform()->GetMatrix();
    //Workaround end

    /*
    * Now we iterate over the recently created slice.
    * For each slice - pixel we check whether there is an according
    * pixel in the input - image which can be set in the slice.
    * In this way a slice is sampled out of the input - image regrading to the given PlaneGeometry
    */
    Point3D currentSliceIndexPointIn2D;
    Point3D currentImageWorldPointIn3D;
    typename InputImageType::IndexType inputIndex;

    SliceIterator sliceIterator ( resultSlice, resultSlice->GetLargestPossibleRegion() );
    sliceIterator.GoToBegin();

    while ( !sliceIterator.IsAtEnd() )
    {
        /*
        * Here we add 0.5 to to assure that the indices are correctly transformed.
        * (Because of the 0.5er Bug)
        */
        currentSliceIndexPointIn2D[0] = sliceIterator.GetIndex()[0]+0.5;
        currentSliceIndexPointIn2D[1] = sliceIterator.GetIndex()[1]+0.5;
        currentSliceIndexPointIn2D[2] = 0;

        newSliceGeometryTest->IndexToWorld( currentSliceIndexPointIn2D, currentImageWorldPointIn3D );

        m_ImageGeometry->WorldToIndex( currentImageWorldPointIn3D, inputIndex);

        if ( m_ImageGeometry->IsIndexInside( inputIndex ))
        {

            resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );

        }
        else
        {
            resultSlice->SetPixel( sliceIterator.GetIndex(), 0);
        }

        ++sliceIterator;
    }

    Image::Pointer resultImage = ImageToImageFilter::GetOutput();
    GrabItkImageMemory(resultSlice, resultImage, NULL, false);
    resultImage->SetClonedGeometry(newSliceGeometryTest);
    //Workaround because of BUG (#6505)
    resultImage->GetGeometry()->GetIndexToWorldTransform()->SetMatrix(tempTransform);
    //Workaround end
}

///**TEST** May ba a little bit more efficient but doesn`t already work/
//right.Normalize();
//bottom.Normalize();
//Point3D currentImagePointIn3D = origin /*+ bottom*newPixelSpacing*/;
//unsigned int columns ( 0 );
/**ENDE**/

/****TEST***/

//SliceImageType::IndexType index = sliceIterator.GetIndex();

//if ( columns == (extentInPixel[0]) )
//{
//If we are at the end of a row, then we have to go to the beginning of the next row
//currentImagePointIn3D = origin;
//currentImagePointIn3D += newPixelSpacing[1]*bottom*index[1];
//columns = 0;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}
//else
//{
////
//if ( columns != 0 )
//{
//currentImagePointIn3D += newPixelSpacing[0]*right;
//}
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//}

//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//else if (currentImagePointIn3D == origin)
//{
//Point3D temp;
//temp[0] = bottom[0]*newPixelSpacing[0]*0.5;
//temp[1] = bottom[1]*newPixelSpacing[1]*0.5;
//temp[2] = bottom[2]*newPixelSpacing[2]*0.5;
//origin[0] += temp[0];
//origin[1] += temp[1];
//origin[2] += temp[2];
//currentImagePointIn3D = origin;
//m_ImageGeometry->WorldToIndex(currentImagePointIn3D, inputIndex);
//if ( m_ImageGeometry->IsIndexInside( inputIndex ))
//{
//resultSlice->SetPixel( sliceIterator.GetIndex(), inputImage->GetPixel(inputIndex) );
//}
//}

/****TEST ENDE****/
<|endoftext|>