<commit_before>#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <regex>
#include <string>
#include <vector>
#include <ctime>

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>

using namespace std;
using namespace boost::filesystem;

map<int, string> files;

struct Node {
    map<char, Node*> children;
    map<int, set<int> > occurrences;
    bool terminal;
};

bool isTokenDelimiter(char c) {
    return c < 'a' || c > 'z';
}

bool isCamlDelimiter(char c) {
    return c < 'A' || c > 'Z';
}

bool isWordDelimiter(char c) {
    return isTokenDelimiter(c) && isCamlDelimiter(c) && (c < '-' || c > ':') && c != '_';
}

void insertToken(Node *root, const string &token, int fileIndex, int line) {
    for (size_t i = 0; i < token.length(); ++i) {
        if (root->children.find(token[i]) == root->children.end()) {
            root->children.emplace(token[i], new Node());
        }
        root = root->children[token[i]];
    }
    root->occurrences[fileIndex].insert(line);
    root->terminal = true;
}

void insertWord(Node *root, const string &word, int fileIndex, int line) {
    for (size_t i = 0; i < word.length(); ++i) {
        if (isTokenDelimiter(word[i])) {
            if (isCamlDelimiter(word[i])) {
                insertToken(root, word.substr(i + 1), fileIndex, line);
            } else {
                insertToken(root, word.substr(i), fileIndex, line);
            }
        }
    }
    insertToken(root, word, fileIndex, line);
}

void printTerminals(Node *root, string &s) {
    if (root->terminal) {
        for (auto it : root->occurrences) {
            string &file = files[it.first];
            for (auto it_line : it.second) {
                cout << file << ':' << it_line << ':' << s << endl;
            }
        }
    }
    for (auto it : root->children) {
        s += it.first;
        printTerminals(it.second, s);
        s.pop_back();
    }
}

bool query(Node *root, string &query) {
    for (size_t i = 0; i < query.length(); ++i) {
        if (root->children.find(query[i]) != root->children.end()) {
            root = root->children.find(query[i])->second;
        } else {
            cout << "No results for query: " << query << endl;
            return false;
        }
    }
    cout << "Results: " << endl;
    printTerminals(root, query);
    return true;
}

int countTokens(Node *root) {
    int count = root->terminal ? 1 : 0;
    for (auto it : root->children) {
        count += countTokens(it.second);
    }
    return count;
}

void indexFile(const string &filepath, int fileIndex, Node *root) {
    char c;
    string s;
    int line = 1;
    std::ifstream file (filepath, ios::in);
    if (file.is_open()) {
        files.emplace(fileIndex, filepath);
        while (file.get(c) && c <= '~') {
            if (isWordDelimiter(c) && s.length()) {
                insertWord(root, s, fileIndex, line);
                s.clear();
            } else if (c > ' ') {
                s += c;
            }
            if (c == '\n') {
                ++line;
            }
        }
        file.close();
    } else {
        cout << "Failed to open file: " << s << endl;
    }
}

int iterateFiles(const string &path, Node *root) {
    int numFiles = 0;
    cout << "Root path: " << path << endl;
    recursive_directory_iterator it(path), end;
    while (it != end)
    {
        if (it->path().stem().string().length() == 0 || is_symlink(*it)) {
            it.no_push();
            ++it;
            continue;
        } else if (is_directory(*it)) {
            cout << "Processing directory: " << it->path().string() << endl;
            ++it;
            continue;
        }
        indexFile(it->path().string(), numFiles, root);
        ++it;
        ++numFiles;
    }
    return numFiles;
}

int main(int argc, char *argv[]) {
    Node *root = new Node();

    string s (argv[1]);
    clock_t start = clock();
    iterateFiles(s, root);
    start = clock() - start;

    cout << "Trie construction time (s) : "
         << (double) start / CLOCKS_PER_SEC << endl;

    cout << "Tokens added: " << countTokens(root) << endl;

    cout << "Input query:" << endl;
    while (cin >> s && s != "done") {
        query(root, s);
        cout << "Input query:" << endl;
    }
    return 0;
}
<commit_msg>Use global variables<commit_after>#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <regex>
#include <string>
#include <vector>
#include <ctime>

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>

using namespace std;
using namespace boost::filesystem;

struct Node {
    map<char, Node*> children;
    map<int, set<int> > occurrences;
    bool terminal;
};

map<int, string> files;
Node *root;

bool isTokenDelimiter(char c) {
    return c < 'a' || c > 'z';
}

bool isCamlDelimiter(char c) {
    return c < 'A' || c > 'Z';
}

bool isWordDelimiter(char c) {
    return isTokenDelimiter(c) && isCamlDelimiter(c) && (c < '-' || c > ':') && c != '_';
}

void insertToken(Node *n, const string &token, int fileIndex, int line) {
    for (size_t i = 0; i < token.length(); ++i) {
        if (n->children.find(token[i]) == n->children.end()) {
            n->children.emplace(token[i], new Node());
        }
        n = n->children[token[i]];
    }
    n->occurrences[fileIndex].insert(line);
    n->terminal = true;
}

void insertWord(const string &word, int fileIndex, int line) {
    for (size_t i = 0; i < word.length(); ++i) {
        if (isTokenDelimiter(word[i])) {
            if (isCamlDelimiter(word[i])) {
                insertToken(root, word.substr(i + 1), fileIndex, line);
            } else {
                insertToken(root, word.substr(i), fileIndex, line);
            }
        }
    }
    insertToken(root, word, fileIndex, line);
}

void printTerminals(Node *n, string &s) {
    if (n->terminal) {
        for (auto it : n->occurrences) {
            string &file = files[it.first];
            for (auto it_line : it.second) {
                cout << file << ':' << it_line << ':' << s << endl;
            }
        }
    }
    for (auto it : n->children) {
        s += it.first;
        printTerminals(it.second, s);
        s.pop_back();
    }
}

bool query(Node *n, string &query) {
    for (size_t i = 0; i < query.length(); ++i) {
        if (n->children.find(query[i]) != n->children.end()) {
            n = n->children.find(query[i])->second;
        } else {
            cout << "No results for query: " << query << endl;
            return false;
        }
    }
    cout << "Results: " << endl;
    printTerminals(n, query);
    return true;
}

int countTokens(Node *n) {
    int count = n->terminal ? 1 : 0;
    for (auto it : n->children) {
        count += countTokens(it.second);
    }
    return count;
}

void indexFile(const string &filepath, int fileIndex) {
    char c;
    string s;
    int line = 1;
    std::ifstream file (filepath, ios::in);
    if (file.is_open()) {
        files.emplace(fileIndex, filepath);
        while (file.get(c) && c <= '~') {
            if (isWordDelimiter(c) && s.length()) {
                insertWord(s, fileIndex, line);
                s.clear();
            } else if (c > ' ') {
                s += c;
            }
            if (c == '\n') {
                ++line;
            }
        }
        file.close();
    } else {
        cout << "Failed to open file: " << s << endl;
    }
}

int iterateFiles(const string &path) {
    int numFiles = 0;
    cout << "Root path: " << path << endl;
    recursive_directory_iterator it(path), end;
    while (it != end)
    {
        if (it->path().stem().string().length() == 0 || is_symlink(*it)) {
            it.no_push();
            ++it;
            continue;
        } else if (is_directory(*it)) {
            cout << "Processing directory: " << it->path().string() << endl;
            ++it;
            continue;
        }
        indexFile(it->path().string(), numFiles);
        ++it;
        ++numFiles;
    }
    return numFiles;
}

