<commit_before>#include "sqliteindexreader.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <set>
#include <sstream>
using namespace std;

SqliteIndexReader::SqliteIndexReader(SqliteIndexManager* m) :manager(m) {

    int r = sqlite3_open(manager->getDBFile(), &db);
    // any value other than SQLITE_OK is an error
    if (r != SQLITE_OK) {
        printf("could not open db\n");
        db = 0;
        return;
    }
    // speed up by being unsafe (we're only reading anyway)
    r = sqlite3_exec(db, "PRAGMA synchronous = OFF", 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not speed up database\n");
    }
}
SqliteIndexReader::~SqliteIndexReader() {
    if (db) {
        int r = sqlite3_close(db);
        if (r != SQLITE_OK) {
            printf("could not create table\n");
        }
    }
}
set<string>
split(const std::string& q) {
    set<string> terms;
    uint pos = q.find(' ');
    uint offset = 0;
    while (pos != string::npos) {
        if (pos-offset > 0) {
            terms.insert(q.substr(offset, pos-offset));
        }
        offset = pos+1;
        pos = q.find(' ', offset);
    }
    if (offset < q.length()) {
        terms.insert(q.substr(offset));
    }
    return terms;
}
string
createQuery(int n, bool filterpath) {
    // TODO: makeing a query with wildcards slows things down, so we must
    // think about reordering them
    // although we'll never be able to manage queries like 'a% b% c%'
    ostringstream q;
    q << "select path";
    if (n > 0) q <<",";
    // the points for a file is the sum of the fraction of the total occurances
    // of that word in this file
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        if (i > 0) q<<"+";
        q << "f"<<a<<".count*1.0/w"<<a<<".count";
    }
    if (n > 0) {
    q <<" p ";
    }
    q <<" from ";
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"words w"<<a<<",";
    }
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"filewords f"<<a<<",";
    }
    q <<"files where ";
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"w"<<a<<".word like ? and w"<<a<<".wordid = f"<<a<<".wordid and ";
    }
    for (int i=1; i<n; ++i) {
        char a = i+'a'-1;
        char b = i+'a';
        q <<"f"<<a<<".fileid = f"<<b<<".fileid and ";
    }
    if (n > 0) {
        q <<"fa.fileid = files.fileid ";
    }
    if (filterpath) {
        if (n > 0) q <<"and ";
        q <<"files.path like ? ";
    }
    if (n > 0) q <<"order by p ";
    q <<"limit 100";
    return q.str();
}
vector<string>
SqliteIndexReader::query(const std::string& query) {
    string q = query;
    // replace * by %
    size_t p = q.find('*');
    while (p != string::npos) {
        q.replace(p, 1, "%");
        p = q.find('*');
    }
    // replace ? by _
    p = q.find('?');
    while (p != string::npos) {
        q.replace(p, 1, "_");
        p = q.find('?');
    }
    // split up in terms
    set<string> terms = split(q);
    std::vector<std::string> results;
    if (terms.size() == 0) return results;
    string pathfilter;
    set<string>::iterator i = terms.begin();
    while (i != terms.end()) {
        if (i->substr(0, 5) == "path:") {
            pathfilter = i->substr(5);
            terms.erase(i);
            i = terms.begin();
        } else {
            i++;
        }
    }
    if (terms.size() == 0 && pathfilter.length() == 0) return results;

    string sql = createQuery(terms.size(), pathfilter.length() > 0);
    printf("%s\n", sql.c_str());

    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare query '%s': %s\n", sql.c_str(),
            sqlite3_errmsg(db));
        manager->deref();
        return results;
    }
    int j = 1;
    for (i=terms.begin(); i!=terms.end(); ++i) {
        sqlite3_bind_text(stmt, j++, i->c_str(), i->length(),
            SQLITE_STATIC);
    }
    if (pathfilter.length() > 0) {
        sqlite3_bind_text(stmt, j, pathfilter.c_str(), pathfilter.length(),
            SQLITE_STATIC);
    }
    r = sqlite3_step(stmt);
    while (r == SQLITE_ROW) {
        results.push_back((const char*)sqlite3_column_text(stmt, 0));
        r = sqlite3_step(stmt);
    }
    if (r != SQLITE_DONE) {
        printf("error reading query results: %s\n", sqlite3_errmsg(db));
    }
    sqlite3_finalize(stmt);
    manager->deref();
    return results;
}
map<string, time_t>
SqliteIndexReader::getFiles(char depth) {
    map<string, time_t> files;
    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, "select path, mtime from files where depth = ?",
        0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare query: %s\n", sqlite3_errmsg(db));
        manager->deref();
        return files;
    }
    sqlite3_bind_int(stmt, 1, depth);
    r = sqlite3_step(stmt);
    while (r == SQLITE_ROW) {
        const char *path = (const char*)sqlite3_column_text(stmt, 0);
        time_t mtime = sqlite3_column_int(stmt, 1);
        files[path] = mtime;
        r = sqlite3_step(stmt);
    }
    if (r != SQLITE_DONE) {
        printf("error reading query results: %s\n", sqlite3_errmsg(db));
    }
    sqlite3_finalize(stmt);
    manager->deref();
    return files;
}
<commit_msg>Group query results to avoid duplicate filenames.<commit_after>#include "sqliteindexreader.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <set>
#include <sstream>
using namespace std;

SqliteIndexReader::SqliteIndexReader(SqliteIndexManager* m) :manager(m) {

    int r = sqlite3_open(manager->getDBFile(), &db);
    // any value other than SQLITE_OK is an error
    if (r != SQLITE_OK) {
        printf("could not open db\n");
        db = 0;
        return;
    }
    // speed up by being unsafe (we're only reading anyway)
    r = sqlite3_exec(db, "PRAGMA synchronous = OFF", 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not speed up database\n");
    }
}
SqliteIndexReader::~SqliteIndexReader() {
    if (db) {
        int r = sqlite3_close(db);
        if (r != SQLITE_OK) {
            printf("could not create table\n");
        }
    }
}
set<string>
split(const std::string& q) {
    set<string> terms;
    uint pos = q.find(' ');
    uint offset = 0;
    while (pos != string::npos) {
        if (pos-offset > 0) {
            terms.insert(q.substr(offset, pos-offset));
        }
        offset = pos+1;
        pos = q.find(' ', offset);
    }
    if (offset < q.length()) {
        terms.insert(q.substr(offset));
    }
    return terms;
}
string
createQuery(int n, bool filterpath) {
    // TODO: makeing a query with wildcards slows things down, so we must
    // think about reordering them
    // although we'll never be able to manage queries like 'a% b% c%'
    ostringstream q;
    q << "select path";
    if (n > 0) q <<", sum(";
    // the points for a file is the sum of the fraction of the total occurances
    // of that word in this file
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        if (i > 0) q<<"+";
        q << "f"<<a<<".count*1.0/w"<<a<<".count";
    }
    if (n > 0) {
    q <<") p ";
    }
    q <<" from ";
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"words w"<<a<<",";
    }
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"filewords f"<<a<<",";
    }
    q <<"files where ";
    for (int i=0; i<n; ++i) {
        char a = i+'a';
        q <<"w"<<a<<".word like ? and w"<<a<<".wordid = f"<<a<<".wordid and ";
    }
    for (int i=1; i<n; ++i) {
        char a = i+'a';
        q <<"fa.fileid = f"<<a<<".fileid and ";
    }
    if (n > 0) {
        q <<"fa.fileid = files.fileid ";
    }
    if (filterpath) {
        if (n > 0) q <<"and ";
        q <<"files.path like ? ";
    }
    if (n > 0) q <<"group by fa.fileid order by p ";
    q <<"limit 100";
    return q.str();
}
vector<string>
SqliteIndexReader::query(const std::string& query) {
    string q = query;
    // replace * by %
    size_t p = q.find('*');
    while (p != string::npos) {
        q.replace(p, 1, "%");
        p = q.find('*');
    }
    // replace ? by _
    p = q.find('?');
    while (p != string::npos) {
        q.replace(p, 1, "_");
        p = q.find('?');
    }
    // split up in terms
    set<string> terms = split(q);
    std::vector<std::string> results;
    if (terms.size() == 0) return results;
    string pathfilter;
    set<string>::iterator i = terms.begin();
    while (i != terms.end()) {
        if (i->substr(0, 5) == "path:") {
            pathfilter = i->substr(5);
            terms.erase(i);
            i = terms.begin();
        } else {
            i++;
        }
    }
    if (terms.size() == 0 && pathfilter.length() == 0) return results;

    string sql = createQuery(terms.size(), pathfilter.length() > 0);
    printf("%s\n", sql.c_str());

    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare query '%s': %s\n", sql.c_str(),
            sqlite3_errmsg(db));
        manager->deref();
        return results;
    }
    int j = 1;
    for (i=terms.begin(); i!=terms.end(); ++i) {
        sqlite3_bind_text(stmt, j++, i->c_str(), i->length(),
            SQLITE_STATIC);
    }
    if (pathfilter.length() > 0) {
        sqlite3_bind_text(stmt, j, pathfilter.c_str(), pathfilter.length(),
            SQLITE_STATIC);
    }
    r = sqlite3_step(stmt);
    while (r == SQLITE_ROW) {
        results.push_back((const char*)sqlite3_column_text(stmt, 0));
        r = sqlite3_step(stmt);
    }
    if (r != SQLITE_DONE) {
        printf("error reading query results: %s\n", sqlite3_errmsg(db));
    }
    sqlite3_finalize(stmt);
    manager->deref();
    return results;
}
map<string, time_t>
SqliteIndexReader::getFiles(char depth) {
    map<string, time_t> files;
    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, "select path, mtime from files where depth = ?",
        0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare query: %s\n", sqlite3_errmsg(db));
        manager->deref();
        return files;
    }
    sqlite3_bind_int(stmt, 1, depth);
    r = sqlite3_step(stmt);
    while (r == SQLITE_ROW) {
        const char *path = (const char*)sqlite3_column_text(stmt, 0);
        time_t mtime = sqlite3_column_int(stmt, 1);
        files[path] = mtime;
        r = sqlite3_step(stmt);
    }
    if (r != SQLITE_DONE) {
        printf("error reading query results: %s\n", sqlite3_errmsg(db));
    }
    sqlite3_finalize(stmt);
    manager->deref();
    return files;
}
<|endoftext|>


<commit_before>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * main.cpp
 *
 * author: ISHII 2bit
 * mail:   2bit@backspace.tokyo
 *
 * **** **** **** **** **** **** **** **** */

#include "bit_by_bit.hpp"