int main(int argc, char *argv[]) {
    root = new Node();

    string s (argv[1]);
    clock_t start = clock();
    iterateFiles(s);
    start = clock() - start;

    cout << "Trie construction time (s) : "
         << (double) start / CLOCKS_PER_SEC << endl;

    cout << "Tokens added: " << countTokens(root) << endl;

    cout << "Input query:" << endl;
    while (cin >> s && s != "done") {
        query(root, s);
        cout << "Input query:" << endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <SFML/Graphics.hpp>
#include "TextButtonWidget.hpp"
#include "CheckBoxWidget.hpp"
#include "ConsoleWidget.hpp"
#include "GUIEnvironment.hpp"
#include "ProgressWidget.hpp"
#include "TextWidget.hpp"
#include "TextInputWidget.hpp"
#include "VerticalLayout.hpp"
#include "ScrollableWidget.hpp"
#include "WindowWidget.hpp"

typedef std::chrono::high_resolution_clock CLOCK;

void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
        float &averageFpsTime, float &fpsInSec, int &fpsCnt,
        int &averageFpsInOneSec,
        CLOCK::time_point &timePoint1);

int main()
{
    unsigned int windowWidth{ 1280 };
    unsigned int windowHeight{ 720 };
    sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, "GUI-SFML");

    sf::Font font;
    if (!font.loadFromFile("assets/fonts/LiberationSans-Regular.ttf"))
    {
        std::cout << "Error by loading Font" << std::endl;
    }

    sf::Text txtStatFPS;
    txtStatFPS.setFont(font);
    txtStatFPS.setCharacterSize(12);
    txtStatFPS.setFillColor(sf::Color::Black);
    float dt{ 0.f };
    float averageFpsTime{ 0.f };
    float fpsInSec{ 0.f };
    int fpsCnt{ 0 };
    int averageFpsInOneSec{ 0 };
    CLOCK::time_point timePoint1{ CLOCK::now() };

    gsf::GUIEnvironment guiEnvironment;
    std::unique_ptr<gsf::TextWidget> textWidget{
    std::make_unique<gsf::TextWidget>
        //012345678 9012345 678901 23456
        ("IM A TEXT\nTESTA\nTESTB\nTESTC\nS", font) };
    //textWidget->centerOrigin();
    textWidget->setBackgroundColor(sf::Color::Red);
    textWidget->setCharacterSize(60);
    textWidget->setPosition(windowWidth / 2.f + 100.f, windowHeight / 2.f - 330.f);
    guiEnvironment.addWidget(std::move(textWidget));

    std::unique_ptr<gsf::ProgressWidget> progressWidget{
        std::make_unique<gsf::ProgressWidget>(260, 40) };
    progressWidget->setPosition(460, 460);
    progressWidget->setProgress(50);
    guiEnvironment.addWidget(std::move(progressWidget));

    std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{
        std::make_unique<gsf::ScrollableWidget>(300, 200) };
    scrollableWidget->setBackgroundColor(sf::Color::Blue);

    std::unique_ptr<gsf::VerticalLayout> layout{
        std::make_unique<gsf::VerticalLayout>() };
    layout->setPosition(0.f , 0.f);
    layout->setBackgroundColor(sf::Color::Cyan);

    for (int i{ 0 }; i != 6; i++)
    {
        std::string textString{ "Text Num " + std::to_string(i) };
        std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>
                (textString, font, 40, sf::Color::White) };
        if (i % 2 == 0)
        {
            text->setBackgroundColor(sf::Color::Green);
        }
        else
        {
            text->setBackgroundColor(sf::Color::Magenta);
        }
        std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
        {
            gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
            std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
                << textWidget->getText().toAnsiString() << std::endl;
        };
        text->setOnLeftClickListener(leftClickListener);
        layout->attachChild(std::move(text));
    }

    scrollableWidget->attachChild(std::move(layout));

    std::unique_ptr<gsf::WindowWidget> windowWidget{
        std::make_unique<gsf::WindowWidget>(300.f, 200.f, "", font) };
    windowWidget->setPosition(0.f , 0.f);
    //windowWidget->setBackgroundColor(sf::Color::White);
    windowWidget->attachChild(std::move(scrollableWidget));
    windowWidget->setIsVisible(true);
    guiEnvironment.addWidget(std::move(windowWidget));

    std::unique_ptr<gsf::WindowWidget> windowWidget2{
        std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
    windowWidget2->setPosition(240.f , 40.f);
    //windowWidget2->setBackgroundColor(sf::Color::Red);
    //windowWidget2->setTopBarFillColor(sf::Color::Green);
    //windowWidget2->setCloseButtonFillColor(sf::Color::Blue);
    windowWidget2->setWindowTitle("Test");
    //windowWidget2->setWindowTitleColor(sf::Color::Red);
    guiEnvironment.addWidget(std::move(windowWidget2));

    std::unique_ptr<gsf::WindowWidget> windowWidget3{
        std::make_unique<gsf::WindowWidget>
            (300.f, 360.f, "Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT", font) };
    windowWidget3->setPosition(300.f , 60.f);
    //windowWidget3->setOutlineThickness(12.f);
    //windowWidget3->setOutlineColor(sf::Color::White);
    //windowWidget3->setBackgroundColor(sf::Color::Blue);
    guiEnvironment.addWidget(std::move(windowWidget3));

    // BUTTON TEST
    std::unique_ptr<gsf::TextButtonWidget> buttonWidget{
        std::make_unique<gsf::TextButtonWidget>
            (200.f, 80.f, "CABBBBBTTTTTTTTTTTTTTTTTTTTTTClick me", font) };
    buttonWidget->setPosition(240.f , 360.f);
    buttonWidget->setOnLeftClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Left Click\n";

            });
    buttonWidget->setOnRightClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Right Click\n";

            });
    buttonWidget->setOnMiddleClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Middle Click\n";

            });
    guiEnvironment.addWidget(std::move(buttonWidget));

    // SCROLLBAR TEST
    std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{
        std::make_unique<gsf::ScrollableWidget>(300, 200) };
    scrollableWidget3->setPosition(820.f, 420.f);
    scrollableWidget3->setBackgroundColor(sf::Color::Yellow);

    std::unique_ptr<gsf::VerticalLayout> layout4{
        std::make_unique<gsf::VerticalLayout>() };
    layout4->setBackgroundColor(sf::Color::Cyan);

    for (int i{0}; i != 10; i++)
    {
        std::string textString{ "Text Text Text Text Text Text Text Num "
            + std::to_string(i) };
        std::unique_ptr<gsf::TextWidget> text{
            std::make_unique<gsf::TextWidget>
                (textString, font, 40, sf::Color::White) };
        if (i % 2 == 0)
        {
            text->setBackgroundColor(sf::Color::Green);
        }
        else
        {
            text->setBackgroundColor(sf::Color::Magenta);
        }
        std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
        {
            gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
            std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
                << textWidget->getText().toAnsiString() << std::endl;
        };
        text->setOnLeftClickListener(leftClickListener);
        //text->setBackgroundColor(sf::Color::Red);
        layout4->attachChild(std::move(text));
    }
    scrollableWidget3->attachChild(std::move(layout4));
    guiEnvironment.addWidget(std::move(scrollableWidget3));

    std::unique_ptr<gsf::TextInputWidget> textInput1{
        std::make_unique<gsf::TextInputWidget>(300.f, 60.f, font) };
    textInput1->setPosition(320.f, 520.f);
    textInput1->setBackgroundColor(sf::Color::White);
    textInput1->setIsHorizontalScrollEnabled(false);
    textInput1->setText(L"Test Text HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH :)");
    guiEnvironment.addWidget(std::move(textInput1));

    // Console Widget
    std::unique_ptr<gsf::ConsoleWidget> console1{
        std::make_unique<gsf::ConsoleWidget>(500.f, 200.f, font) };
    console1->setPosition(700.f, 200.f);
    console1->setOnCommandEnteredListener(
            [] (gsf::Widget *widget, std::wstring inputText)
            {
                std::wcout << "CommandEnteredListener command: " << inputText
                    << std::endl;
                gsf::ConsoleWidget *consoleWidget{
                    static_cast<gsf::ConsoleWidget*>(widget) };
                consoleWidget->addTextToDisplay(L"OK");
            }
    );
    guiEnvironment.addWidget(std::move(console1));

    // CheckBoxWidget
    std::unique_ptr<gsf::CheckBoxWidget> checkBox1{
        std::make_unique<gsf::CheckBoxWidget>(60, 60.f) };
    checkBox1->setPosition(10.f, 620.f);
    guiEnvironment.addWidget(std::move(checkBox1));

    while (window.isOpen())
    {
        determineFpsAndDeltaTime(txtStatFPS, dt, averageFpsTime, fpsInSec, fpsCnt,
            averageFpsInOneSec, timePoint1);
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }
            guiEnvironment.handleEvent(event);
        }
        guiEnvironment.update(dt);

        window.clear(sf::Color::White);
        window.draw(guiEnvironment);
        window.draw(txtStatFPS);
        window.display();
    }

    return 0;
}

void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
        float &averageFpsTime, float &fpsInSec, int &fpsCnt,
        int &averageFpsInOneSec,
        CLOCK::time_point &timePoint1)
{
    CLOCK::time_point timePoint2{ CLOCK::now() };
    std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };
    timePoint1 = CLOCK::now();
    // Get deltaTime as float in seconds
    dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>>
        (timeSpan).count();
    float fps{ 1.f / dt };

    averageFpsTime += dt;
    fpsInSec += fps;
    fpsCnt++;
    if (averageFpsTime >= 1.f)
    {
        averageFpsInOneSec = fpsInSec / fpsCnt;
        averageFpsTime = 0.f;
        fpsInSec = 0.f;
        fpsCnt = 0;
    }

    txtStatFPS.setString("FPS: " + std::to_string(averageFpsInOneSec) + " ("
            + std::to_string(fps) + ")");
}
<commit_msg>Change colors of example<commit_after>#include <chrono>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <SFML/Graphics.hpp>
#include "TextButtonWidget.hpp"
#include "CheckBoxWidget.hpp"
#include "ConsoleWidget.hpp"
#include "GUIEnvironment.hpp"
#include "ProgressWidget.hpp"
#include "TextWidget.hpp"
#include "TextInputWidget.hpp"
#include "VerticalLayout.hpp"
#include "ScrollableWidget.hpp"
#include "WindowWidget.hpp"

typedef std::chrono::high_resolution_clock CLOCK;

void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
        float &averageFpsTime, float &fpsInSec, int &fpsCnt,
        int &averageFpsInOneSec,
        CLOCK::time_point &timePoint1);