void reusable_array_test();
void byte_array_test();
void multithread_test(size_t num);
void range_test();
void iterator_test();

int main(int argc, char *argv[]) {
    reusable_array_test();
    byte_array_test();
    multithread_test(4);
    range_test();
    iterator_test();
}

#pragma mark reusable_array_test

#include <cassert>
#include <iostream>

struct particle {
    int life_time;
    int age;
    int name;

    particle() {}
    particle(int life_time, int name)
        : life_time(life_time)
        , name(name)
        , age(0) {}

    void init(int life_time, int name) {
        this->life_time = life_time;
        this->name = name;
        this->age = 0;
    }

    bool update() {
        return ++age < life_time;
    }

    void print() const {
        std::cout << name << ", " << (life_time - age) << std::endl;
    }
};

constexpr int loop_num(1);
constexpr int elem_num(10);

void reusable_array_test() {
    bbb::random::set_seed_mt(0);
    auto a = bbb::random::mt();
    bbb::random::set_seed_mt(0);
    auto b = bbb::random::mt();
    bbb::random::set_seed_mt(1);
    auto c = bbb::random::mt();
    assert(a == b);
    assert(a != c);

    bbb::stop_watch watch;
    watch.start();

    {
        bbb::random::set_seed_mt(0);
        bbb::reusable_array<particle, elem_num> f;
        watch.rap();

        for(int k = 0; k++ < loop_num;) {
            do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());
            while(f.current_size()) {
                f.update();
            }
        }

        watch.rap();
        std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
    }

    {
        bbb::random::set_seed_mt(0);
        bbb::shared_vector<particle> f;
        watch.rap();

        for(int k = 0; k++ < loop_num;) {
            for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));
            auto wrapper = bbb::make_reverse(f);
            while(f.size()) for(auto e : wrapper) if(!e->update()) {
                e = f.back();
                f.pop_back();
            }
        }

        watch.rap();
        std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
    }
}

void byte_array_test() {
    bbb::byte_array<int> barr{0x7FFFFFFF};
    for(auto i = 0; i < barr.size(); i++) {
        std::cout << (int)barr[i] << std::endl;
    }
    for(auto &b : barr) {
        std::cout << (int)b << std::endl;
    }
};

void multithread_test(size_t num) {
    size_t sum = 0;
    bool is_run = true;
    bbb::stop_watch watch;
    watch.start();
    bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {
        while(is_run) {
            if(mutex.try_lock()) {
                sum++;
                mutex.unlock();
            }
            bbb::sleep_nanoseconds(50);
        }
    });

    while(is_run) {
        bbb::sleep_milliseconds(10);
        auto lock(manager.lock_guard());
        if(100000 < sum) {
            is_run = false;
            manager.join();
        }
    }
    watch.rap();
    std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl;
}

void range_test() {
    {
        std::vector<int> vec;
        bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); });
        bbb::for_each(vec, [](int &x) { x *= 2; });

        for(auto v : bbb::enumerate(vec)) {
            std::cout << v.index << ", " << v.value << std::endl;
            v.value *= 2;
        }
        for(auto v : bbb::enumerate(vec)) {
            std::cout << v.index << ", " << v.value << std::endl;
        }
    }

    {
        const std::vector<int> cvec{1, 2, 3};
        for(auto v : bbb::enumerate(cvec)) {
            std::cout << v.index << ", " << v.value << std::endl;
        }
    }
    std::cout << std::endl;

    std::vector<std::string> svec{"a", "hoge", "foo"};
    for(auto &v : bbb::enumerate(svec)) {
        std::cout << v.index << ", " << v.value << std::endl;
    }
    for(const auto &v : bbb::enumerate(svec)) {
        std::cout << v.index << ", " << v.value << std::endl;
    }
}

#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <map>
#include <string>

struct vectroid
    : bbb::iterator_delegation<std::vector<int>> {
    std::vector<int> body;
    vectroid() : delegation(body) {};
};

struct mappoid : bbb::iterator_delegation<std::map<int, int>> {
    std::map<int, int> body;
    mappoid() : delegation(body) {};
};

struct introid : bbb::iterator_delegation<int> {
    int body;
    introid() : delegation(body) {};
};

void iterator_test() {
    static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_iterator, "vector<int> has iterator");
    static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_reverse_iterator, "vector<int> has reverse_iterator");
    std::cout << "std::map<int, int>::iterator " << bbb::iteratable_class_traits<std::map<int, int>>::has_iterator << std::endl;
    std::cout << "std::string::iterator " << bbb::iteratable_class_traits<std::string>::has_iterator << std::endl;
    std::cout << "int::iterator " << bbb::iteratable_class_traits<int>::has_iterator << std::endl;
    std::cout << "bbb::iterator_delegation<std::vector<int>>::iterator " << bbb::iteratable_class_traits<bbb::iterator_delegation<std::vector<int>>>::has_iterator << std::endl;

    std::cout << std::endl;

    std::cout << "vector has_insert " << bbb::iteratable_class_traits<std::vector<int>>::has_insert << std::endl;
    std::cout << "vector has_push_back " << bbb::iteratable_class_traits<std::vector<int>>::has_push_back << std::endl;
    std::cout << "vector has_push_front " << bbb::iteratable_class_traits<std::vector<int>>::has_push_front << std::endl;

    std::cout << "deque has_insert " << bbb::iteratable_class_traits<std::deque<int>>::has_insert << std::endl;
    std::cout << "deque has_push_back " << bbb::iteratable_class_traits<std::deque<int>>::has_push_back << std::endl;
    std::cout << "deque has_push_front " << bbb::iteratable_class_traits<std::deque<int>>::has_push_front << std::endl;

    std::cout << "list has_insert " << bbb::iteratable_class_traits<std::list<int>>::has_insert << std::endl;
    std::cout << "list has_push_back " << bbb::iteratable_class_traits<std::list<int>>::has_push_back << std::endl;
    std::cout << "list has_push_front " << bbb::iteratable_class_traits<std::list<int>>::has_push_front << std::endl;

    std::cout << "queue has_insert " << bbb::iteratable_class_traits<std::queue<int>>::has_insert << std::endl;
    std::cout << "queue has_push_back " << bbb::iteratable_class_traits<std::queue<int>>::has_push_back << std::endl;
    std::cout << "queue has_push_front " << bbb::iteratable_class_traits<std::queue<int>>::has_push_front << std::endl;

    std::cout << "int has_insert " << bbb::iteratable_class_traits<int>::has_insert << std::endl;
    std::cout << "int has_push_back " << bbb::iteratable_class_traits<int>::has_push_back << std::endl;
    std::cout << "int has_push_front " << bbb::iteratable_class_traits<int>::has_push_front << std::endl;

    vectroid v;
    v.body.push_back(-1);
    v.body.push_back(-2);
    v.body.push_back(-3);
    std::vector<int> src{1, 2, 3, 4};
    std::copy(src.begin(), src.end(), std::back_inserter(v));
    std::copy(src.begin(), src.end(), std::inserter(v, v.begin()));
    for(const auto &i : v) {
        std::cout << i << std::endl;
    }

    mappoid m;
    m.body.insert(std::make_pair(2, 3));
    m.body.insert(std::make_pair(6, 7));
    m.body.insert(std::make_pair(4, 5));
    m.body.insert(std::make_pair(8, 9));
    for(const auto &p : m) {
        std::cout << p.first << ", " << p.second << std::endl;
    }
    introid i;
//	for(auto &it : i) {} // Error: delegated type doesn't provide iterator
}<commit_msg>update test<commit_after>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * main.cpp
 *
 * author: ISHII 2bit
 * mail:   2bit@backspace.tokyo
 *
 * **** **** **** **** **** **** **** **** */

#include "bit_by_bit.hpp"

void reusable_array_test();
void byte_array_test();
void multithread_test(size_t num);
void range_test();
namespace iterator_delegation { void test(); };

int main(int argc, char *argv[]) {
    reusable_array_test();
    byte_array_test();
    multithread_test(4);
    range_test();
    iterator_delegation::test();
}

#pragma mark reusable_array_test

#include <cassert>
#include <iostream>

struct particle {
    int life_time;
    int age;
    int name;

    particle() {}
    particle(int life_time, int name)
        : life_time(life_time)
        , name(name)
        , age(0) {}

    void init(int life_time, int name) {
        this->life_time = life_time;
        this->name = name;
        this->age = 0;
    }

    bool update() {
        return ++age < life_time;
    }

    void print() const {
        std::cout << name << ", " << (life_time - age) << std::endl;
    }
};

constexpr int loop_num(1);
constexpr int elem_num(10);

void reusable_array_test() {
    bbb::random::set_seed_mt(0);
    auto a = bbb::random::mt();
    bbb::random::set_seed_mt(0);
    auto b = bbb::random::mt();
    bbb::random::set_seed_mt(1);
    auto c = bbb::random::mt();
    assert(a == b);
    assert(a != c);

    bbb::stop_watch watch;
    watch.start();

    {
        bbb::random::set_seed_mt(0);
        bbb::reusable_array<particle, elem_num> f;
        watch.rap();

        for(int k = 0; k++ < loop_num;) {
            do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());
            while(f.current_size()) {
                f.update();
            }
        }

        watch.rap();
        std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
    }

    {
        bbb::random::set_seed_mt(0);
        bbb::shared_vector<particle> f;
        watch.rap();

        for(int k = 0; k++ < loop_num;) {
            for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));
            auto wrapper = bbb::make_reverse(f);
            while(f.size()) for(auto e : wrapper) if(!e->update()) {
                e = f.back();
                f.pop_back();
            }
        }

        watch.rap();
        std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
    }
}

void byte_array_test() {
    bbb::byte_array<int> barr{0x7FFFFFFF};
    for(auto i = 0; i < barr.size(); i++) {
        std::cout << (int)barr[i] << std::endl;
    }
    for(auto &b : barr) {
        std::cout << (int)b << std::endl;
    }
};

void multithread_test(size_t num) {
    size_t sum = 0;
    bool is_run = true;
    bbb::stop_watch watch;
    watch.start();
    bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {
        while(is_run) {
            if(mutex.try_lock()) {
                sum++;
                mutex.unlock();
            }
            bbb::sleep_nanoseconds(50);
        }
    });

    while(is_run) {
        bbb::sleep_milliseconds(10);
        auto lock(manager.lock_guard());
        if(100000 < sum) {
            is_run = false;
            manager.join();
        }
    }
    watch.rap();
    std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl;
}

void range_test() {
    {
        std::vector<int> vec;
        bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); });
        bbb::for_each(vec, [](int &x) { x *= 2; });

        for(auto v : bbb::enumerate(vec)) {
            std::cout << v.index << ", " << v.value << std::endl;
            v.value *= 2;
        }
        for(auto v : bbb::enumerate(vec)) {
            std::cout << v.index << ", " << v.value << std::endl;
        }
    }

    {
        const std::vector<int> cvec{1, 2, 3};
        for(auto v : bbb::enumerate(cvec)) {
            std::cout << v.index << ", " << v.value << std::endl;
        }
    }
    std::cout << std::endl;

    std::vector<std::string> svec{"a", "hoge", "foo"};
    for(auto &v : bbb::enumerate(svec)) {
        std::cout << v.index << ", " << v.value << std::endl;
    }
    for(const auto &v : bbb::enumerate(svec)) {
        std::cout << v.index << ", " << v.value << std::endl;
    }
}

#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <map>
#include <string>

namespace iterator_delegation {
    struct vectroid
        : bbb::iterator_delegation<std::vector<int>> {
        std::vector<int> body;

        vectroid() : delegation(body) { };
    };

    struct mappoid : bbb::iterator_delegation<std::map<int, int>> {
        std::map<int, int> body;

        mappoid() : delegation(body) { };
    };

    struct introid : bbb::iterator_delegation<int> {
        int body;

        introid() : delegation(body) { };
    };

    void test() {
        static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_iterator, "vector<int> has iterator");
        static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_reverse_iterator,
                      "vector<int> has reverse_iterator");
        static_assert(bbb::iteratable_class_traits<std::map<int, int>>::has_iterator, "map<int, int> has_iterator");
        static_assert(bbb::iteratable_class_traits<std::string>::has_iterator);
        static_assert(!bbb::iteratable_class_traits<int>::has_iterator);
        static_assert(bbb::iteratable_class_traits<bbb::iterator_delegation<std::vector<int>>>::has_iterator);

        static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_insert);
        static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_push_back);
        static_assert(!bbb::iteratable_class_traits<std::vector<int>>::has_push_front);

        static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_insert);
        static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_back);
        static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_front);

        static_assert(bbb::iteratable_class_traits<std::list<int>>::has_insert);
        static_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_back);
        static_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_front);

        static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_insert);
        static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_back);
        static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_front);

        static_assert(!bbb::iteratable_class_traits<int>::has_insert);
        static_assert(!bbb::iteratable_class_traits<int>::has_push_back);
        static_assert(!bbb::iteratable_class_traits<int>::has_push_front);

        vectroid v;
        v.body.push_back(-1);
        v.body.push_back(-2);
        v.body.push_back(-3);
        std::vector<int> src{1, 2, 3, 4};
        std::copy(src.begin(), src.end(), std::back_inserter(v));
        std::copy(src.begin(), src.end(), std::inserter(v, v.begin()));
        for (const auto &i : v) {
            std::cout << i << std::endl;
        }

        mappoid m;
        m.body.insert(std::make_pair(2, 3));
        m.body.insert(std::make_pair(6, 7));
        m.body.insert(std::make_pair(4, 5));
        m.body.insert(std::make_pair(8, 9));
        for (const auto &p : m) {
            std::cout << p.first << ", " << p.second << std::endl;
        }
        introid i;
        //	for(auto &it : i) {} // Error: delegated type doesn't provide iterator
    }
};<|endoftext|>


<commit_before>// Copyright 2012 UT-Battelle, LLC.  See LICENSE.txt for more information.
#include <QtGui/QApplication>
#include "ELMainWindow.h"

#include <eavlDataSet.h>
#include <eavlException.h>
#include <eavlCUDA.h>

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

        QApplication a(argc, argv);

        ELMainWindow w;

        // want a bigger font? hardcode it here
        if (true)
        {
            QFont f = w.font();
            f.setPixelSize(20);
            w.setFont(f);
        }

        if (argc == 1)
            ;// do nothing
        else if (argc == 2)
            w.OpenFile(argv[1]);
        else
            cerr << "Error: unexpected extra arguments\n";

        w.show();

        return a.exec();
    }
    catch (const eavlException &e)
    {
        cerr << e.GetErrorText() << endl;
        return -1;
    }
    return 0;
}
<commit_msg>small hack to allow bigger font size for demos.<commit_after>// Copyright 2012 UT-Battelle, LLC.  See LICENSE.txt for more information.
#include <QtGui/QApplication>
#include "ELMainWindow.h"

#include <eavlDataSet.h>
#include <eavlException.h>
#include <eavlCUDA.h>

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

        QApplication a(argc, argv);

        ELMainWindow w;

        // want a bigger font? hardcode it here
        if (argc == 3)
        {
            QFont f = w.font();
            f.setPixelSize(atoi(argv[2]));
            w.setFont(f);
        }

        if (argc == 1)
            ;// do nothing
        else if (argc >= 2)
            w.OpenFile(argv[1]);
        else
            cerr << "Error: unexpected extra arguments\n";

        w.show();

        return a.exec();
    }
    catch (const eavlException &e)
    {
        cerr << e.GetErrorText() << endl;
        return -1;
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
using namespace std;
int main()
{
	int level;
	int pv;
	int vel;
	int Errore;
	int fine;
	int exp_agg;
	int exp;
	unsigned int Pokemonum;
	string Pokemon;
	string Shiny;
	string scheda;
	string fisico = ":fisico:";
	string mosse_apprese;
	string azione;
	string lista_mosse_if;
	string nome_pokemon;
	string ant_move;
	string mossa[3];
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Pokémon.\n");
	printf("Numero Pokemon: ");
	cin >> Pokemonum;
	switch (Pokemonum)
		{
		case 1:
			nome_pokemon = "Bulbasaur";
			printf("Hai scelto Bulbasaur!\nIl Pokémon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 23;
			vel = 45;
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Bulbasaur shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Bulbasaur NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
		exp_agg = 2;
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 4:
			printf("Hai scelto Charmander!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Charmander";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Charmander shiny!\n");
			Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/charmander.gif]\nCharmander :fuoco:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Charmander NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/charmander.gif]\nCharmander :fuoco:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu";
		break;

		case 7:
			printf("Hai scelto Squirtle!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Squirtle";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Squirtle shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/squirtle.gif]\nSquirtle :acqua:\n";
			}
			else
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Squirtle NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/squirtle.gif]\nSquirtle :acqua:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu 2";
		break;

		default:
			printf("Non ancora implementato\n");
			cin.get();
		break;
		}
	do
	{
	    printf("Digita il livello del Pokemon!\n");
 	    cin >> level;
	} while(level<=0 or level>100);
	vel = vel + level - 1;
	int pot_da_aggiungere;
	if (level >= 51)
	{
		pv = (49 * 3) + ((level - 50) * 5) + pv;
		pot_da_aggiungere = 49 + (level - 50) * 2;
	}
	else
	if (level <= 50)
	{
		pv = (level - 1) * 3 + pv;
		pot_da_aggiungere = level - 1;
	}
	int pot_azione = 4 + pot_da_aggiungere;
	printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
	cin >>	 lista_mosse_if;
	if (lista_mosse_if == "Sì" or lista_mosse_if == "sì" or lista_mosse_if == "Si" or lista_mosse_if == "si")
	{
		cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
	}
	printf("Inserisci la mossa numero 1\n");
	cin>>mossa[0];
	printf("Inserisci la mossa numero 2\n");
	cin>>mossa[1];
	printf("Inserisci la mossa numero 3\n");
	cin>>mossa[2];
	printf("Inserisci la mossa numero 4\n");
	cin>>mossa[3];
	exp = exp_agg * level;
	scheda = Pokemon + "Lv " + to_string(level) + "Pv " + to_string(pv) + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "EXP: 0/" + to_string(exp);
	Pokemon = Pokemon, "Lv ", level, "Pv ", pv, "Vel ", vel;
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt'!\n");
	FILE * pFile;
	pFile = fopen("Scheda.txt", "w");
	if (pFile != NULL)
	{
		fputs(scheda.c_str(), pFile);
		fclose(pFile);
	}
}

// else
// {
// 	cout<< "\nQuesto ID non esiste! Sicuro di non aver sbagliato?\nDigita '1' per riavviare il programma, oppure digita '0' per chiudere il programma.\n";
// 	cin >> Errore;
// 	if(Errore == 0)
// 	{
// 		return 0;
// 	}
// 	if(Errore == 1)
//
// 	{
// 		return main();
// 	}
// }
// cout << "Vuoi creare un altra scheda?\nSì = 1 	No = 0\n";
// cin >> fine;
// if(fine == 1)
// {
// 	return main();
// 	}
// if(fine == 0)
// {
// 	return 0;
// }
<commit_msg>Controllo numero<commit_after>#include <iostream>
using namespace std;
int main()
{
	int level;
	int pv;
	int vel;
	int Errore;
	int fine;
	int exp_agg;
	int exp;
	unsigned int Pokemonum;
	string Pokemon;
	string Shiny;
	string scheda;
	string fisico = ":fisico:";
	string mosse_apprese;
	string azione;
	string lista_mosse_if;
	string nome_pokemon;
	string ant_move;
	string mossa[3];
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Pokémon.\n");
	do{
	printf("Numero Pokemon: ");
	cin >> Pokemonum;
	}while(Pokemonum<=0 or Pokemonum>802);
	switch (Pokemonum)
		{
		case 1:
			nome_pokemon = "Bulbasaur";
			printf("Hai scelto Bulbasaur!\nIl Pokémon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 23;
			vel = 45;
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Bulbasaur shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Bulbasaur NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/bulbasaur.gif]\nBulbasaur :erba: :veleno:\n";
			}
		exp_agg = 2;
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 4:
			printf("Hai scelto Charmander!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Charmander";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Charmander shiny!\n");
			Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/charmander.gif]\nCharmander :fuoco:\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Charmander NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/charmander.gif]\nCharmander :fuoco:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu";
		break;

		case 7:
			printf("Hai scelto Squirtle!\nIl Pokemon e' shiny?\nRispondi con 'Si' o 'No'\n");
			pv = 15;
			vel = 65;
			nome_pokemon = "Squirtle";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				printf("Ok, hai selezionato Squirtle shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/squirtle.gif]\nSquirtle :acqua:\n";
			}
			else
			if (Shiny == "No" or Shiny == "no")
			{
				printf("Ok, hai selezionato Squirtle NON shiny!\n");
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/squirtle.gif]\nSquirtle :acqua:\n";
			}
		exp_agg=2;
		mosse_apprese= "Te lo fai tu 2";
		break;

		default:
			printf("Non ancora implementato\n");
			cin.get();
		break;
		}
	do
	{
	    printf("Digita il livello del Pokemon!\n");
 	    cin >> level;
	} while(level<=0 or level>100);
	vel = vel + level - 1;
	int pot_da_aggiungere;
	if (level >= 51)
	{
		pv = (49 * 3) + ((level - 50) * 5) + pv;
		pot_da_aggiungere = 49 + (level - 50) * 2;
	}
	else
	if (level <= 50)
	{
		pv = (level - 1) * 3 + pv;
		pot_da_aggiungere = level - 1;
	}
	int pot_azione = 4 + pot_da_aggiungere;
	printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
	cin >>	 lista_mosse_if;
	if (lista_mosse_if == "Sì" or lista_mosse_if == "sì" or lista_mosse_if == "Si" or lista_mosse_if == "si")
	{
		cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
	}
	printf("Inserisci la mossa numero 1\n");
	cin>>mossa[0];
	printf("Inserisci la mossa numero 2\n");
	cin>>mossa[1];
	printf("Inserisci la mossa numero 3\n");
	cin>>mossa[2];
	printf("Inserisci la mossa numero 4\n");
	cin>>mossa[3];
	exp = exp_agg * level;
	scheda = Pokemon + "Lv " + to_string(level) + "Pv " + to_string(pv) + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "EXP: 0/" + to_string(exp);
	Pokemon = Pokemon, "Lv ", level, "Pv ", pv, "Vel ", vel;
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt'!\n");
	FILE * pFile;
	pFile = fopen("Scheda.txt", "w");
	if (pFile != NULL)
	{
		fputs(scheda.c_str(), pFile);
		fclose(pFile);
	}
}