int main()
{
    unsigned int windowWidth{ 1280 };
    unsigned int windowHeight{ 720 };
    sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, "GUI-SFML");

    sf::Font font;
    if (!font.loadFromFile("assets/fonts/LiberationSans-Regular.ttf"))
    {
        std::cout << "Error by loading Font" << std::endl;
    }

    sf::Text txtStatFPS;
    txtStatFPS.setFont(font);
    txtStatFPS.setCharacterSize(12);
    txtStatFPS.setFillColor(sf::Color::Black);
    float dt{ 0.f };
    float averageFpsTime{ 0.f };
    float fpsInSec{ 0.f };
    int fpsCnt{ 0 };
    int averageFpsInOneSec{ 0 };
    CLOCK::time_point timePoint1{ CLOCK::now() };

    gsf::GUIEnvironment guiEnvironment;
    std::unique_ptr<gsf::TextWidget> textWidget{
    std::make_unique<gsf::TextWidget>
        //012345678 9012345 678901 23456
        ("IM A TEXT\nTESTA\nTESTB\nTESTC\nS", font) };
    //textWidget->centerOrigin();
    textWidget->setBackgroundColor(sf::Color{ 192, 192, 192 });
    textWidget->setCharacterSize(60);
    textWidget->setPosition(windowWidth / 2.f + 100.f, windowHeight / 2.f - 330.f);
    guiEnvironment.addWidget(std::move(textWidget));

    std::unique_ptr<gsf::ProgressWidget> progressWidget{
        std::make_unique<gsf::ProgressWidget>(260, 40) };
    progressWidget->setPosition(460, 460);
    progressWidget->setProgress(50);
    guiEnvironment.addWidget(std::move(progressWidget));

    std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{
        std::make_unique<gsf::ScrollableWidget>(300, 200) };
    scrollableWidget->setBackgroundColor(sf::Color{ 162, 162, 162 });

    std::unique_ptr<gsf::VerticalLayout> layout{
        std::make_unique<gsf::VerticalLayout>() };
    layout->setPosition(0.f , 0.f);

    for (int i{ 0 }; i != 6; i++)
    {
        std::string textString{ "Text Num " + std::to_string(i) };
        std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>
                (textString, font, 40, sf::Color::White) };
        if (i % 2 == 0)
        {
            text->setBackgroundColor(sf::Color{ 192, 192, 192 });
        }
        else
        {
            text->setBackgroundColor(sf::Color{ 128, 128, 128 });
        }
        std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
        {
            gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
            std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
                << textWidget->getText().toAnsiString() << std::endl;
        };
        text->setOnLeftClickListener(leftClickListener);
        layout->attachChild(std::move(text));
    }

    scrollableWidget->attachChild(std::move(layout));

    std::unique_ptr<gsf::WindowWidget> windowWidget{
        std::make_unique<gsf::WindowWidget>(300.f, 200.f, "", font) };
    windowWidget->setPosition(0.f , 0.f);
    //windowWidget->setBackgroundColor(sf::Color::White);
    windowWidget->attachChild(std::move(scrollableWidget));
    windowWidget->setIsVisible(true);
    guiEnvironment.addWidget(std::move(windowWidget));

    std::unique_ptr<gsf::WindowWidget> windowWidget2{
        std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
    windowWidget2->setPosition(240.f , 40.f);
    //windowWidget2->setBackgroundColor(sf::Color::Red);
    //windowWidget2->setTopBarFillColor(sf::Color::Green);
    //windowWidget2->setCloseButtonFillColor(sf::Color::Blue);
    windowWidget2->setWindowTitle("Test");
    //windowWidget2->setWindowTitleColor(sf::Color::Red);
    guiEnvironment.addWidget(std::move(windowWidget2));

    std::unique_ptr<gsf::WindowWidget> windowWidget3{
        std::make_unique<gsf::WindowWidget>
            (300.f, 360.f, "Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT", font) };
    windowWidget3->setPosition(300.f , 60.f);
    //windowWidget3->setOutlineThickness(12.f);
    //windowWidget3->setOutlineColor(sf::Color::White);
    //windowWidget3->setBackgroundColor(sf::Color::Blue);
    guiEnvironment.addWidget(std::move(windowWidget3));

    // BUTTON TEST
    std::unique_ptr<gsf::TextButtonWidget> buttonWidget{
        std::make_unique<gsf::TextButtonWidget>
            (200.f, 80.f, "CABBBBBTTTTTTTTTTTTTTTTTTTTTTClick me", font) };
    buttonWidget->setPosition(240.f , 360.f);
    buttonWidget->setOnLeftClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Left Click\n";

            });
    buttonWidget->setOnRightClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Right Click\n";

            });
    buttonWidget->setOnMiddleClickListener(
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
            {
                std::cout << "Button Middle Click\n";

            });
    guiEnvironment.addWidget(std::move(buttonWidget));

    // SCROLLBAR TEST
    std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{
        std::make_unique<gsf::ScrollableWidget>(300, 200) };
    scrollableWidget3->setPosition(820.f, 420.f);
    scrollableWidget3->setBackgroundColor(sf::Color::Yellow);

    std::unique_ptr<gsf::VerticalLayout> layout4{
        std::make_unique<gsf::VerticalLayout>() };
    layout4->setBackgroundColor(sf::Color::Cyan);

    for (int i{0}; i != 10; i++)
    {
        std::string textString{ "Text Text Text Text Text Text Text Num "
            + std::to_string(i) };
        std::unique_ptr<gsf::TextWidget> text{
            std::make_unique<gsf::TextWidget>
                (textString, font, 40, sf::Color::White) };
        if (i % 2 == 0)
        {
            text->setBackgroundColor(sf::Color::Green);
        }
        else
        {
            text->setBackgroundColor(sf::Color::Magenta);
        }
        std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
            [] (gsf::Widget* widget, sf::Vector2f mousePos)
        {
            gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
            std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
                << textWidget->getText().toAnsiString() << std::endl;
        };
        text->setOnLeftClickListener(leftClickListener);
        //text->setBackgroundColor(sf::Color::Red);
        layout4->attachChild(std::move(text));
    }
    scrollableWidget3->attachChild(std::move(layout4));
    guiEnvironment.addWidget(std::move(scrollableWidget3));

    std::unique_ptr<gsf::TextInputWidget> textInput1{
        std::make_unique<gsf::TextInputWidget>(300.f, 60.f, font) };
    textInput1->setPosition(320.f, 520.f);
    textInput1->setBackgroundColor(sf::Color::White);
    textInput1->setIsHorizontalScrollEnabled(false);
    textInput1->setText(L"Test Text HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH :)");
    guiEnvironment.addWidget(std::move(textInput1));

    // Console Widget
    std::unique_ptr<gsf::ConsoleWidget> console1{
        std::make_unique<gsf::ConsoleWidget>(500.f, 200.f, font) };
    console1->setPosition(700.f, 200.f);
    console1->setOnCommandEnteredListener(
            [] (gsf::Widget *widget, std::wstring inputText)
            {
                std::wcout << "CommandEnteredListener command: " << inputText
                    << std::endl;
                gsf::ConsoleWidget *consoleWidget{
                    static_cast<gsf::ConsoleWidget*>(widget) };
                consoleWidget->addTextToDisplay(L"OK");
            }
    );
    guiEnvironment.addWidget(std::move(console1));

    // CheckBoxWidget
    std::unique_ptr<gsf::CheckBoxWidget> checkBox1{
        std::make_unique<gsf::CheckBoxWidget>(60, 60.f) };
    checkBox1->setPosition(10.f, 620.f);
    guiEnvironment.addWidget(std::move(checkBox1));

    while (window.isOpen())
    {
        determineFpsAndDeltaTime(txtStatFPS, dt, averageFpsTime, fpsInSec, fpsCnt,
            averageFpsInOneSec, timePoint1);
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }
            guiEnvironment.handleEvent(event);
        }
        guiEnvironment.update(dt);

        window.clear(sf::Color::White);
        window.draw(guiEnvironment);
        window.draw(txtStatFPS);
        window.display();
    }

    return 0;
}

void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
        float &averageFpsTime, float &fpsInSec, int &fpsCnt,
        int &averageFpsInOneSec,
        CLOCK::time_point &timePoint1)
{
    CLOCK::time_point timePoint2{ CLOCK::now() };
    std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };
    timePoint1 = CLOCK::now();
    // Get deltaTime as float in seconds
    dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>>
        (timeSpan).count();
    float fps{ 1.f / dt };

    averageFpsTime += dt;
    fpsInSec += fps;
    fpsCnt++;
    if (averageFpsTime >= 1.f)
    {
        averageFpsInOneSec = fpsInSec / fpsCnt;
        averageFpsTime = 0.f;
        fpsInSec = 0.f;
        fpsCnt = 0;
    }

    txtStatFPS.setString("FPS: " + std::to_string(averageFpsInOneSec) + " ("
            + std::to_string(fps) + ")");
}
<|endoftext|>


<commit_before>d0bae1ca-4b02-11e5-b74e-28cfe9171a43<commit_msg>NO CHANGES<commit_after>d0c69c61-4b02-11e5-bbc2-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <ncurses.h>
#include "node.h"
#include "B_tree.h"
#include "treeNode.h"
#include "AVLTree.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
#include <sstream>

using std::stringstream;
using std::vector;
using std::string;
using std::atoi;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;

void loadNumbers(vector<int>&);

int main(int argc, char*argv[]){
	int NodosTotales = 0;
	AVLTree Arbolito(0);
	int width, height;
	char salir = '0';
	int pruebas = 0;

	initscr();
	(void)echo();
	char opcion1 = '0';

	while(opcion1 != '3'){
		getmaxyx(curscr, height, width);

		init_pair(1, COLOR_BLUE, COLOR_BLACK);
		init_pair(2, COLOR_RED, COLOR_BLACK);

		attron(COLOR_PAIR(1));
		mvprintw(3,width-100,"DATA-BASE MODELING");

		attron(COLOR_PAIR(2));
		mvprintw(5,width-100,"1.- Arbol AVL");
		mvprintw(6,width-100,"2.- Arbol B");
		mvprintw(7,width-100,"3.- SALIR");

		mvprintw(8,width-100,"Ingrese una opcion: ");
		opcion1 = getch();

		if(opcion1 == '1'){
			char opcion2 = '1';
			while(opcion2 != '0'){
				clear();
				string ValorIngresado = "";
				char ValorIngresadoTemp[15];
				int ValorAgregar;

				mvprintw(3,width-100,"ARBOL Adelson-Velskii y Landis");
				mvprintw(7, width-50, "SALIR [0]");

				mvprintw(5,width-100,"Digite un valor para ingresar al arbol AVL: ");
				getnstr(ValorIngresadoTemp, sizeof(ValorIngresadoTemp) - 1);

				//sacar la string
				for(int i = 0; i < 16; i++){
					if(ValorIngresadoTemp[i] != ' '){
						ValorIngresado += ValorIngresadoTemp[i];
					}
				}

				int ValorAgregarTemp = atoi(ValorIngresado.c_str());
				if(ValorAgregarTemp != 0){
					ValorAgregar = ValorAgregarTemp;
					Arbolito.AddNode(ValorAgregar);
					NodosTotales++;

					pruebas = ValorAgregar;
				}else{
					opcion2 = '0';
				}

				if(opcion2 != '0'){
					mvprintw(6,width-100,"VALOR INGRESADO EXITOSAMENTE!");
					refresh();
					getch();
				}else{
					mvprintw(6,width-100,"Regresaras al menu principal");
					opcion2 = '0';
					getch();
				}
			}
		}else if(opcion1 == '2'){
			char opcion3 = '1';
			while(opcion3 != '0'){
				mvprintw(3,width-100,"ARBOL-B");
			}
		}
		clear();
	}

	//aqui termina la mierda
	getch();
	endwin();
	cout << "EL NUMERO QUE CONVERTISTE ES: " << pruebas << endl;
	Arbolito.Recorrido(Arbolito.getRootPointer());
	return 0;
}

/*int size = 0;
	int number = 0;
	int decision = 0;
	bool seguir = true;
	string word = "";
	cout << "---------------------------------------------------" << endl;
	cout << "ingrese el tamaño de su arbol: ";
	cin >> size;
	btree tree(size);
	//EL VECTOR Y EL ARREGLO VALEN PIJA
	vector<int> lista;
	int lista2[] = {21,33,77,98,12,6,31,44,28,4,3,99,101,200,14,1};

	//ESTO ESTA EN UN WHILE PERO COMO LO VAS A ACOMODAR A NCURSES, PUES NO SE QUE PUTAS HARAS
	while(seguir){
		cout << "*************************************************************************" << endl;
		cout << "1. Para Agregar. " << endl;
		cout << "2. Para Borrar. " << endl;
		cout << "3. Mostrar" << endl;
		cout << "4. Cargar arbol" << endl;
		cout << "5. Cambiar Size" << endl;
		cout << "6 salir" << endl;
		cin >> decision;

		if(decision == 1){
			//AQUI PEDIS EL NUMERO Y LO MANDAS A INSERTAR AL ARBOL, FIJATE QUE LA FUNCION TAMBIEN RECIBE A LA RAIZ DEL ARBOL
			cout << "Ingrese un numero: ";
			cin >> number;
			tree.insert(number, tree.getRoot());
		}else if(decision == 2){
			//AQUI BORRAS UN ELEMENTO
			cout << "Ingrese un numero: ";
			cin >> number;
			tree.borrar(number);
		}else if(decision == 3){
			//AQUI MOSTRAS EL ARBOL PERO ME FALTA HACER LA FUNCION
			treeNode** root = new treeNode*[1];
			root[0] = tree.getRoot();
			tree.showTree(root, 1);
		}else if(decision == 4){
			//AQUI CARGAS EL ARCHIVO DE TEXTO PERO ESTO FALLA
			//loadNumbers(lista);
			for(int i = 0; i < 16; i++){
				lista.push_back(lista2[i]);
			}
			for(int i = 0; i < 16; i++){
				tree.insert(lista[i], tree.getRoot());
			}

		}else if(decision == 5){
			//aQUI LE CAMBIAS EL SIZE EL ARBOL EN CASO DE QUE EL USUARIO QUIERA
			cout << "Nuevo Size: ";
			cin >>size;
			btree arbol(size);
			lista = tree.getKeys();

			for(int i = 0; i < lista.size(); i++){
				arbol.insert(lista[i],arbol.getRoot());
			}
			tree = arbol;
		}
		//EN ESTA COSA MERA PIJA SE SALE DEL CICLO
		decision == 6 ? seguir = false : seguir = true;
	}*/

	//ESTA FUNCION ES PARA CARGAR EL ARCHIVO
	/*void loadNumbers(vector<int>& lista){
	ifstream fentrada;
	fentrada.open("numeros.txt");
    stringstream ss;
    string numero;

    while(!fentrada.fail()){
    	char digito;
    	fentrada >> digito;
    	if(!fentrada.fail()){
    		if(digito == ','){
    			numero = ss.str();
    			ss.str("");
    			int b = atoi(numero.c_str());
    			lista.push_back(b);
    		}else{
    			ss << digito;
    		}
    	}
    }
    fentrada.close();
}*/

<commit_msg>afinando detalles<commit_after>#include <iostream>
#include <ncurses.h>
#include "node.h"
#include "B_tree.h"
#include "treeNode.h"
#include "AVLTree.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
#include <sstream>

using std::stringstream;
using std::vector;
using std::string;
using std::atoi;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;

void loadNumbers(vector<int>&);

int main(int argc, char*argv[]){
	int NodosTotales = 0;
	AVLTree Arbolito(0);
	int width, height;
	char salir = '0';
	int pruebas = 0;

	initscr();
	(void)echo();
	char opcion1 = '0';

	while(opcion1 != '3'){
		getmaxyx(curscr, height, width);

		init_pair(1, COLOR_BLUE, COLOR_BLACK);
		init_pair(2, COLOR_RED, COLOR_BLACK);

		attron(COLOR_PAIR(1));
		mvprintw(3,width-100,"DATA-BASE MODELING");

		attron(COLOR_PAIR(2));
		mvprintw(5,width-100,"1.- Arbol AVL");
		mvprintw(6,width-100,"2.- Arbol B");
		mvprintw(7,width-100,"3.- SALIR");

		mvprintw(8,width-100,"Ingrese una opcion: ");
		opcion1 = getch();

		if(opcion1 == '1'){
			char opcion2 = '1';
			while(opcion2 != '0'){
				clear();
				string ValorIngresado = "";
				char ValorIngresadoTemp[15];
				int ValorAgregar;

				mvprintw(3,width-100,"ARBOL Adelson-Velskii y Landis");
				mvprintw(7, width-50, "SALIR [0]");

				mvprintw(5,width-100,"Digite un valor para ingresar al arbol AVL: ");
				getnstr(ValorIngresadoTemp, sizeof(ValorIngresadoTemp) - 1);

				//sacar la string
				for(int i = 0; i < 16; i++){
					if(ValorIngresadoTemp[i] != ' '){
						ValorIngresado += ValorIngresadoTemp[i];
					}
				}

				int ValorAgregarTemp = atoi(ValorIngresado.c_str());
				if(ValorAgregarTemp != 0){
					ValorAgregar = ValorAgregarTemp;
					Arbolito.AddNode(ValorAgregar);
					NodosTotales++;

					pruebas = ValorAgregar;
				}else{
					opcion2 = '0';
				}

				if(opcion2 != '0'){
					mvprintw(6,width-100,"VALOR INGRESADO EXITOSAMENTE!");
					refresh();
					getch();
				}else{
					mvprintw(6,width-100,"Regresaras al menu principal");
					opcion2 = '0';
					getch();
				}
			}
		}else if(opcion1 == '2'){
			char opcion3 = '1';
			while(opcion3 != '0'){
				mvprintw(3,width-100,"ARBOL-B");
			}
		}
		clear();
	}

	//aqui termina la mierda
	getch();
	endwin();
	cout << "EL NUMERO QUE CONVERTISTE ES: " << pruebas << endl;
	Arbolito.Recorrido(Arbolito.getRootPointer());
	/*int size = 0;
	int number = 0;
	int decision = 0;
	bool seguir = true;
	string word = "";
	cout << "---------------------------------------------------" << endl;
	cout << "ingrese el tamaño de su arbol: ";
	cin >> size;
	btree tree(size);
	//EL VECTOR Y EL ARREGLO VALEN PIJA
	vector<int> lista;
	int lista2[] = {21,33,77,98,12,6,31,44,28,4,3,99,101,200,14,1};

	//ESTO ESTA EN UN WHILE PERO COMO LO VAS A ACOMODAR A NCURSES, PUES NO SE QUE PUTAS HARAS
	while(seguir){
		cout << "*************************************************************************" << endl;
		cout << "1. Para Agregar. " << endl;
		cout << "2. Para Borrar. " << endl;
		cout << "3. Mostrar" << endl;
		cout << "4. Cargar arbol" << endl;
		cout << "5. Cambiar Size" << endl;
		cout << "6 salir" << endl;
		cin >> decision;

		if(decision == 1){
			//AQUI PEDIS EL NUMERO Y LO MANDAS A INSERTAR AL ARBOL, FIJATE QUE LA FUNCION TAMBIEN RECIBE A LA RAIZ DEL ARBOL
			cout << "Ingrese un numero: ";
			cin >> number;
			tree.insert(number, tree.getRoot());
		}else if(decision == 2){
			//AQUI BORRAS UN ELEMENTO
			cout << "Ingrese un numero: ";
			cin >> number;
			tree.borrar(number);
		}else if(decision == 3){
			//AQUI MOSTRAS EL ARBOL PERO ME FALTA HACER LA FUNCION
			treeNode** root = new treeNode*[1];
			root[0] = tree.getRoot();
			tree.showTree(root, 1);
		}else if(decision == 4){
			//AQUI CARGAS EL ARCHIVO DE TEXTO PERO ESTO FALLA
			//loadNumbers(lista);
			for(int i = 0; i < 16; i++){
				lista.push_back(lista2[i]);
			}
			for(int i = 1; i < 101; i++){
				//tree.insert(lista[i], tree.getRoot());
				tree.insert(i, tree.getRoot());
			}

		}else if(decision == 5){
			//aQUI LE CAMBIAS EL SIZE EL ARBOL EN CASO DE QUE EL USUARIO QUIERA
			cout << "Nuevo Size: ";
			cin >>size;
			btree arbol(size);
			lista = tree.getKeys();

			for(int i = 0; i < lista.size(); i++){
				arbol.insert(lista[i],arbol.getRoot());
			}
			tree = arbol;
		}
		//EN ESTA COSA MERA PIJA SE SALE DEL CICLO
		decision == 6 ? seguir = false : seguir = true;
	}*/
	return 0;
}

/*
	}*/

	//ESTA FUNCION ES PARA CARGAR EL ARCHIVO
	/*void loadNumbers(vector<int>& lista){
	ifstream fentrada;
	fentrada.open("numeros.txt");
    stringstream ss;
    string numero;

    while(!fentrada.fail()){
    	char digito;
    	fentrada >> digito;
    	if(!fentrada.fail()){
    		if(digito == ','){
    			numero = ss.str();
    			ss.str("");
    			int b = atoi(numero.c_str());
    			lista.push_back(b);
    		}else{
    			ss << digito;
    		}
    	}
    }
    fentrada.close();
}*/

<|endoftext|>


<commit_before>ebc85df3-ad58-11e7-ac04-ac87a332f658<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>ec2d1170-ad58-11e7-b7a3-ac87a332f658<|endoftext|>


<commit_before>a4e59e0a-4b02-11e5-ad49-28cfe9171a43<commit_msg>Does anyone even read these anymore???<commit_after>a4f35d57-4b02-11e5-8d3d-28cfe9171a43<|endoftext|>