// else
// {
// 	cout<< "\nQuesto ID non esiste! Sicuro di non aver sbagliato?\nDigita '1' per riavviare il programma, oppure digita '0' per chiudere il programma.\n";
// 	cin >> Errore;
// 	if(Errore == 0)
// 	{
// 		return 0;
// 	}
// 	if(Errore == 1)
//
// 	{
// 		return main();
// 	}
// }
// cout << "Vuoi creare un altra scheda?\nSì = 1 	No = 0\n";
// cin >> fine;
// if(fine == 1)
// {
// 	return main();
// 	}
// if(fine == 0)
// {
// 	return 0;
// }
<|endoftext|>


<commit_before>0ca30440-2748-11e6-b0fb-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>0cadecca-2748-11e6-8a57-e0f84713e7b8<|endoftext|>


<commit_before>7d43ef97-4b02-11e5-bdf2-28cfe9171a43<commit_msg>updated some files<commit_after>7d537557-4b02-11e5-b904-28cfe9171a43<|endoftext|>


<commit_before>//! \file
//! Entry point

#include <map>
#include <string>
#include <vector>
#include "MainState.h"
#include "Game.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
#include "Sprite.h"
#include "Animation.h"
#include "MenuItem.h"

static void update(MainState &state);
static void render(const MainState &state);
static void change(MainState &state, MainState nextState);

Menu menu;
unsigned int index = 0;
Game* game;
Field f;
std::map<std::string, int> TextMap;
std::vector<std::string> Menu_EN;
unsigned char ip[4];
unsigned short port;
Sprite sprite;
int frame;

int text;

int main()
{
	Menu_EN.push_back("Host game");
	Menu_EN.push_back("Join game");
	Menu_EN.push_back("Quit");

	std::string font = "../prstartk.ttf";

	TextMap["."] = Renderer::CreateText(font, ".", 24);
	TextMap[":"] = Renderer::CreateText(font, ":", 24);
	TextMap["0"] = Renderer::CreateText(font, "0", 24);
	TextMap["1"] = Renderer::CreateText(font, "1", 24);
	TextMap["2"] = Renderer::CreateText(font, "2", 24);
	TextMap["3"] = Renderer::CreateText(font, "3", 24);
	TextMap["4"] = Renderer::CreateText(font, "4", 24);
	TextMap["5"] = Renderer::CreateText(font, "5", 24);
	TextMap["6"] = Renderer::CreateText(font, "6", 24);
	TextMap["7"] = Renderer::CreateText(font, "7", 24);
	TextMap["8"] = Renderer::CreateText(font, "8", 24);
	TextMap["9"] = Renderer::CreateText(font, "9", 24);

	TextMap[">"] = Renderer::CreateText(font, ">", 24);
	for (unsigned int i = 0; i < Menu_EN.size(); i++)
	{
		std::string string = Menu_EN[i];
		TextMap[string] = Renderer::CreateText(font, string, 24);
	}
	MenuItem item1, item2, item3;
	item1.Text = 0;
	item1.Function = Host;
	menu.push_back(item1);
	item2.Text = 1;
	item2.Function = Join;
	menu.push_back(item2);
	item3.Text = 2;
	item3.Function = Exiting;
	menu.push_back(item3);

	Renderer::Scale = 8.0f;
	Renderer::CreateWindow(1280, 720, "My window");

	sprite.Index = Renderer::CreateSprite("../pacman.png");

	text = Renderer::CreateText(font, "TESTING", 24);

	Animation pac_move(4);
	pac_move.AddFrame(34, 170, 32, 32);
	pac_move.AddFrame(1, 170, 32, 32);
	pac_move.AddFrame(34, 170, 32, 32);
	pac_move.AddFrame(67, 170, 32, 32);
	sprite.Animations.push_back(pac_move);
	frame = 0;

	for (int i = 0; i < FIELD_WIDTH; i++)
	{
		for (int j = 0; j < FIELD_HEIGHT; j++)
		{
			if (i == 0 || i == FIELD_WIDTH - 1 || j == 0 || j == FIELD_HEIGHT - 1)
			{
				f.Tiles[i][j] = Field::Wall;
			}
			else
			{
				f.Tiles[i][j] = Field::Empty;
			}
		}
	}

	MainState state = MainMenu;

	NetworkManager::Init();

    while (Renderer::WindowOpen())
    {
		InputHandler::PollEvents();
		if (InputHandler::WindowClosed)
		{
			break;
		}

		update(state);
		render(state);
		if (state == Exiting)
		{
			break;
		}
    }

	Renderer::Deinit();
    return 0;
}

static void update(MainState &state)
{
	switch (state)
	{
		case MainMenu:
			{
				if (InputHandler::InputTime == 0)
				{
					switch (InputHandler::LastInput)
					{
						case Player::Up:
							{
								if (index > 0)
								{
									index--;
								}
							}
							break;
						case Player::Down:
							{
								if (index < menu.size() - 1)
								{
									index++;
								}
							}
							break;
						case Player::Right:
							{
								MainState newState = menu[index].Function;
								if (newState == Host)
								{
									change(state, Host);
								}
								else if (newState == Join)
								{
									change(state, Join);
								}
								else if (newState == Exiting)
								{
									change(state, Exiting);
								}
							}
							break;
					}
				}
			}
			break;
		case Host:
			{
				// handle incoming network traffic
				NetworkManager::MessageType mtype;
				std::vector<char> data;
				unsigned int id;
				NetworkManager::Receive(mtype, data, id);
				if (mtype != NetworkManager::None)
				{
					switch (mtype)
					{
						case NetworkManager::RequestServer:
							{
								// TODO: add identity to lobby
								std::vector<char> d(0);
								NetworkManager::Send(NetworkManager::ConfirmClient, d, id);
								change(state, Gameplay);
							}
							break;
						case NetworkManager::PingServer:
							// TODO: confirm identity, reset timeout
							break;
						case NetworkManager::DisconnectServer:
							// TODO: remove identity from lobby
							break;
					}
				}
				if (InputHandler::InputTime == 0 && InputHandler::LastInput == Player::Right)
				{
					change(state, Gameplay);
				}
				else
				{
					// TODO: ping all clients
				}
			}
			break;
		case Join:
			{
				if (InputHandler::InputTime == 0)
				{
					switch (InputHandler::LastInput)
					{
						case Player::Left:
							{
								if (index > 0)
								{
									index--;
								}
							}
							break;
						case Player::Right:
							{
								if (index < 16)
								{
									index++;
								}
								else
								{
									char addr[16];
									sprintf(addr, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
									std::string address = addr;
									unsigned int server = NetworkManager::GetConnection(addr, port);
									std::vector<char> data(0);
									NetworkManager::Send(NetworkManager::RequestServer, data, server);
								}
							}
							break;
						case Player::Up:
							{
								if (index <= 11)
								{
									unsigned char &byte = ip[index / 3];
									unsigned char byte_max = 255;
									if (index % 3 == 0 && byte < byte_max - 100)
									{
										byte += 100;
									}
									else if (index % 3 == 1 && byte < byte_max - 10)
									{
										byte += 10;
									}
									else if (index % 3 == 2 && byte < byte_max - 1)
									{
										byte += 1;
									}
									else
									{
										byte = byte_max;
									}
								}
								else
								{
									unsigned short port_max = 65535;
									if (index - 12 == 0 && port < port_max - 10000)
									{
										port += 10000;
									}
									else if (index - 12 == 1 && port < port_max - 1000)
									{
										port += 1000;
									}
									else if (index - 12 == 2 && port < port_max - 100)
									{
										port += 100;
									}
									else if (index - 12 == 3 && port < port_max - 10)
									{
										port += 10;
									}
									else if (index - 12 == 4 && port < port_max - 1)
									{
										port += 1;
									}
									else
									{
										port = port_max;
									}
								}
							}
							break;
						case Player::Down:
							{
								if (index <= 11)
								{
									unsigned char &byte = ip[index / 3];
									if (index % 3 == 0 && byte > 100)
									{
										byte -= 100;
									}
									else if (index % 3 == 1 && byte > 10)
									{
										byte -= 10;
									}
									else if (index % 3 == 2 && byte > 1)
									{
										byte -= 1;
									}
									else
									{
										byte = 0;
									}
								}
								else
								{
									if (index - 12 == 0 && port > 10000)
									{
										port -= 10000;
									}
									else if (index - 12 == 1 && port > 1000)
									{
										port -= 1000;
									}
									else if (index - 12 == 2 && port > 100)
									{
										port -= 100;
									}
									else if (index - 12 == 3 && port > 10)
									{
										port -= 10;
									}
									else if (index - 12 == 4 && port > 1)
									{
										port -= 1;
									}
									else
									{
										port = 0;
									}
								}
							}
							break;
					}
				}
				// TODO: check connection status
				bool connection_waiting = false;
				char addr[16];
				sprintf(addr, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
				std::string address = addr;
				// parse server messages
				NetworkManager::MessageType mtype;
				std::vector<char> data;
				unsigned int sender;
				NetworkManager::Receive(mtype, data, sender);
				if (mtype != NetworkManager::None)
				{
					switch (mtype)
					{
						case NetworkManager::ConfirmClient:
							// TODO: display confirmation
							change(state, Gameplay);
							break;
						case NetworkManager::PingClient:
							// TODO: reset timeout
							break;
						case NetworkManager::DisconnectClient:
							// TODO: exit lobby
							break;
					}
				}
				if (connection_waiting)
				{
					bool timeout = false;
					if (timeout)
					{
						// TODO cancel connection
					}
					else
					{
						// send connection request
						std::vector<char> data(0);
						NetworkManager::Send(NetworkManager::RequestServer, data, 0);
					}
				}
				else
				{
					// TODO: prompt for IP address and port
					NetworkManager::ResetConnections();
					NetworkManager::GetConnection(address, port);
				}
				// TODO: ping server
			}
			break;
		case Gameplay:
			{
				game->Players[0].NextDir = InputHandler::LastInput;
				game->update();
			}
			break;
		case Exiting:
			// Don't do anything
			break;
	}
}

static void render(const MainState &state)
{
	Renderer::Clear();

	switch (state)
	{
		case MainMenu:
			{
				for (unsigned int i = 0; i < menu.size(); i++)
				{
					Renderer::DrawText(
							TextMap[Menu_EN[menu[i].Text]], 6, 10 + 6 * i);
					if (i == index)
					{
						Renderer::DrawText(
								TextMap[">"], 2, 10 + 6 * i);
					}
				}
			}
			break;
		case Host:
			{
				std::string address = NetworkManager::GetAddress();
				unsigned short port = NetworkManager::GetPort();
				char disp[22];
				sprintf(disp, "%s:%d", address.c_str(), port);
				for (unsigned int i = 0; disp[i] != '\0'; i++)
				{
					std::string s({ disp[i] });
					Renderer::DrawText(TextMap[s], 10 + 6 * i, 15);
				}
			}
			break;
		case Join:
			{
				char disp[22];
				sprintf(disp, "%03d.%03d.%03d.%03d:%05d", ip[0], ip[1], ip[2], ip[3], port);
				for (unsigned int i = 0; i < 21; i++)
				{
					std::string s({ disp[i] });
					Renderer::DrawText(TextMap[s], 10 + 6 * i, 15);
				}
			}
			break;
		case Gameplay:
			{
				Renderer::DrawSprite(
						sprite,
						game->Players[0].XPos, game->Players[0].YPos,
						game->Players[0].CurrentDir * -90.f,
						0, frame++);
				Renderer::DrawText(text, 10, 2);
			}
			break;
		case Exiting:
			// Don't do anything
			break;
	}
	Renderer::Display();
}

static void change(MainState &state, MainState nextState)
{
	state = nextState;
	switch (nextState)
	{
		case MainMenu:
			{
				index = 0;
			}
			break;
		case Host:
			{
				// TODO
			}
			break;
		case Join:
			{
				index = 0;
				ip[0] = 127;
				ip[1] = 0;
				ip[2] = 0;
				ip[3] = 1;
				port = 1;
			}
			break;
		case Gameplay:
			{
				std::vector<Player> p(1, Player(Player::Pacman));
				game = new Game(f, p);
				// TODO: delete game;
			}
			break;
		case Exiting:
			break;
	}
}
<commit_msg>Logic cleanup<commit_after>//! \file
//! Entry point

#include <map>
#include <string>
#include <vector>
#include "MainState.h"
#include "Game.h"
#include "Renderer.h"
#include "InputHandler.h"
#include "NetworkManager.h"
#include "Sprite.h"
#include "Animation.h"
#include "MenuItem.h"

static void update(MainState &state);
static void render(const MainState &state);
static void change(MainState &state, MainState nextState);
static void addrIncrement(unsigned int digit, int amount);

Menu menu;
unsigned int index = 0;
Game* game;
Field f;
std::map<std::string, int> TextMap;
std::vector<std::string> Menu_EN;
unsigned char ip[4];
unsigned short port;
Sprite sprite;
int frame;

int text;

int main()
{
	Menu_EN.push_back("Host game");
	Menu_EN.push_back("Join game");
	Menu_EN.push_back("Quit");

	std::string font = "../prstartk.ttf";

	TextMap["."] = Renderer::CreateText(font, ".", 24);
	TextMap[":"] = Renderer::CreateText(font, ":", 24);
	TextMap["0"] = Renderer::CreateText(font, "0", 24);
	TextMap["1"] = Renderer::CreateText(font, "1", 24);
	TextMap["2"] = Renderer::CreateText(font, "2", 24);
	TextMap["3"] = Renderer::CreateText(font, "3", 24);
	TextMap["4"] = Renderer::CreateText(font, "4", 24);
	TextMap["5"] = Renderer::CreateText(font, "5", 24);
	TextMap["6"] = Renderer::CreateText(font, "6", 24);
	TextMap["7"] = Renderer::CreateText(font, "7", 24);
	TextMap["8"] = Renderer::CreateText(font, "8", 24);
	TextMap["9"] = Renderer::CreateText(font, "9", 24);

	TextMap[">"] = Renderer::CreateText(font, ">", 24);
	for (unsigned int i = 0; i < Menu_EN.size(); i++)
	{
		std::string string = Menu_EN[i];
		TextMap[string] = Renderer::CreateText(font, string, 24);
	}
	MenuItem item1, item2, item3;
	item1.Text = 0;
	item1.Function = Host;
	menu.push_back(item1);
	item2.Text = 1;
	item2.Function = Join;
	menu.push_back(item2);
	item3.Text = 2;
	item3.Function = Exiting;
	menu.push_back(item3);

	Renderer::Scale = 8.0f;
	Renderer::CreateWindow(1280, 720, "My window");

	sprite.Index = Renderer::CreateSprite("../pacman.png");

	text = Renderer::CreateText(font, "TESTING", 24);

	Animation pac_move(4);
	pac_move.AddFrame(34, 170, 32, 32);
	pac_move.AddFrame(1, 170, 32, 32);
	pac_move.AddFrame(34, 170, 32, 32);
	pac_move.AddFrame(67, 170, 32, 32);
	sprite.Animations.push_back(pac_move);
	frame = 0;

	for (int i = 0; i < FIELD_WIDTH; i++)
	{
		for (int j = 0; j < FIELD_HEIGHT; j++)
		{
			if (i == 0 || i == FIELD_WIDTH - 1 || j == 0 || j == FIELD_HEIGHT - 1)
			{
				f.Tiles[i][j] = Field::Wall;
			}
			else
			{
				f.Tiles[i][j] = Field::Empty;
			}
		}
	}

	MainState state = MainMenu;

	NetworkManager::Init();

    while (Renderer::WindowOpen())
    {
		InputHandler::PollEvents();
		if (InputHandler::WindowClosed)
		{
			break;
		}

		update(state);
		render(state);
		if (state == Exiting)
		{
			break;
		}
    }

	Renderer::Deinit();
    return 0;
}

static void update(MainState &state)
{
	switch (state)
	{
		case MainMenu:
			{
				if (InputHandler::InputTime == 0)
				{
					switch (InputHandler::LastInput)
					{
						case Player::Up:
							{
								if (index > 0)
								{
									index--;
								}
							}
							break;
						case Player::Down:
							{
								if (index < menu.size() - 1)
								{
									index++;
								}
							}
							break;
						case Player::Right:
							{
								MainState newState = menu[index].Function;
								if (newState == Host)
								{
									change(state, Host);
								}
								else if (newState == Join)
								{
									change(state, Join);
								}
								else if (newState == Exiting)
								{
									change(state, Exiting);
								}
							}
							break;
					}
				}
			}
			break;
		case Host:
			{
				// handle incoming network traffic
				NetworkManager::MessageType mtype;
				std::vector<char> data;
				unsigned int id;
				NetworkManager::Receive(mtype, data, id);
				switch (mtype)
				{
					case NetworkManager::None:
						break;
					case NetworkManager::RequestServer:
						{
							// TODO: add identity to lobby
							std::vector<char> d(0);
							NetworkManager::Send(NetworkManager::ConfirmClient, d, id);
							change(state, Gameplay);
						}
						break;
					case NetworkManager::PingServer:
						// TODO: confirm identity, reset timeout
						break;
					case NetworkManager::DisconnectServer:
						// TODO: remove identity from lobby
						break;
				}
				if (InputHandler::InputTime == 0 && InputHandler::LastInput == Player::Right)
				{
					change(state, Gameplay);
				}
				else
				{
					// TODO: ping all clients
				}
			}
			break;
		case Join:
			{
				if (InputHandler::InputTime == 0)
				{
					switch (InputHandler::LastInput)
					{
						case Player::Left:
							{
								if (index > 0)
								{
									index--;
								}
							}
							break;
						case Player::Right:
							{
								if (index < 16)
								{
									index++;
								}
								else
								{
									char addr[16];
									sprintf(addr, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
									std::string address = addr;
									NetworkManager::ResetConnections();
									unsigned int server = NetworkManager::GetConnection(addr, port);
									// TODO: set connection to waiting
									std::vector<char> data(0);
									NetworkManager::Send(NetworkManager::RequestServer, data, server);
								}
							}
							break;
						case Player::Up:
							{
								addrIncrement(index, 1);
							}
							break;
						case Player::Down:
							{
								addrIncrement(index, -1);
							}
							break;
					}
				}
				// TODO: check connection status
				bool connection_waiting = false;
				// parse server messages
				NetworkManager::MessageType mtype;
				std::vector<char> data;
				unsigned int sender;
				NetworkManager::Receive(mtype, data, sender);
				if (sender == 0)
				{
					switch (mtype)
					{
						case NetworkManager::None:
							// ignore
							break;
						case NetworkManager::ConfirmClient:
							// TODO: display confirmation
							change(state, Gameplay);
							break;
						case NetworkManager::PingClient:
							// TODO: reset timeout
							break;
						case NetworkManager::DisconnectClient:
							// TODO: exit lobby
							break;
					}
				}
				if (connection_waiting)
				{
					bool timeout = false;
					if (timeout)
					{
						// TODO cancel connection
					}
					else
					{
						// send connection request
						std::vector<char> data(0);
						NetworkManager::Send(NetworkManager::RequestServer, data, 0);
					}
				}
				// TODO: ping server
			}
			break;
		case Gameplay:
			{
				game->Players[0].NextDir = InputHandler::LastInput;
				game->update();
			}
			break;
		case Exiting:
			// Don't do anything
			break;
	}
}

static void render(const MainState &state)
{
	Renderer::Clear();

	switch (state)
	{
		case MainMenu:
			{
				for (unsigned int i = 0; i < menu.size(); i++)
				{
					Renderer::DrawText(
							TextMap[Menu_EN[menu[i].Text]], 6, 10 + 6 * i);
					if (i == index)
					{
						Renderer::DrawText(
								TextMap[">"], 2, 10 + 6 * i);
					}
				}
			}
			break;
		case Host:
			{
				std::string address = NetworkManager::GetAddress();
				unsigned short port = NetworkManager::GetPort();
				char disp[22];
				sprintf(disp, "%s:%d", address.c_str(), port);
				for (unsigned int i = 0; disp[i] != '\0'; i++)
				{
					std::string s({ disp[i] });
					Renderer::DrawText(TextMap[s], 10 + 6 * i, 15);
				}
			}
			break;
		case Join:
			{
				char disp[22];
				sprintf(disp, "%03d.%03d.%03d.%03d:%05d", ip[0], ip[1], ip[2], ip[3], port);
				for (unsigned int i = 0; i < 21; i++)
				{
					std::string s({ disp[i] });
					Renderer::DrawText(TextMap[s], 10 + 6 * i, 15);
				}
			}
			break;
		case Gameplay:
			{
				Renderer::DrawSprite(
						sprite,
						game->Players[0].XPos, game->Players[0].YPos,
						game->Players[0].CurrentDir * -90.f,
						0, frame++);
				Renderer::DrawText(text, 10, 2);
			}
			break;
		case Exiting:
			// Don't do anything
			break;
	}
	Renderer::Display();
}

static void change(MainState &state, MainState nextState)
{
	state = nextState;
	switch (nextState)
	{
		case MainMenu:
			{
				index = 0;
			}
			break;
		case Host:
			{
				// TODO
			}
			break;
		case Join:
			{
				index = 0;
				ip[0] = 127;
				ip[1] = 0;
				ip[2] = 0;
				ip[3] = 1;
				port = 1;
			}
			break;
		case Gameplay:
			{
				std::vector<Player> p(1, Player(Player::Pacman));
				game = new Game(f, p);
				// TODO: delete game;
			}
			break;
		case Exiting:
			break;
	}
}

static void addrIncrement(unsigned int digit, int amount)
{
	int delta = amount;
	if (digit < 12)
	{
		for (unsigned int i = digit % 3; i < 2; i++)
		{
			delta *= 10;
		}
		unsigned char &selected = ip[digit / 3];
		if (selected + delta == (int)(unsigned char)(selected + delta))
		{
			selected += delta;
		}
		else
		{
			selected = (amount > 0) ? 255 : 0;
		}
	}
	else
	{
		for (unsigned int i = digit - 12; i < 4; i++)
		{
			delta *= 10;
		}
		if (port + delta == (int)(unsigned short)(port + delta))
		{
			port += delta;
		}
		else
		{
			port = (amount > 0) ? 65535 : 0;
		}
	}
}
<|endoftext|>


<commit_before>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>

// POSIX++
#include <climits> // PATH_MAX
#include <cstdint>
#include <cassert>
#include <cstring>
#include <ctime>

// STL
#include <map>
#include <set>
#include <string>
#include <system_error>

#include <put/specialized/osdetect.h>
#include <put/specialized/procstat.h>
#include <put/cxxutils/posix_helpers.h>

namespace scfs
{
  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const noexcept // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  static std::map<uid_t, std::set<file_entry_t>> files;
  static struct timespec inittime;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept
  {
    const char* dir_pos = std::strchr(path, '/') + 1;
    const char* file_pos = std::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == NULL)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = posix::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set) noexcept
  {
    process_state_t data;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(::procstat(pos->pid, data))
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }
/*
  struct timespec get_oldest(std::set<file_entry_t>& dir_set)
  {
    struct timespec oldest = dir_set.begin()->stat.st_atim;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(pos->stat.st_atim.tv_sec < oldest.tv_sec)
        oldest.tv_sec = pos->stat.st_atim.tv_sec;
    }
    return oldest;
  }
*/
  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept
  {
    (void)fileInfo;
    filler(buf, "." , NULL, 0);
    filler(buf, "..", NULL, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            struct passwd* p = posix::getpwuid(pos->first);
            if(p != NULL)
              filler(buf, p->pw_name, NULL, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
          return posix::errorval(std::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success_response;
  }

  int mknod(const char* path, mode_t mode, dev_t rdev) noexcept
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return posix::errorval(std::errc::permission_denied);

    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    if(fuse_get_context()->uid && // if NOT root AND
       pw_ent->pw_uid != fuse_get_context()->uid) // UID doesn't match
      return posix::errorval(std::errc::invalid_argument);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return posix::errorval(std::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
#if defined(__darwin__) || defined(BSD)
        stat.st_ctimespec =
        stat.st_mtimespec =
        stat.st_atimespec = time;
#elif defined(__linux__)
        stat.st_ctim =
        stat.st_mtim =
        stat.st_atim = time;
#else
# error unknown OS
#endif
        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success_response;
  }

  int getattr(const char* path, struct stat* statbuf) noexcept
  {
    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);
    statbuf->st_size = 0;

    switch(type)
    {
      case Epath::root:      // root directory (always exists)
#if defined(__darwin__) || defined(BSD)
        statbuf->st_ctimespec =
        statbuf->st_mtimespec =
        statbuf->st_atimespec = inittime;
#elif defined(__linux__)
        statbuf->st_ctim =
        statbuf->st_mtim =
        statbuf->st_atim = inittime;
#else
# error unknown OS
#endif
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        if(pw_ent == nullptr)
          return posix::errorval(std::errc::no_such_file_or_directory);
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
          return posix::errorval(std::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            return posix::success_response;
          }
        }

        return posix::errorval(std::errc::no_such_file_or_directory); // no file matched
    }
    return posix::success_response;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  clock_gettime(CLOCK_REALTIME, &scfs::inittime);

  ops.readdir = scfs::readdir;
  ops.mknod   = scfs::mknod;
  ops.getattr = scfs::getattr;

  return fuse_main(argc, argv, &ops, NULL);
}
<commit_msg>fix filesystem<commit_after>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>

// POSIX++
#include <climits> // PATH_MAX
#include <cstdint>
#include <cassert>
#include <cstring>
#include <ctime>

// STL
#include <map>
#include <set>
#include <string>
#include <system_error>

#include <put/specialized/osdetect.h>
#include <put/specialized/procstat.h>
#include <put/cxxutils/posix_helpers.h>

#if !defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600 || \
  defined(__darwin__) || defined(BSD)
# define st_ctim st_ctimespec
# define st_mtim st_mtimespec
# define st_atim st_atimespec
#endif

namespace scfs
{
  inline int return_error(posix::errc val) noexcept
    { return 0 - int(val); }

  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const noexcept // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  static std::map<uid_t, std::set<file_entry_t>> files;
  static struct timespec inittime;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename) noexcept
  {
    const char* dir_pos = posix::strchr(path, '/') + 1;
    const char* file_pos = posix::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == NULL)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = posix::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set) noexcept
  {
    process_state_t data;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(!::procstat(pos->pid, data))
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }

  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo) noexcept
  {
    (void)fileInfo;
    filler(buf, "." , NULL, 0);
    filler(buf, "..", NULL, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            struct passwd* p = posix::getpwuid(pos->first);
            if(p != NULL)
              filler(buf, p->pw_name, NULL, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success_response;
  }

  int mknod(const char* path, mode_t mode, dev_t rdev) noexcept
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return return_error(posix::errc::permission_denied);

    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    if(fuse_get_context()->uid && // if NOT root AND
       pw_ent->pw_uid != fuse_get_context()->uid) // UID doesn't match
      return return_error(posix::errc::invalid_argument);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return return_error(posix::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
        stat.st_ctim =
        stat.st_mtim =
        stat.st_atim = time;

        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success_response;
  }

  int getattr(const char* path, struct stat* statbuf) noexcept
  {
    Epath type;
    passwd* pw_ent = NULL;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);
    statbuf->st_size = 0;

    switch(type)
    {
      case Epath::root:      // root directory (always exists)

        statbuf->st_ctim =
        statbuf->st_mtim =
        statbuf->st_atim = inittime;
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | // set as directory
                           S_IRUSR | S_IRGRP | S_IROTH | // set readable to everyone
                           S_IXUSR | S_IXGRP | S_IXOTH; // set executable to everyone
        if(pw_ent == nullptr)
          return return_error(posix::errc::no_such_file_or_directory);
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
          return return_error(posix::errc::no_such_file_or_directory);

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            return posix::success_response;
          }
        }

        return return_error(posix::errc::no_such_file_or_directory); // no file matched
    }
    return posix::success_response;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  clock_gettime(CLOCK_REALTIME, &scfs::inittime);

  ops.readdir = scfs::readdir;
  ops.mknod   = scfs::mknod;
  ops.getattr = scfs::getattr;

  return fuse_main(argc, argv, &ops, NULL);
}
<|endoftext|>


<commit_before>
int main() {
    return 0;
}
<commit_msg>Add window<commit_after>#include <SFML/Graphics.hpp>

#include "level.hpp"

int main() {
    // Create the main window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

    // Start the game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close window: exit
            if (event.type == sf::Event::Closed)
                window.close();
        }
        // Clear screen
        window.clear();

        // Update the window
        window.display();
    }
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>d702bd33-4b02-11e5-ac00-28cfe9171a43<commit_msg>I hope I am done<commit_after>d71133fa-4b02-11e5-8244-28cfe9171a43<|endoftext|>