<commit_before>31b7b068-ad5b-11e7-9b1b-ac87a332f658<commit_msg>Did ANOTHER thing<commit_after>3242f5f8-ad5b-11e7-8820-ac87a332f658<|endoftext|>


<commit_before>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "DebugField.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>
#include "SimplexNoise.h"

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* road;
Object* tree;
SoapBubble* gBubble;
Wind* gWind;
Gravity* gGrav;
Vortex* gTurbine;

bool gDisplayInfo;
bool gStatsGraph;
bool gWireframe;

sgct::SharedDouble curr_time(0.0);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble vortFactorX(0.0);
sgct::SharedDouble vortFactorY(0.0);
sgct::SharedDouble vortFactorZ(0.0);
sgct::SharedDouble positionX(0.0);
sgct::SharedDouble positionZ(0.0);
sgct::SharedDouble radius(0.0);

void initialize();
void draw();
void myPreSyncFun();
void statsDrawFun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);
void sendMessageToExternalControl(void * data, int length);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(statsDrawFun);
	gEngine->setExternalControlCallback(externalControlCallback);
	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);

	gBubble = new SoapBubble(gEngine);

	road = new Object(gEngine);
	tree = new Object(gEngine);

	gGrav = new Gravity();
	gGrav->init(-9.81f);
	gParticles->addField(gGrav);

	gWind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	//gParticles->addField(gWind);

	gTurbine = new Vortex();
	gTurbine->init(0.0f, 0.0f, 0.0f);
	// gParticles->addField(gTurbine);

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	//Not working yet... :(
	SimplexNoise* noise = new SimplexNoise();
	noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime());

	// gParticles->addField(noise);

	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	gEngine->render();

	gParticles->destroy();
	road->deleteObject();
	delete road;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;
	delete gWind;
	delete gTurbine;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	road->loadObj("road/road.obj", "road/road.png");
	road->scale(0.2f,0.2f,0.2f);
	road->translate(0.0f, -2.0f, 5.0f);

	tree->loadObj("road/tree.obj","road/tree.png");
	tree->scale(0.05f,0.05f,0.05f);
	tree->translate(0.0f, -1.0f, -6.0f);

	gBubble->createSphere(1.5f, 100);

	gDisplayInfo = false;
	gStatsGraph = false;
	gWireframe = false;
}

void draw()
{
	double delta = gEngine->getDt();
	gWorld->drawWorld();
	gBubble->drawBubble();
	road->draw();
	tree->draw();
	gParticles->move(delta);
	gParticles->draw(delta);
}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

void myEncodeFun()
{
	sgct::SharedData::instance()->writeDouble(&curr_time);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
 	sgct::SharedData::instance()->writeDouble(&vortFactorX);
 	sgct::SharedData::instance()->writeDouble(&vortFactorY);
 	sgct::SharedData::instance()->writeDouble(&vortFactorZ);
 	sgct::SharedData::instance()->writeDouble(&positionX);
 	sgct::SharedData::instance()->writeDouble(&positionZ);
 	sgct::SharedData::instance()->writeDouble(&radius);
}

void myDecodeFun()
{
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&vortFactorX);
	sgct::SharedData::instance()->readDouble(&vortFactorY);
	sgct::SharedData::instance()->readDouble(&vortFactorZ);
	sgct::SharedData::instance()->readDouble(&positionX);
	sgct::SharedData::instance()->readDouble(&positionZ);
	sgct::SharedData::instance()->readDouble(&radius);
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false.
void statsDrawFun()
{
	gEngine->setDisplayInfoVisibility(gDisplayInfo);
	gEngine->setStatsGraphVisibility(gStatsGraph);
	gEngine->setWireframe(gWireframe);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
 			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorX.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));

		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorY.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorZ.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}
		else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorY.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorZ.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionX.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionZ.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strcmp(receivedChars, "radius") != 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			radius.setVal(tmpVal);
			gTurbine->setRadius(radius.getVal());
		}

		else if(size >= 6 && strcmp(receivedChars, "pause") != 0)
		{
			gParticles->togglePause();
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gGrav->init(-tmpVal);
		}

		else if(size >= 6 && strcmp(receivedChars, "display") != 0)
		{
			gDisplayInfo = !gDisplayInfo;
		}

		else if(size >= 6 && strcmp(receivedChars, "stats") != 0)
		{
			gStatsGraph = !gStatsGraph;
		}

		else if(size >= 6 && strcmp(receivedChars, "wire") != 0)
		{
			gWireframe = !gWireframe;
		}
	}
}
<commit_msg>Added implementation for fadeDistance in cpp file<commit_after>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "DebugField.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>
#include "SimplexNoise.h"

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* road;
Object* tree;
SoapBubble* gBubble;
Wind* gWind;
Gravity* gGrav;
Vortex* gTurbine;

bool gDisplayInfo;
bool gStatsGraph;
bool gWireframe;

sgct::SharedDouble curr_time(0.0);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble vortFactorX(0.0);
sgct::SharedDouble vortFactorY(0.0);
sgct::SharedDouble vortFactorZ(0.0);
sgct::SharedDouble positionX(0.0);
sgct::SharedDouble positionZ(0.0);
sgct::SharedDouble radius(0.0);
sgct::SharedDouble fadeDistance(0.0);

void initialize();
void draw();
void myPreSyncFun();
void statsDrawFun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);
void sendMessageToExternalControl(void * data, int length);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(statsDrawFun);
	gEngine->setExternalControlCallback(externalControlCallback);
	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);

	gBubble = new SoapBubble(gEngine);

	road = new Object(gEngine);
	tree = new Object(gEngine);

	gGrav = new Gravity();
	gGrav->init(-9.81f);
	gParticles->addField(gGrav);

	gWind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	//gParticles->addField(gWind);

	gTurbine = new Vortex();
	gTurbine->init(0.0f, 0.0f, 0.0f);
	// gParticles->addField(gTurbine);

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	//Not working yet... :(
	SimplexNoise* noise = new SimplexNoise();
	noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime());

	// gParticles->addField(noise);

	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	gEngine->render();

	gParticles->destroy();
	road->deleteObject();
	delete road;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;
	delete gWind;
	delete gTurbine;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	road->loadObj("road/road.obj", "road/road.png");
	road->scale(0.2f,0.2f,0.2f);
	road->translate(0.0f, -2.0f, 5.0f);

	tree->loadObj("road/tree.obj","road/tree.png");
	tree->scale(0.05f,0.05f,0.05f);
	tree->translate(0.0f, -1.0f, -6.0f);

	gBubble->createSphere(1.5f, 100);

	gDisplayInfo = false;
	gStatsGraph = false;
	gWireframe = false;
}

void draw()
{
	double delta = gEngine->getDt();
	gWorld->drawWorld();
	gBubble->drawBubble();
	road->draw();
	tree->draw();
	gParticles->move(delta);
	gParticles->draw(delta);
}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

void myEncodeFun()
{
	sgct::SharedData::instance()->writeDouble(&curr_time);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
 	sgct::SharedData::instance()->writeDouble(&vortFactorX);
 	sgct::SharedData::instance()->writeDouble(&vortFactorY);
 	sgct::SharedData::instance()->writeDouble(&vortFactorZ);
 	sgct::SharedData::instance()->writeDouble(&positionX);
 	sgct::SharedData::instance()->writeDouble(&positionZ);
 	sgct::SharedData::instance()->writeDouble(&radius);
 	sgct::SharedData::instance()->writeDouble(&fadeDistance);

}

void myDecodeFun()
{
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&vortFactorX);
	sgct::SharedData::instance()->readDouble(&vortFactorY);
	sgct::SharedData::instance()->readDouble(&vortFactorZ);
	sgct::SharedData::instance()->readDouble(&positionX);
	sgct::SharedData::instance()->readDouble(&positionZ);
	sgct::SharedData::instance()->readDouble(&radius);
	sgct::SharedData::instance()->readDouble(&fadeDistance);
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false.
void statsDrawFun()
{
	gEngine->setDisplayInfoVisibility(gDisplayInfo);
	gEngine->setStatsGraphVisibility(gStatsGraph);
	gEngine->setWireframe(gWireframe);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
 			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorX.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));

		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorY.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorZ.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}
		else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorY.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorZ.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionX.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionZ.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strcmp(receivedChars, "radius") != 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			radius.setVal(tmpVal);
			gTurbine->setRadius(radius.getVal());
		}

		else if(size >= 6 && strcmp(receivedChars, "pause") != 0)
		{
			gParticles->togglePause();
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gGrav->init(-tmpVal);
		}

		else if(strcmp(receivedChars, "fadeDistance") != 0)
		{
			float tmpVal = atof(receivedChars + 5);
			fadeDistance.setVal(tmpVal);
			gParticles->setFadeDistance(fadeDistance.getVal());
		}

		else if(size >= 6 && strcmp(receivedChars, "display") != 0)
		{
			gDisplayInfo = !gDisplayInfo;
		}

		else if(size >= 6 && strcmp(receivedChars, "stats") != 0)
		{
			gStatsGraph = !gStatsGraph;
		}

		else if(size >= 6 && strcmp(receivedChars, "wire") != 0)
		{
			gWireframe = !gWireframe;
		}
	}
}
<|endoftext|>


<commit_before>#include <iostream>

#include "Graphics/SplashScreen/SplashScreen.h"
#include "InputHandling/InputHandler.h"

#include "Generator/bertofGenerator/Generator.h"
#include "Logger/ScreenLogger/ScreenLogger.h"
#include "Logger/DoubleLogger/DoubleLogger.h"

int main(int argc, char *argv[]) {
	//TODO better spash screen
	//TODO better input handling
	//TODO guide on how to use it (--help)

	// Spash screen
	std::cout << SplashScreen::getSplashScreen() << std::endl;

	// Handle input
	InputHandler::handle(argc, argv);

	// Choose the generator
	GeneratorInterface *g = new bertof::Generator();

	// Generate pins
	g->generatePin("7C:5C:F8:F6:D0:B5");

	// TODO show the pins
	std::cout << "Solution:\t" << std::endl;

	// END
	std::cout << "END MAIN" << std::endl;

	return 0;
}<commit_msg>Better solution output<commit_after>#include <iostream>