<commit_before>e2fbfdcf-4b02-11e5-90bb-28cfe9171a43<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>7d2871f3-ad58-11e7-b677-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>7db015f0-ad58-11e7-a496-ac87a332f658<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <fstream>
#include <iostream>
#include <string>

#include <boost/format.hpp>

#include "SQLiteCpp/src/SQLiteC++.h"

#include <pkmnsim/enums.hpp>
#include <pkmnsim/game_save.hpp>
#include <pkmnsim/paths.hpp>

#include <pokehack/SaveParser.h>
#include <pokelib/pokelib.h>
#include <pkmds/pkmds_g5.h>

using namespace std;

namespace pkmnsim
{
    game_save::sptr game_save::make(string filename)
    {
        //Detect type of game save
        bool can_be_gen3, can_be_gen4, can_be_gen5;

        //Read save file and get size
        FILE* save_file;
        save_file = fopen(filename.c_str(), "rb");
        fseek(save_file, 0, SEEK_END);
        int size = ftell(save_file);
        rewind(save_file);
        char* buffer = (char*)malloc(size);
        int result = fread(buffer, 1, size, save_file);
        fclose(save_file);

        //Use size to determine possibilities
        if(size >= 0x80000)
        {
            can_be_gen3 = false;
            can_be_gen4 = true;
            can_be_gen5 = true;
        }
        else if(size >= 0x40000)
        {
            can_be_gen3 = false;
            can_be_gen4 = true;
            can_be_gen5 = false;
        }
        else if(size >= 0x20000)
        {
            can_be_gen3 = true;
            can_be_gen4 = false;
            can_be_gen5 = false;
        }
        else
        {
            cerr << "This file is too small to be a proper save file." << endl;
            exit(EXIT_FAILURE);
        }

        //Once size is determined, determine whether or not save is valid
        if(can_be_gen4 and can_be_gen5)
        {
            //Check to see if PokeLib accepts it as a proper Gen 4 save
            PokeLib::Save save(filename.c_str());
            if(save.parseRawSave())
            {
                free(buffer);
                //return sptr(new game_save_gen4impl(save));
            }
            else
            {
                //Check to see if PokeLib accepts it as a proper Gen 4 save
                free(buffer);
                bw2sav_obj* sav = new bw2sav_obj;
                read(filename.c_str(), sav);
                if(savisbw2(sav))
                {
                    //return sptr(new game_save_gen5impl(sav));
                }
            }
        }
        else if(can_be_gen4)
        {
            PokeLib::Save save(filename.c_str());
            if(save.parseRawSave())
            {
                free(buffer);
                //return sptr(new game_save_gen4impl(save));
            }
        }
        else
        {
            //Check for Gen 3 game by searching for game code
            int game_type;
            if(buffer[int(0xAC)] != 1) game_type = 0;
            else game_type = 1;

            SaveParser* parser = SaveParser::Instance();
            if(parser->load(filename.c_str(), game_type))
            {
                free(buffer);
                //return sptr(new game_save_gen3impl(parser));
            }
        }

        //If code has gotten to this point, the file is not a valid save file
        cerr << "Invalid save file." << endl;
        exit(EXIT_FAILURE);
    }
}
<commit_msg>game_save: removed redundant code from factory function<commit_after>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <fstream>
#include <iostream>
#include <string>

#include <boost/format.hpp>

#include "SQLiteCpp/src/SQLiteC++.h"

#include <pkmnsim/enums.hpp>
#include <pkmnsim/game_save.hpp>
#include <pkmnsim/paths.hpp>

#include <pokehack/SaveParser.h>
#include <pokelib/pokelib.h>
#include <pkmds/pkmds_g5.h>

using namespace std;

namespace pkmnsim
{
    game_save::sptr game_save::make(string filename)
    {
        //Read save file and get size
        FILE* save_file;
        save_file = fopen(filename.c_str(), "rb");
        fseek(save_file, 0, SEEK_END);
        int size = ftell(save_file);
        rewind(save_file);
        char* buffer = (char*)malloc(size);
        int result = fread(buffer, 1, size, save_file);
        fclose(save_file);

        //Once size is determined, determine whether or not save is valid
        if(size > 0x80000)
        {
            //Check to see if PokeLib accepts it as a proper Gen 4 save
            PokeLib::Save save(filename.c_str());
            if(save.parseRawSave())
            {
                free(buffer);
                //return sptr(new game_save_gen4impl(save));
            }
            else
            {
                //Check to see if PokeLib accepts it as a proper Gen 4 save
                free(buffer);
                bw2sav_obj* sav = new bw2sav_obj;
                read(filename.c_str(), sav);
                if(savisbw2(sav))
                {
                    //return sptr(new game_save_gen5impl(sav));
                }
            }
        }
        else if(size > 0x40000)
        {
            PokeLib::Save save(filename.c_str());
            if(save.parseRawSave())
            {
                free(buffer);
                //return sptr(new game_save_gen4impl(save));
            }
        }
        else if(size >= 0x20000)
        {
            //Check for Gen 3 game by searching for game code
            int game_type;
            if(buffer[int(0xAC)] != 1) game_type = 0;
            else game_type = 1;

            SaveParser* parser = SaveParser::Instance();
            if(parser->load(filename.c_str(), game_type))
            {
                free(buffer);
                //return sptr(new game_save_gen3impl(parser));
            }
        }
        else
        {
            cerr << "This file is too small to be a proper save file." << endl;
            exit(EXIT_FAILURE);
        }
    }
}
<|endoftext|>


<commit_before>c47138f8-4b02-11e5-8a82-28cfe9171a43<commit_msg>Adding stuff<commit_after>c47c8db8-4b02-11e5-9596-28cfe9171a43<|endoftext|>


<commit_before>#ifndef __INTERFACE_MAINWINDOW_H__
#define __INTERFACE_MAINWINDOW_H__
#include <QWidget>
#include <QListWidget>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTextEdit>
#include <QSplitter>
#include <QList>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QIcon>

#include <Control/ControlData.hh>

class MainWindow : public QMainWindow {
public:
  MainWindow(QMainWindow *parent, ControlData *ctrlData);

private:
  ControlData *localControl;

  QWidget *centralWidget;

  QHBoxLayout *mainLayout;
  QVBoxLayout *listLayout;

  QListWidget *pageList;

  QGraphicsScene *canvas;
  QGraphicsView *canvasDisplay;

  QSplitter *mainSplitters;

  QTextEdit *editor;

  QAction *newProject;
  QAction *openProject;
  QAction *addImages;
  QAction *saveProject;
  QAction *saveAsProject;
  QAction *exit;
  QAction *zoomIn;
  QAction *zoomOut;
  QAction *zoomNormal;
  QAction *orcNow;
  QAction *prefSettings;
  QAction *about;
  QAction *documentation;

  QMenu *file;
  QMenu *tools;
  QMenu *help;

  QToolBar *mainToolbar;

  void allocateResources();
  void configurePageList();
  void configureCanvas();
  void configureEditor();
  void configureSplitters();
  void configureLayout();
  void configureAction();
  void configureConnections();
  void configureMenu();
  void configureToolbar();

  void handleOpenProject();
  void handleAddProject();

  void showLoadDialog();

  void testMessagePrint();

  //Foreign Dependenices
  std::function<void()> pageUpdateWrapper;

  void syncNavbar();
  void setSignalWrappers();

  QList<Page> *getPageLink();
  QString getThumbnailPage(int index);
  QString getFullPage(int index);
  int getTotalPages();
};

#endif
<commit_msg>testing branching<commit_after>#ifndef __INTERFACE_MAINWINDOW_H__
#define __INTERFACE_MAINWINDOW_H__
#include <QWidget>
#include <QListWidget>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QTextEdit>
#include <QSplitter>
#include <QList>
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QIcon>

#include <Control/ControlData.hh>

class MainWindow : public QMainWindow {
public:
  MainWindow(QMainWindow *parent, ControlData *ctrlData);

private:
  ControlData *localControl;

  QWidget *centralWidget;

  QHBoxLayout *mainLayout;
  QVBoxLayout *listLayout;

  QListWidget *pageList;

  QGraphicsScene *canvas;
  QGraphicsView *canvasDisplay;

  QSplitter *mainSplitters;

  QTextEdit *editor;

  QAction *newProject;
  QAction *openProject;
  QAction *addImages;
  QAction *saveProject;
  QAction *saveAsProject;
  QAction *exit;
  QAction *zoomIn;
  QAction *zoomOut;
  QAction *zoomNormal;
  QAction *orcNow;
  QAction *prefSettings;
  QAction *about;
  QAction *documentation;

  QMenu *file;
  QMenu *tools;
  QMenu *help;

  QToolBar *mainToolbar;

  void allocateResources();
  void configurePageList();
  void configureCanvas();
  void configureEditor();
  void configureSplitters();
  void configureLayout();
  void configureAction();
  void configureConnections();
  void configureMenu();
  void configureToolbar();

  void handleOpenProject();
  void handleAddProject();

  void showLoadDialog();

  void testMessagePrint();

  //Foreign Dependenices
  std::function<void()> pageUpdateWrapper;

  void syncNavbar();
  void setSignalWrappers();

  QList<Page> *getPageLink();
  QString getThumbnailPage(int index);
  QString getFullPage(int index);
  int getTotalPages();
};

#endif
<|endoftext|>


<commit_before>/*********************************************
* Jampack - general purpose compression algorithm by Lucas Marsh (c) 2017
*
* Compression memory usage is 8MB + 6 x block size x number of threads.
* Decompression memory usage is 6 x block size.
* Regardless of the number of threads decoding memory is always constant in size.
**********************************************/
#include "jampack.hpp"