#include "Graphics/SplashScreen/SplashScreen.h"
#include "InputHandling/InputHandler.h"

#include "Generator/bertofGenerator/Generator.h"

#include "Logger/ScreenLogger/ScreenLogger.h"
#include "Logger/DoubleLogger/DoubleLogger.h"

int main(int argc, char *argv[]) {
	//TODO better spash screen
	//TODO better input handling
	//TODO guide on how to use it (--help)

	// Spash screen
	std::cout << SplashScreen::getSplashScreen() << std::endl;

	// Handle input
	InputHandler::handle(argc, argv);

	// Choose the generator
	GeneratorInterface *g = new bertof::Generator();

	// Generate pins
	std::vector<Pin> solution = g->generatePin("7C:5C:F8:F6:D0:B5");

	// TODO show the pins
	std::cout << "Solution:\t" << std::endl;
	for (int i = 0; i < solution.size(); ++i) {
		std::cout << i + 1 << ":\t" << solution[i].toString() << std::endl;
	}

	// END
	std::cout << "END MAIN" << std::endl;

	return 0;
}<|endoftext|>


<commit_before>0a2a67c5-ad59-11e7-a0a7-ac87a332f658<commit_msg>Did a thing<commit_after>0addc742-ad59-11e7-bb32-ac87a332f658<|endoftext|>


<commit_before>#include "dense_map.hpp"
#include <future>
#include "MyMallocator.hpp"
#include <thread>
#include <vector>

void ConstructorTest();
void AssignmentTest();
void IteratorTest();
void DimensionTest();
void AccessorTest();
void AddRemoveTest();
void RelationalTest();

template<typename T>
using comparison_type = std::less<T>;
template<typename K, typename T>
using dense_map = custom_containers::DenseMap < K, T, comparison_type<void>,
	MyMallocator< K >, MyMallocator < T >> ;
template<typename K, typename T>
using value_type = typename dense_map<K, T>::value_type;

template<typename T, typename U>
using KeyAllocator = typename dense_map<T, U>::allocator_type::first_type;
template<typename T, typename U>
using ValueAllocator = typename dense_map<T, U>::allocator_type::second_type;

int main()
{
	std::vector<std::future<void>> futures;
	futures.reserve(8);

	futures.push_back(std::async(ConstructorTest));
	futures.push_back(std::async(AssignmentTest));
	futures.push_back(std::async(IteratorTest));
	futures.push_back(std::async(DimensionTest));
	futures.push_back(std::async(AccessorTest));
	futures.push_back(std::async(AddRemoveTest));
	futures.push_back(std::async(RelationalTest));

	std::this_thread::yield();

	for (const auto& x : futures)
	{
		x.wait();
	}
}

void ConstructorTest()
{
	std::vector<int> k{ 3, 4, 7, 11, 14, 25, 9, 1, 1, 6 };
	std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	auto init = std::initializer_list<value_type<int, int>>
		{ { 3, 5 },{ 2, 4 },{ 1, 1 },{ 4, 4 },{ 1, 3 } };
	dense_map<int, int> m1;
	dense_map<int, int> m2{ comparison_type<void>() };
	dense_map<int, int> m3(k.begin(), k.end(), v.begin(), v.end());
	dense_map<int, int> m4(v.begin(), v.end(), k.begin(), k.end(),
		KeyAllocator<int, int>(), ValueAllocator<int, int>());
	dense_map<int, int> m5(m3);
	dense_map<int, int> m6(m4, KeyAllocator<int, int>(),
		ValueAllocator<int, int>());
	dense_map<int, int> m7(std::move(m3));
	dense_map<int, int> m8(std::move(m4),
		KeyAllocator<int, int>(), ValueAllocator<int, int>());
	dense_map<int, int> m9(init);
	dense_map<int, int> m10(init,
		KeyAllocator<int, int>(), ValueAllocator<int, int>());

	(void)m1, (void)m2, (void)m3, (void)m4, (void)m5, (void)m6, (void)m7,
		(void)m8, (void)m9, (void)m10;
}
void AssignmentTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1(init);
	dense_map<int, int> m2(init);
	dense_map<int, int> m3(init);

	m1 = m2;
	m2 = std::move(m3);
	m3 = init;
}
void IteratorTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> v(init);
	auto allocInstance = v.get_allocator();

	auto i1 = v.begin();
	(void)v.end();
	auto i3 = v.rbegin();
	(void)v.rend();
	auto i5 = v.cbegin();
	(void)v.cend();
	auto i7 = v.crbegin();
	(void)v.crend();
	(void)v.begin_values();
	(void)v.end_values();
	(void)v.rbegin_values();
	(void)v.rend_values();
	(void)v.cbegin_values();
	(void)v.cend_values();
	(void)v.crbegin_values();
	(void)v.crend_values();

	(void)*i1, (void)*i3, (void)*i5, (void)*i7;
	(void)++i1, (void)++i3, (void)++i5, (void)++i7;
	(void)i1++, (void)i3++, (void)i5++, (void)i7++;
	(void)--i1, (void)--i3, (void)--i5, (void)--i7;
	(void)i1--, (void)i3--, (void)i5--, (void)i7--;
	(void)(i1 + 1), (void)(i3 + 1), (void)(i5 + 1), (void)(i7 + 1);
	(void)(i1 - 1), (void)(i3 - 1), (void)(i5 - 1), (void)(i7 - 1);
	(void)(i1 - i1), (void)(i3 - i3), (void)(i5 - i5), (void)(i7 - i7);
	i1 = i1, i3 = i3, i5 = i5, i7 = i7;
	auto i2 = i1;
	auto i4 = i3;
	auto i6 = i5;
	auto i8 = i7;

	i2[0], i4[0], i6[0], i8[0];
	i2 == i2, i4 == i4, i6 == i6, i8 == i8;
	i2 < i2, i4 < i4, i6 < i6, i8 < i8;

	(void)allocInstance;
}
void DimensionTest()
{
	dense_map<int, int> m1;

	m1.size();
	m1.max_size();
	m1.capacity();
	m1.empty();
	m1.reserve(1024);
	m1.shrink_to_fit();
}
void AccessorTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m(init);
	const dense_map<int, int>& mr = m;

	m[0] = 42, m.at(0), mr.at(0);
	(void)m.find(3); (void)mr.find(11);
	(void)m.lower_bound(5); (void)mr.lower_bound(3);
	(void)m.upper_bound(2); (void)mr.upper_bound(5);
	(void)m.equal_range(5); (void)mr.equal_range(1);
}
void AddRemoveTest()
{
	std::vector<int> k{ 3, 4, 7, 11, 14, 25, 9, 1, 1, 6 };
	std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1(init);
	int a = 24;
	int b = 42;

	m1.insert(value_type<int, int>{a, b});
	m1.insert(m1.begin() + 1, value_type<int, int>{2, 5});
	m1.insert(42, 24);
	m1.insert(m1.end() - 1, a, b);
	m1.insert(m1.end() - 1, 33, 22);
	m1.insert(k.begin(), k.end(), v.begin(), v.end());
	m1.insert(init);

	m1.insert_or_assign(value_type<int, int>{a, b});
	m1.insert_or_assign(m1.begin() + 1, value_type<int, int>{2, 5});
	m1.insert_or_assign(42, 24);
	m1.insert_or_assign(m1.end() - 1, a, b);
	m1.insert_or_assign(m1.end() - 1, 33, 22);

	m1.erase(m1.begin() + m1.size() / 2);
	m1.erase(m1.begin(), m1.begin() + m1.size() / 3);

	dense_map<int, int> m2;
	m2.swap(m1);
	m2.clear();
}
void RelationalTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1{ init };
	dense_map<int, int> m2{ init };

	m1 == m1;
	m1 == m2;
	m1 != m2;
	m1 < m2;
	m1 > m2;
	m1 <= m1;
	m2 >= m2;

	(void)m1.key_comp();
	(void)m2.value_comp();
}<commit_msg>Added a coverage test for assigning through iterators.<commit_after>#include "dense_map.hpp"
#include <future>
#include "MyMallocator.hpp"
#include <thread>
#include <vector>

void ConstructorTest();
void AssignmentTest();
void IteratorTest();
void DimensionTest();
void AccessorTest();
void AddRemoveTest();
void RelationalTest();

template<typename T>
using comparison_type = std::less<T>;
template<typename K, typename T>
using dense_map = custom_containers::DenseMap < K, T, comparison_type<void>,
	MyMallocator< K >, MyMallocator < T >> ;
template<typename K, typename T>
using value_type = typename dense_map<K, T>::value_type;

template<typename T, typename U>
using KeyAllocator = typename dense_map<T, U>::allocator_type::first_type;
template<typename T, typename U>
using ValueAllocator = typename dense_map<T, U>::allocator_type::second_type;

int main()
{
	std::vector<std::future<void>> futures;
	futures.reserve(8);

	futures.push_back(std::async(ConstructorTest));
	futures.push_back(std::async(AssignmentTest));
	futures.push_back(std::async(IteratorTest));
	futures.push_back(std::async(DimensionTest));
	futures.push_back(std::async(AccessorTest));
	futures.push_back(std::async(AddRemoveTest));
	futures.push_back(std::async(RelationalTest));

	std::this_thread::yield();

	for (const auto& x : futures)
	{
		x.wait();
	}
}