int main(int argc, char** argv)
{
	if (argc < 4)
	{
	#ifdef __CUDACC__
		printf("Jampack v%.2f by Lucas Marsh (c) 2017\n \n\
Usage: Jampack.exe <c|d> input output <options>\n \n\
Options:\n\
   -t# : Threads\n\
   -b# : Block size in MB\n\
   -g : Enable GPU decoding\n   \n\
Press 'enter' to continue", JAM_VERSION);
	#else
		printf("Jampack v%.2f by Lucas Marsh (c) 2017\n \n\
Usage: Jampack.exe <c|d> input output <options>\n \n\
Options:\n\
   -t# : Threads\n\
   -b# : Block size in MB\n   \n\
Press 'enter' to continue", JAM_VERSION);
	#endif
		getchar();
		return 0;
	}

	if(strcmp(argv[2], argv[3]) == 0)
		Error("Refusing to write to input.");

	FILE* input = fopen(argv[2], "rb");
	if (input == NULL) return perror(argv[2]), 1;
	FILE* output = fopen(argv[3], "wb");
	if (output == NULL) return perror(argv[3]), 1;

	int threads = MAX_THREADS;
	int blocksize = DEFAULT_BLOCKSIZE;
	bool gpu = false;
	int cur_opt = 4;
	if (argc > 4)
	{
		while(cur_opt != argc)
		{
			const char* p=argv[cur_opt++];
			if(*p == '-')
			{
				p++;
				while (*p)
				{
					switch (*p)
					{
						case 'b': blocksize = atoi(p+1) << 20; break;
						case 't': threads = atoi(p+1); break;
						case 'g': gpu = true; break;
					}
					p++;
				}
			}
		}
	}

	Jampack* Jam = new Jampack();

	time_t start;
	start = clock();
	switch (argv[1][0])
	{
		case 'c': Jam->Compress (input, output, threads, blocksize); break;
		case 'd': Jam->Decompress (input, output, threads, gpu); break;
		default: printf("Invalid option!\n"); exit(0);
	}
	printf("Completed in %.2f seconds\n",  ((double)clock() - (double)start) / CLOCKS_PER_SEC);

	delete Jam;

	fclose(input);
	fclose(output);
	return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>bb0eb0f5-4b02-11e5-a19f-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>bb19d466-4b02-11e5-893d-28cfe9171a43<|endoftext|>


<commit_before>/*
 * Main
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

// KDE
#include <KCmdLineArgs>
#include <KApplication>
#include <KAboutData>
#include <KLocale>
#include <KUrl>
#include <KFileDialog>
#include <KDebug>

#include "mainwindow.h"
#include "version.h"

int main(int argc, char *argv[])
{
    KAboutData aboutData("ktp-send-file", 0,
                         ki18n("Telepathy Send File"),
                         KTP_SEND_FILE_VERSION);
    aboutData.addAuthor(ki18n("David Edmundson"), ki18n("Author"), "kde@davidedmundson.co.uk");

    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+file", ki18n("The file to send"));
    KCmdLineArgs::addCmdLineOptions(options);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    KApplication app;

    KUrl fileToSend;

    if (args->count() == 0) {
        fileToSend = KFileDialog::getOpenUrl(KUrl("kfiledialog://telepathySendFile"), QString(), 0, i18n("Select File To Send"));
    } else {
        fileToSend = args->arg(0);
    }

    if (! fileToSend.isEmpty()) {
        MainWindow *w = new MainWindow(fileToSend);
        w->show();
        return app.exec();
    } else {
        return -1;
    }

}

<commit_msg>Set bugzilla product name and icon<commit_after>/*
 * Main
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

// KDE
#include <KCmdLineArgs>
#include <KApplication>
#include <KAboutData>
#include <KLocale>
#include <KUrl>
#include <KFileDialog>
#include <KDebug>

#include "mainwindow.h"
#include "version.h"

int main(int argc, char *argv[])
{
    KAboutData aboutData("ktp-send-file", 0,
                         ki18n("Telepathy Send File"),
                         KTP_SEND_FILE_VERSION);
    aboutData.addAuthor(ki18n("David Edmundson"), ki18n("Author"), "kde@davidedmundson.co.uk");
    aboutData.setProductName("telepathy/send-file");
    aboutData.setProgramIconName(QLatin1String("telepathy-kde"));

    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+file", ki18n("The file to send"));
    KCmdLineArgs::addCmdLineOptions(options);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    KApplication app;

    KUrl fileToSend;

    if (args->count() == 0) {
        fileToSend = KFileDialog::getOpenUrl(KUrl("kfiledialog://telepathySendFile"), QString(), 0, i18n("Select File To Send"));
    } else {
        fileToSend = args->arg(0);
    }

    if (! fileToSend.isEmpty()) {
        MainWindow *w = new MainWindow(fileToSend);
        w->show();
        return app.exec();
    } else {
        return -1;
    }

}

<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <kconfig.h>
#include <kdebug.h>
#include <kio/job.h>
#include <kglobal.h>

#include "provider.h"
#include "provider.moc"

using namespace KNS;

Provider::Provider()
{
}

Provider::Provider( const QDomElement &e )
{
  parseDomElement( e );
}

Provider::~Provider()
{
}

void Provider::setName( const QString &name )
{
  mName = name;
}

QString Provider::name() const
{
  return mName;
}

void Provider::setDownloadUrl( const KURL &url )
{
  mDownloadUrl = url;
}

KURL Provider::downloadUrl() const
{
  return mDownloadUrl;
}

void Provider::setUploadUrl( const KURL &url )
{
  mUploadUrl = url;
}

KURL Provider::uploadUrl() const
{
  return mUploadUrl;
}

void Provider::parseDomElement( const QDomElement &element )
{
  if ( element.tagName() != "provider" ) return;

  setDownloadUrl( KURL( element.attribute("downloadurl") ) );
  setUploadUrl( KURL( element.attribute("uploadurl") ) );

  setName( element.text().stripWhiteSpace() );
}

QDomElement Provider::createDomElement( QDomDocument &doc, QDomElement &parent )
{
  QDomElement entry = doc.createElement( "stuff" );
  parent.appendChild( entry );

  QDomElement n = doc.createElement( "name" );
  n.appendChild( doc.createTextNode( name() ) );
  entry.appendChild( n );

  return entry;
}

ProviderLoader::ProviderLoader( QWidget *parentWidget ) :
  mParentWidget( parentWidget )
{
  mProviders.setAutoDelete( true );
}

void ProviderLoader::load( const QString &type )
{
  kdDebug() << "ProviderLoader::load()" << endl;

  mProviders.clear();
  mJobData = "";

  KConfig *cfg = KGlobal::config();
  cfg->setGroup("KNewStuff");

  QString server = cfg->readEntry( "MasterServer",
                                   "http://korganizer.kde.org" );

  QString providersUrl = server + "/knewstuff/" +
                         type + "/providers.xml";

  kdDebug() << "ProviderLoader::load(): providersUrl: " << providersUrl << endl;

  KIO::TransferJob *job = KIO::get( providersUrl );
  connect( job, SIGNAL( result( KIO::Job * ) ),
           SLOT( slotJobResult( KIO::Job * ) ) );
  connect( job, SIGNAL( data( KIO::Job *, const QByteArray & ) ),
           SLOT( slotJobData( KIO::Job *, const QByteArray & ) ) );

//  job->dumpObjectInfo();
}

void ProviderLoader::slotJobData( KIO::Job *, const QByteArray &data )
{
  kdDebug() << "ProviderLoader::slotJobData()" << endl;

  if ( data.size() == 0 ) return;

  QString s = data;
  mJobData.append( s );
}

void ProviderLoader::slotJobResult( KIO::Job *job )
{
  if ( job->error() ) {
    job->showErrorDialog( mParentWidget );
  }

  kdDebug() << "--PROVIDERS-START--" << endl << mJobData << "--PROV_END--"
            << endl;

  QDomDocument doc;
  if ( !doc.setContent( QString::fromUtf8( mJobData ) ) ) {
    kdDebug() << "Error parsing Providers.xml." << endl;
    return;
  }

  QDomElement providers = doc.documentElement();

  if ( providers.isNull() ) {
    kdDebug() << "No document in Providers.xml." << endl;
  }

  QDomNode n;
  for ( n = providers.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement p = n.toElement();

    mProviders.append( new Provider( p ) );
  }

  emit providersLoaded( &mProviders );
}
<commit_msg>Use providers.xml URL from config file, if there is an ProvidersUrl entry.<commit_after>/*
    This file is part of KOrganizer.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <kconfig.h>
#include <kdebug.h>
#include <kio/job.h>
#include <kglobal.h>

#include "provider.h"
#include "provider.moc"

using namespace KNS;

Provider::Provider()
{
}

Provider::Provider( const QDomElement &e )
{
  parseDomElement( e );
}

Provider::~Provider()
{
}

void Provider::setName( const QString &name )
{
  mName = name;
}

QString Provider::name() const
{
  return mName;
}

void Provider::setDownloadUrl( const KURL &url )
{
  mDownloadUrl = url;
}

KURL Provider::downloadUrl() const
{
  return mDownloadUrl;
}

void Provider::setUploadUrl( const KURL &url )
{
  mUploadUrl = url;
}

KURL Provider::uploadUrl() const
{
  return mUploadUrl;
}

void Provider::parseDomElement( const QDomElement &element )
{
  if ( element.tagName() != "provider" ) return;

  setDownloadUrl( KURL( element.attribute("downloadurl") ) );
  setUploadUrl( KURL( element.attribute("uploadurl") ) );

  setName( element.text().stripWhiteSpace() );
}

QDomElement Provider::createDomElement( QDomDocument &doc, QDomElement &parent )
{
  QDomElement entry = doc.createElement( "stuff" );
  parent.appendChild( entry );

  QDomElement n = doc.createElement( "name" );
  n.appendChild( doc.createTextNode( name() ) );
  entry.appendChild( n );

  return entry;
}

ProviderLoader::ProviderLoader( QWidget *parentWidget ) :
  mParentWidget( parentWidget )
{
  mProviders.setAutoDelete( true );
}

void ProviderLoader::load( const QString &type )
{
  kdDebug() << "ProviderLoader::load()" << endl;

  mProviders.clear();
  mJobData = "";

  KConfig *cfg = KGlobal::config();
  cfg->setGroup("KNewStuff");

  QString providersUrl = cfg->readEntry( "ProvidersUrl" );

  if ( providersUrl.isEmpty() ) {
    // TODO: Replace the default by the real one.
    QString server = cfg->readEntry( "MasterServer",
                                     "http://korganizer.kde.org" );

    providersUrl = server + "/knewstuff/" + type + "/providers.xml";
  }

  kdDebug() << "ProviderLoader::load(): providersUrl: " << providersUrl << endl;

  KIO::TransferJob *job = KIO::get( providersUrl );
  connect( job, SIGNAL( result( KIO::Job * ) ),
           SLOT( slotJobResult( KIO::Job * ) ) );
  connect( job, SIGNAL( data( KIO::Job *, const QByteArray & ) ),
           SLOT( slotJobData( KIO::Job *, const QByteArray & ) ) );

//  job->dumpObjectInfo();
}

void ProviderLoader::slotJobData( KIO::Job *, const QByteArray &data )
{
  kdDebug() << "ProviderLoader::slotJobData()" << endl;

  if ( data.size() == 0 ) return;

  QString s = data;
  mJobData.append( s );
}

void ProviderLoader::slotJobResult( KIO::Job *job )
{
  if ( job->error() ) {
    job->showErrorDialog( mParentWidget );
  }

  kdDebug() << "--PROVIDERS-START--" << endl << mJobData << "--PROV_END--"
            << endl;

  QDomDocument doc;
  if ( !doc.setContent( QString::fromUtf8( mJobData ) ) ) {
    kdDebug() << "Error parsing Providers.xml." << endl;
    return;
  }

  QDomElement providers = doc.documentElement();

  if ( providers.isNull() ) {
    kdDebug() << "No document in Providers.xml." << endl;
  }

  QDomNode n;
  for ( n = providers.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement p = n.toElement();

    mProviders.append( new Provider( p ) );
  }

  emit providersLoaded( &mProviders );
}
<|endoftext|>