void ConstructorTest()
{
	std::vector<int> k{ 3, 4, 7, 11, 14, 25, 9, 1, 1, 6 };
	std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	auto init = std::initializer_list<value_type<int, int>>
		{ { 3, 5 },{ 2, 4 },{ 1, 1 },{ 4, 4 },{ 1, 3 } };
	dense_map<int, int> m1;
	dense_map<int, int> m2{ comparison_type<void>() };
	dense_map<int, int> m3(k.begin(), k.end(), v.begin(), v.end());
	dense_map<int, int> m4(v.begin(), v.end(), k.begin(), k.end(),
		KeyAllocator<int, int>(), ValueAllocator<int, int>());
	dense_map<int, int> m5(m3);
	dense_map<int, int> m6(m4, KeyAllocator<int, int>(),
		ValueAllocator<int, int>());
	dense_map<int, int> m7(std::move(m3));
	dense_map<int, int> m8(std::move(m4),
		KeyAllocator<int, int>(), ValueAllocator<int, int>());
	dense_map<int, int> m9(init);
	dense_map<int, int> m10(init,
		KeyAllocator<int, int>(), ValueAllocator<int, int>());

	(void)m1, (void)m2, (void)m3, (void)m4, (void)m5, (void)m6, (void)m7,
		(void)m8, (void)m9, (void)m10;
}
void AssignmentTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1(init);
	dense_map<int, int> m2(init);
	dense_map<int, int> m3(init);

	m1 = m2;
	m2 = std::move(m3);
	m3 = init;
}
void IteratorTest()
{
	int a = 33;
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> v(init);
	auto allocInstance = v.get_allocator();

	auto i1 = v.begin();
	(void)v.end();
	auto i3 = v.rbegin();
	(void)v.rend();
	auto i5 = v.cbegin();
	(void)v.cend();
	auto i7 = v.crbegin();
	(void)v.crend();
	(void)v.begin_values();
	(void)v.end_values();
	(void)v.rbegin_values();
	(void)v.rend_values();
	(void)v.cbegin_values();
	(void)v.cend_values();
	(void)v.crbegin_values();
	(void)v.crend_values();

	(*i1).second = a, (*i3).second = a, (void)*i5, (void)*i7;
	(void)++i1, (void)++i3, (void)++i5, (void)++i7;
	(void)i1++, (void)i3++, (void)i5++, (void)i7++;
	(void)--i1, (void)--i3, (void)--i5, (void)--i7;
	(void)i1--, (void)i3--, (void)i5--, (void)i7--;
	(void)(i1 + 1), (void)(i3 + 1), (void)(i5 + 1), (void)(i7 + 1);
	(void)(i1 - 1), (void)(i3 - 1), (void)(i5 - 1), (void)(i7 - 1);
	(void)(i1 - i1), (void)(i3 - i3), (void)(i5 - i5), (void)(i7 - i7);
	i1 = i1, i3 = i3, i5 = i5, i7 = i7;
	auto i2 = i1;
	auto i4 = i3;
	auto i6 = i5;
	auto i8 = i7;

	i2[0], i4[0], i6[0], i8[0];
	i2 == i2, i4 == i4, i6 == i6, i8 == i8;
	i2 < i2, i4 < i4, i6 < i6, i8 < i8;

	(void)allocInstance;
}
void DimensionTest()
{
	dense_map<int, int> m1;

	m1.size();
	m1.max_size();
	m1.capacity();
	m1.empty();
	m1.reserve(1024);
	m1.shrink_to_fit();
}
void AccessorTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m(init);
	const dense_map<int, int>& mr = m;

	m[0] = 42, m.at(0), mr.at(0);
	(void)m.find(3); (void)mr.find(11);
	(void)m.lower_bound(5); (void)mr.lower_bound(3);
	(void)m.upper_bound(2); (void)mr.upper_bound(5);
	(void)m.equal_range(5); (void)mr.equal_range(1);
}
void AddRemoveTest()
{
	std::vector<int> k{ 3, 4, 7, 11, 14, 25, 9, 1, 1, 6 };
	std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1(init);
	int a = 24;
	int b = 42;

	m1.insert(value_type<int, int>{a, b});
	m1.insert(m1.begin() + 1, value_type<int, int>{2, 5});
	m1.insert(42, 24);
	m1.insert(m1.end() - 1, a, b);
	m1.insert(m1.end() - 1, 33, 22);
	m1.insert(k.begin(), k.end(), v.begin(), v.end());
	m1.insert(init);

	m1.insert_or_assign(value_type<int, int>{a, b});
	m1.insert_or_assign(m1.begin() + 1, value_type<int, int>{2, 5});
	m1.insert_or_assign(42, 24);
	m1.insert_or_assign(m1.end() - 1, a, b);
	m1.insert_or_assign(m1.end() - 1, 33, 22);

	m1.erase(m1.begin() + m1.size() / 2);
	m1.erase(m1.begin(), m1.begin() + m1.size() / 3);

	dense_map<int, int> m2;
	m2.swap(m1);
	m2.clear();
}
void RelationalTest()
{
	auto init = std::initializer_list<value_type<int, int>>
	{ { 3, 5 }, { 2, 4 }, { 1, 1 }, { 4, 4 }, { 1, 3 } };

	dense_map<int, int> m1{ init };
	dense_map<int, int> m2{ init };

	m1 == m1;
	m1 == m2;
	m1 != m2;
	m1 < m2;
	m1 > m2;
	m1 <= m1;
	m2 >= m2;

	(void)m1.key_comp();
	(void)m2.value_comp();
}<|endoftext|>


<commit_before>#pragma once

#include <cstdlib>
#include <vector>

#include <common_types.hpp>
#include <cell.hpp>
#include <cell_group.hpp>
#include <fvm_cell.hpp>
#include <memory>
#include <recipe.hpp>
#include <thread_private_spike_store.hpp>
#include <communication/communicator.hpp>
#include <communication/global_policy.hpp>
#include <profiling/profiler.hpp>

#include "trace_sampler.hpp"

namespace nest {
namespace mc {

template <typename Cell>
class model {
public:
    using cell_group_type = cell_group<Cell>;
    using time_type = typename cell_group_type::time_type;
    using value_type = typename cell_group_type::value_type;
    using communicator_type = communication::communicator<time_type, communication::global_policy>;
    using sampler_function = typename cell_group_type::sampler_function;
    using spike_type = typename communicator_type::spike_type;
    using spike_export_function = std::function<void(const std::vector<spike_type>&)>;

    struct probe_record {
        cell_member_type id;
        probe_spec probe;
    };

    model(const recipe& rec, cell_gid_type cell_from, cell_gid_type cell_to):
        cell_from_(cell_from),
        cell_to_(cell_to),
        communicator_(cell_from, cell_to)
    {
        // generate the cell groups in parallel, with one task per cell group
        cell_groups_ = std::vector<cell_group_type>{cell_to_-cell_from_};
        threading::parallel_vector<probe_record> probes;

        threading::parallel_for::apply(cell_from_, cell_to_,
            [&](cell_gid_type i) {
                PE("setup", "cells");
                auto cell = rec.get_cell(i);
                auto idx = i-cell_from_;
                cell_groups_[idx] = cell_group_type(i, cell);

                cell_lid_type j = 0;
                for (const auto& probe: cell.probes()) {
                    cell_member_type probe_id{i,j++};
                    probes.push_back({probe_id, probe});
                }
                PL(2);
            });

        // insert probes
        probes_.assign(probes.begin(), probes.end());

        // generate the network connections
        for (cell_gid_type i=cell_from_; i<cell_to_; ++i) {
            for (const auto& cc: rec.connections_on(i)) {
                connection<time_type> conn{cc.source, cc.dest, cc.weight, cc.delay};
                communicator_.add_connection(conn);
            }
        }
        communicator_.construct();

        // Allocate an empty queue buffer for each cell group
        // These must be set initially to ensure that a queue is available for each
        // cell group for the first time step.
        current_events().resize(num_groups());
        future_events().resize(num_groups());
    }

    void reset() {
        t_ = 0.;
        for (auto& group: cell_groups_) {
            group.reset();
        }
        communicator_.reset();
    }

    time_type run(time_type tfinal, time_type dt) {
        // Calculate the size of the largest possible time integration interval
        // before communication of spikes is required.
        // If spike exchange and cell update are serialized, this is the
        // minimum delay of the network, however we use half this period
        // to overlap communication and computation.
        time_type t_interval = communicator_.min_delay()/2;

        while (t_<tfinal) {
            auto tuntil = std::min(t_+t_interval, tfinal);

            event_queues_.exchange();
            local_spikes_.exchange();

            // empty the spike buffers for the current integration period.
            // these buffers will store the new spikes generated in update_cells.
            current_spikes().clear();

            // task that updates cell state in parallel.
            auto update_cells = [&] () {
                threading::parallel_for::apply(
                    0u, cell_groups_.size(),
                     [&](unsigned i) {
                        auto &group = cell_groups_[i];

                        PE("stepping","events");
                        group.enqueue_events(current_events()[i]);
                        PL();

                        group.advance(tuntil, dt);

                        PE("events");
                        current_spikes().insert(group.spikes());
                        group.clear_spikes();
                        PL(2);
                    });
            };

            // task that performs spike exchange with the spikes generated in
            // the previous integration period, generating the postsynaptic
            // events that must be delivered at the start of the next
            // integration period at the latest.

            //TODO:
            //An improvement might be :
            //the exchange method simply exchanges spikes, and does not generate the event queues.It returns a struct that has both 1) the global spike list 2) an integer vector that describes the distribution of spikes across the ranks
            //another method called something like build_queues that takes this spike info and returns the local spikes
            //    and the callbacks can then be called on the spike information directly in the model.
            auto exchange = [&] () {
                PE("stepping", "exchange");
                auto local_spikes = previous_spikes().gather();
                local_export_callback_(local_spikes);
                future_events() = communicator_.exchange(local_spikes,
                    // send the exporter function as pointer
                    [&] (const std::vector<spike_type>& spikes){ global_export_callback_(spikes); });
                PL(2);
            };

            // run the tasks, overlapping if the threading model and number of
            // available threads permits it.
            threading::task_group g;
            g.run(exchange);
            g.run(update_cells);
            g.wait();

            t_ = tuntil;
        }
        return t_;
    }

    // only thread safe if called outside the run() method
    void add_artificial_spike(cell_member_type source) {
        add_artificial_spike(source, t_);
    }

    // only thread safe if called outside the run() method
    void add_artificial_spike(cell_member_type source, time_type tspike) {
        current_spikes().get().push_back({source, tspike});
    }

    void attach_sampler(cell_member_type probe_id, sampler_function f, time_type tfrom = 0) {
        // TODO: translate probe_id.gid to appropriate group, but for now 1-1.
        if (probe_id.gid<cell_from_ || probe_id.gid>=cell_to_) {
            return;
        }
        cell_groups_[probe_id.gid-cell_from_].add_sampler(probe_id, f, tfrom);
    }

    const std::vector<probe_record>& probes() const { return probes_; }

    std::size_t num_spikes() const { return communicator_.num_spikes(); }
    std::size_t num_groups() const { return cell_groups_.size(); }

    // register a callback that will perform a export of the global
    // spike vector
    void set_global_spike_callback(spike_export_function export_callback)
    {
        global_export_callback_ = export_callback;
    }

    // register a callback that will perform a export of the rank local
    // spike vector
    void set_local_spike_callback(spike_export_function export_callback)
    {
        local_export_callback_ = export_callback;
    }

private:
    cell_gid_type cell_from_;
    cell_gid_type cell_to_;
    time_type t_ = 0.;
    std::vector<cell_group_type> cell_groups_;
    communicator_type communicator_;
    std::vector<probe_record> probes_;

    using event_queue_type = typename communicator_type::event_queue;
    util::double_buffer< std::vector<event_queue_type> > event_queues_;

    using local_spike_store_type = thread_private_spike_store<time_type>;
    util::double_buffer< local_spike_store_type > local_spikes_;

    spike_export_function global_export_callback_;
    spike_export_function local_export_callback_;
    // Convenience functions that map the spike buffers and event queues onto
    // the appropriate integration interval.
    //
    // To overlap communication and computation, integration intervals of
    // size Delta/2 are used, where Delta is the minimum delay in the global
    // system.
    // From the frame of reference of the current integration period we
    // define three intervals: previous, current and future
    // Then we define the following :
    //      current_spikes : spikes generated in the current interval
    //      previous_spikes: spikes generated in the preceding interval
    //      current_events : events to be delivered at the start of
    //                       the current interval
    //      future_events  : events to be delivered at the start of
    //                       the next interval

    local_spike_store_type& current_spikes()  { return local_spikes_.get(); }
    local_spike_store_type& previous_spikes() { return local_spikes_.other(); }

    std::vector<event_queue_type>& current_events()  { return event_queues_.get(); }
    std::vector<event_queue_type>& future_events()   { return event_queues_.other(); }
};

} // namespace mc
} // namespace nest
<commit_msg>simple assignment of callback<commit_after>#pragma once

#include <cstdlib>
#include <vector>

#include <common_types.hpp>
#include <cell.hpp>
#include <cell_group.hpp>
#include <fvm_cell.hpp>
#include <memory>
#include <recipe.hpp>
#include <thread_private_spike_store.hpp>
#include <communication/communicator.hpp>
#include <communication/global_policy.hpp>
#include <profiling/profiler.hpp>

#include "trace_sampler.hpp"

namespace nest {
namespace mc {

template <typename Cell>
class model {
public:
    using cell_group_type = cell_group<Cell>;
    using time_type = typename cell_group_type::time_type;
    using value_type = typename cell_group_type::value_type;
    using communicator_type = communication::communicator<time_type, communication::global_policy>;
    using sampler_function = typename cell_group_type::sampler_function;
    using spike_type = typename communicator_type::spike_type;
    using spike_export_function = std::function<void(const std::vector<spike_type>&)>;

    struct probe_record {
        cell_member_type id;
        probe_spec probe;
    };

    model(const recipe& rec, cell_gid_type cell_from, cell_gid_type cell_to):
        cell_from_(cell_from),
        cell_to_(cell_to),
        communicator_(cell_from, cell_to)
    {
        // generate the cell groups in parallel, with one task per cell group
        cell_groups_ = std::vector<cell_group_type>{cell_to_-cell_from_};
        threading::parallel_vector<probe_record> probes;

        threading::parallel_for::apply(cell_from_, cell_to_,
            [&](cell_gid_type i) {
                PE("setup", "cells");
                auto cell = rec.get_cell(i);
                auto idx = i-cell_from_;
                cell_groups_[idx] = cell_group_type(i, cell);

                cell_lid_type j = 0;
                for (const auto& probe: cell.probes()) {
                    cell_member_type probe_id{i,j++};
                    probes.push_back({probe_id, probe});
                }
                PL(2);
            });

        // insert probes
        probes_.assign(probes.begin(), probes.end());

        // generate the network connections
        for (cell_gid_type i=cell_from_; i<cell_to_; ++i) {
            for (const auto& cc: rec.connections_on(i)) {
                connection<time_type> conn{cc.source, cc.dest, cc.weight, cc.delay};
                communicator_.add_connection(conn);
            }
        }
        communicator_.construct();

        // Allocate an empty queue buffer for each cell group
        // These must be set initially to ensure that a queue is available for each
        // cell group for the first time step.
        current_events().resize(num_groups());
        future_events().resize(num_groups());
    }

    void reset() {
        t_ = 0.;
        for (auto& group: cell_groups_) {
            group.reset();
        }
        communicator_.reset();
    }

    time_type run(time_type tfinal, time_type dt) {
        // Calculate the size of the largest possible time integration interval
        // before communication of spikes is required.
        // If spike exchange and cell update are serialized, this is the
        // minimum delay of the network, however we use half this period
        // to overlap communication and computation.
        time_type t_interval = communicator_.min_delay()/2;

        while (t_<tfinal) {
            auto tuntil = std::min(t_+t_interval, tfinal);

            event_queues_.exchange();
            local_spikes_.exchange();

            // empty the spike buffers for the current integration period.
            // these buffers will store the new spikes generated in update_cells.
            current_spikes().clear();

            // task that updates cell state in parallel.
            auto update_cells = [&] () {
                threading::parallel_for::apply(
                    0u, cell_groups_.size(),
                     [&](unsigned i) {
                        auto &group = cell_groups_[i];

                        PE("stepping","events");
                        group.enqueue_events(current_events()[i]);
                        PL();

                        group.advance(tuntil, dt);

                        PE("events");
                        current_spikes().insert(group.spikes());
                        group.clear_spikes();
                        PL(2);
                    });
            };

            // task that performs spike exchange with the spikes generated in
            // the previous integration period, generating the postsynaptic
            // events that must be delivered at the start of the next
            // integration period at the latest.

            //TODO:
            //An improvement might be :
            //the exchange method simply exchanges spikes, and does not generate the event queues.It returns a struct that has both 1) the global spike list 2) an integer vector that describes the distribution of spikes across the ranks
            //another method called something like build_queues that takes this spike info and returns the local spikes
            //    and the callbacks can then be called on the spike information directly in the model.
            auto exchange = [&] () {
                PE("stepping", "exchange");
                auto local_spikes = previous_spikes().gather();
                local_export_callback_(local_spikes);
                future_events() = communicator_.exchange(local_spikes,
                     global_export_callback_);
                PL(2);
            };

            // run the tasks, overlapping if the threading model and number of
            // available threads permits it.
            threading::task_group g;
            g.run(exchange);
            g.run(update_cells);
            g.wait();

            t_ = tuntil;
        }
        return t_;
    }

    // only thread safe if called outside the run() method
    void add_artificial_spike(cell_member_type source) {
        add_artificial_spike(source, t_);
    }

    // only thread safe if called outside the run() method
    void add_artificial_spike(cell_member_type source, time_type tspike) {
        current_spikes().get().push_back({source, tspike});
    }

    void attach_sampler(cell_member_type probe_id, sampler_function f, time_type tfrom = 0) {
        // TODO: translate probe_id.gid to appropriate group, but for now 1-1.
        if (probe_id.gid<cell_from_ || probe_id.gid>=cell_to_) {
            return;
        }
        cell_groups_[probe_id.gid-cell_from_].add_sampler(probe_id, f, tfrom);
    }

    const std::vector<probe_record>& probes() const { return probes_; }

    std::size_t num_spikes() const { return communicator_.num_spikes(); }
    std::size_t num_groups() const { return cell_groups_.size(); }

    // register a callback that will perform a export of the global
    // spike vector
    void set_global_spike_callback(spike_export_function export_callback)
    {
        global_export_callback_ = export_callback;
    }

    // register a callback that will perform a export of the rank local
    // spike vector
    void set_local_spike_callback(spike_export_function export_callback)
    {
        local_export_callback_ = export_callback;
    }

private:
    cell_gid_type cell_from_;
    cell_gid_type cell_to_;
    time_type t_ = 0.;
    std::vector<cell_group_type> cell_groups_;
    communicator_type communicator_;
    std::vector<probe_record> probes_;

    using event_queue_type = typename communicator_type::event_queue;
    util::double_buffer< std::vector<event_queue_type> > event_queues_;

    using local_spike_store_type = thread_private_spike_store<time_type>;
    util::double_buffer< local_spike_store_type > local_spikes_;

    spike_export_function global_export_callback_;
    spike_export_function local_export_callback_;
    // Convenience functions that map the spike buffers and event queues onto
    // the appropriate integration interval.
    //
    // To overlap communication and computation, integration intervals of
    // size Delta/2 are used, where Delta is the minimum delay in the global
    // system.
    // From the frame of reference of the current integration period we
    // define three intervals: previous, current and future
    // Then we define the following :
    //      current_spikes : spikes generated in the current interval
    //      previous_spikes: spikes generated in the preceding interval
    //      current_events : events to be delivered at the start of
    //                       the current interval
    //      future_events  : events to be delivered at the start of
    //                       the next interval

    local_spike_store_type& current_spikes()  { return local_spikes_.get(); }
    local_spike_store_type& previous_spikes() { return local_spikes_.other(); }

    std::vector<event_queue_type>& current_events()  { return event_queues_.get(); }
    std::vector<event_queue_type>& future_events()   { return event_queues_.other(); }
};

} // namespace mc
} // namespace nest
<|endoftext|>