<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

using namespace std;

unsigned short const int nY=20, nX=70;

void glider(bool tablica[][nX]);
void los(bool tablica[][nX]);
int mod (int a, int b);
void przeliczGeneracjeNaKomorce(bool tablica[][nX], bool bTymczasowa[][nX]);
void kopiujTablice(bool tablica[][nX], bool bTymczasowa[][nX]);
void kolejnaGeneracja(bool tablica[][nX], bool bTymczasowa[][nX]);
void drukujTablice(bool tablica[][nX]);
bool czyKonczyc(int i);

int main()
{
    srand(time(NULL));
    bool tablica[nY][nX]={}, bTymczasowa[nY][nX]={};
    //los(tablica);
    glider(tablica);
    system("color a");
    for(int i=1; ; i++)
    {
        drukujTablice(tablica);
        kolejnaGeneracja(tablica, bTymczasowa);
        Sleep(50);
        if(czyKonczyc(i)==1)
        {
            return 0;
        }
    }
}

void glider(bool tablica[][nX])
{
    tablica[5][5] = 1;
    tablica[6][6] = 1;
    tablica[7][4] = 1;
    tablica[7][5] = 1;
    tablica[7][6] = 1;
}

void los(bool tablica[][nX])
{
    bool *wb;
    wb = &tablica[0][0];
    int nLosowa;

    for(int i=0; i<nX*nY; i++)
    {
        nLosowa=rand() %100 +1;
        if(nLosowa<26)
        {
            *(wb++)=1;
        }
        else
        {
            *(wb++)=0;
        }
    }
}

int mod (int a, int b)
{
   int ret = a % b;
   if(ret < 0)
     ret+=b;
   return ret;
}

void przeliczGeneracjeNaKomorce(bool tablica[][nX], bool bTymczasowa[][nX])
{
    for(int y=0; y<nY; y++)
    {
        for(int x=0; x<nX; x++)
        {
            int nLive=0;

            if((y!=0)||(y!=nY-1)||(x!=0)||(x!=nX-1))
            {
                nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                    +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                    +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
            }
            else if(y==0)
            {
                if(x==0)
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
                else if(x==nX-1)
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
                else
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
            }
            else if(y==nY-1)
            {
                if(x==0)
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
                else if(x==nX-1)
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
                else
                {
                    nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                        +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                        +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
                }
            }
            else if(x==0)
            {
                nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                    +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                    +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
            }
            else if(x==nX-1)
            {
                nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                    +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                    +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];
            }

            if(tablica[y][x]==0)
            {
                if(nLive==3)
                {
                    bTymczasowa[y][x]=1;
                }
                else
                {
                    bTymczasowa[y][x]=0;
                }
            }
            else if(tablica[y][x]==1)
            {
                if((nLive<2)||(nLive>3))
                {
                    bTymczasowa[y][x]=0;
                }
                else
                {
                    bTymczasowa[y][x]=1;
                }
            }
        }
    }
}

void kopiujTablice(bool tablica[][nX], bool bTymczasowa[][nX])
{
    for(int y=0; y<nY; y++)
    {
        for(int x=0; x<nX; x++)
        {
            tablica[y][x]=bTymczasowa[y][x];
        }
    }
}

void kolejnaGeneracja(bool tablica[][nX], bool bTymczasowa[][nX])
{
    przeliczGeneracjeNaKomorce(tablica, bTymczasowa);
    kopiujTablice(tablica, bTymczasowa);
}

void drukujTablice(bool tablica[][nX])
{
    system("cls");
    cout<<"------------------------------------------------------------------------"<<endl;
    for(int y=0; y<nY; y++)
    {
        cout<<"|";
        for(int x=0; x<nX; x++)
        {
            if(tablica[y][x]==0)
            {
                cout<<' ';
            }
            else
            {
                cout<<'*';
            }
        }
        cout<<"|"<<endl;
    }
    cout<<"------------------------------------------------------------------------"<<endl;
}

bool czyKonczyc(int i)
{
    if(i%100==0)
    {
        cout<<endl<<endl<<"  1. Continue"<<endl<<"  2. Exit"<<endl<<"   Your choise: ";
        int wybor;
        cin>>wybor;
        switch(wybor)
        {
            case 1: return 0;
            case 2: return 1;
        }
    }
    else
    {
        return 0;
    }
}
<commit_msg>Suma ilości żywych komórek bez ifów<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

using namespace std;

unsigned short const int nY=20, nX=70;

void glider(bool tablica[][nX]);
void los(bool tablica[][nX]);
int mod (int a, int b);
void przeliczGeneracjeNaKomorce(bool tablica[][nX], bool bTymczasowa[][nX]);
void kopiujTablice(bool tablica[][nX], bool bTymczasowa[][nX]);
void kolejnaGeneracja(bool tablica[][nX], bool bTymczasowa[][nX]);
void drukujTablice(bool tablica[][nX]);
bool czyKonczyc(int i);

int main()
{
    srand(time(NULL));
    bool tablica[nY][nX]={}, bTymczasowa[nY][nX]={};
    //los(tablica);
    glider(tablica);
    system("color a");
    for(int i=1; ; i++)
    {
        drukujTablice(tablica);
        kolejnaGeneracja(tablica, bTymczasowa);
        Sleep(50);
        if(czyKonczyc(i)==1)
        {
            return 0;
        }
    }
}

void glider(bool tablica[][nX])
{
    tablica[5][5] = 1;
    tablica[6][6] = 1;
    tablica[7][4] = 1;
    tablica[7][5] = 1;
    tablica[7][6] = 1;
}

void los(bool tablica[][nX])
{
    bool *wb;
    wb = &tablica[0][0];
    int nLosowa;

    for(int i=0; i<nX*nY; i++)
    {
        nLosowa=rand() %100 +1;
        if(nLosowa<26)
        {
            *(wb++)=1;
        }
        else
        {
            *(wb++)=0;
        }
    }
}

int mod (int a, int b)
{
   int ret = a % b;
   if(ret < 0)
     ret+=b;
   return ret;
}

void przeliczGeneracjeNaKomorce(bool tablica[][nX], bool bTymczasowa[][nX])
{
    for(int y=0; y<nY; y++)
    {
        for(int x=0; x<nX; x++)
        {
            int nLive=0;

            nLive = tablica[mod(y-1, nY)][mod(x-1, nX)]+tablica[y][mod(x-1, nX)]+tablica[mod(y+1, nY)][mod(x-1, nX)]
                +tablica[mod(y-1, nY)][mod(x, nX)]+tablica[mod(y+1, nY)][mod(x, nX)]
                +tablica[mod(y-1, nY)][mod(x+1, nX)]+tablica[mod(y, nY)][mod(x+1, nX)]+tablica[mod(y+1, nY)][mod(x+1, nX)];

            if(tablica[y][x]==0)
            {
                if(nLive==3)
                {
                    bTymczasowa[y][x]=1;
                }
                else
                {
                    bTymczasowa[y][x]=0;
                }
            }
            else if(tablica[y][x]==1)
            {
                if((nLive<2)||(nLive>3))
                {
                    bTymczasowa[y][x]=0;
                }
                else
                {
                    bTymczasowa[y][x]=1;
                }
            }
        }
    }
}

void kopiujTablice(bool tablica[][nX], bool bTymczasowa[][nX])
{
    for(int y=0; y<nY; y++)
    {
        for(int x=0; x<nX; x++)
        {
            tablica[y][x]=bTymczasowa[y][x];
        }
    }
}

void kolejnaGeneracja(bool tablica[][nX], bool bTymczasowa[][nX])
{
    przeliczGeneracjeNaKomorce(tablica, bTymczasowa);
    kopiujTablice(tablica, bTymczasowa);
}

void drukujTablice(bool tablica[][nX])
{
    system("cls");
    cout<<"------------------------------------------------------------------------"<<endl;
    for(int y=0; y<nY; y++)
    {
        cout<<"|";
        for(int x=0; x<nX; x++)
        {
            if(tablica[y][x]==0)
            {
                cout<<' ';
            }
            else
            {
                cout<<'*';
            }
        }
        cout<<"|"<<endl;
    }
    cout<<"------------------------------------------------------------------------"<<endl;
}

bool czyKonczyc(int i)
{
    if(i%100==0)
    {
        cout<<endl<<endl<<"  1. Continue"<<endl<<"  2. Exit"<<endl<<"   Your choise: ";
        int wybor;
        cin>>wybor;
        switch(wybor)
        {
            case 1: return 0;
            case 2: return 1;
        }
    }
    else
    {
        return 0;
    }
}
<|endoftext|>


<commit_before>00bc7fc7-2748-11e6-85a4-e0f84713e7b8<commit_msg>ashley added more bugs<commit_after>00d2fc19-2748-11e6-9548-e0f84713e7b8<|endoftext|>


<commit_before>#include "net/neuron.hpp"
#include "net/genetic.hpp"

#include <algorithm>
#include <iostream>

using namespace neuron;
using namespace std;

typedef Net<7> XorNet;

const int GRADE_REPETITIONS = 4;
const double MAX_ERROR = 0.00001;

static const vector<vector<int>> input = {
    { -1, -1, -1 },
    { -1,  1,  1 },
    {  1, -1,  1 },
    {  1,  1, -1 }
};

void test(XorNet & net) {
    for (int c = 0; c < input.size(); ++c) {
        net.stimulate(0, input[c][0]);
        net.stimulate(1, input[c][1]);

        net.step();

        cout << "INPUT 1: "<< input[c][0] << "\tINPUT 2: " << input[c][1] << "\tEXPECTED: " << input[c][2]
             << "\tOUTPUT: " << net.value(6) << endl;
    }
}

vector<double> grade(vector<XorNet> & nets) {
    vector<double> results;

    auto nextIt = [](decltype(input.begin()) & iter) {
        if (++iter == input.end()) {
            iter = input.begin();
        }
    };

    for (auto & net : nets) {
        double deviation = 0;
        double maxDeviation = input.size() * GRADE_REPETITIONS * 2.;

        auto inputIter = input.begin();

        for (int c = 0; c < input.size() * GRADE_REPETITIONS; nextIt(inputIter), ++c) {
            auto & data = *inputIter;

            net.stimulate(0, data[0]);
            net.stimulate(1, data[1]);

            net.step();

            deviation += fabs((data[2] + 1.) - (net.value(6) + 1.));
        }

        results.push_back(deviation / maxDeviation);
    }

    return results;
}

int main() {

    XorNet base;
    // input 0 - to hidden
    base[0][2] = 0;
    base[0][3] = 0;
    base[0][4] = 0;
    base[0][5] = 0;

    // input 1 - to hidden
    base[1][2] = 0;
    base[1][3] = 0;
    base[1][4] = 0;
    base[1][5] = 0;

    // hidden to output
    base[2][6] = 0;
    base[3][6] = 0;
    base[4][6] = 0;
    base[5][6] = 0;

    vector<XorNet> nets(10, base);
    for_each(nets.begin(), nets.end(), neuron::random<7>);

    while (1) {
        auto grades = grade(nets);
        vector<int> sorted(grades.size());
        int c = 0;
        for (auto & i : sorted) { i = c++; }

        sort(sorted.begin(), sorted.end(), [&grades] (int left, int right) {
            return grades[left] > grades[right];
        });

        for (int c = 0; c < grades.size(); ++c) {
            cout << grades[sorted[c]] <<  endl;
        }

        XorNet & best = nets[sorted.back()];

        if (grades[sorted.back()] < MAX_ERROR) {
            cout << "Best error: " << grades[sorted.back()] << endl;

            test(best);
            return 0;
        }

        auto randNet = [&nets]() -> XorNet & {
            return nets[randMax(nets.size() - 1)];
        };

        for (int c = 0; c < grades.size() / 2; ++c) {
            auto idx = sorted[c];

            nets[idx] = cross(best, randNet());
            if (chance(0.05)) {
                mutate(nets[idx], 0.5);
            }
        }
    }

}
<commit_msg>Add more mutation<commit_after>#include "net/neuron.hpp"
#include "net/genetic.hpp"

#include <algorithm>
#include <iostream>

using namespace neuron;
using namespace std;

typedef Net<7> XorNet;

const int GRADE_REPETITIONS = 10;
const double MAX_ERROR = 0.01;

static const vector<vector<int>> input = {
    { -1, -1, -1 },
    { -1,  1,  1 },
    {  1, -1,  1 },
    {  1,  1, -1 }
};

void test(XorNet & net) {
    for (int c = 0; c < input.size(); ++c) {
        net.stimulate(0, input[c][0]);
        net.stimulate(1, input[c][1]);

        net.step();

        cout << "INPUT 1: "<< input[c][0] << "\tINPUT 2: " << input[c][1] << "\tEXPECTED: " << input[c][2]
             << "\tOUTPUT: " << net.value(6) << endl;
    }
}

vector<double> grade(vector<XorNet> & nets) {
    vector<double> results;

    auto nextIt = [](decltype(input.begin()) & iter) {
        if (++iter == input.end()) {
            iter = input.begin();
        }
    };

    for (auto & net : nets) {
        double deviation = 0;
        double maxDeviation = input.size() * GRADE_REPETITIONS * 2.;

        auto inputIter = input.begin();

        for (int c = 0; c < input.size() * GRADE_REPETITIONS; nextIt(inputIter), ++c) {
            auto & data = *inputIter;

            net.stimulate(0, data[0]);
            net.stimulate(1, data[1]);

            net.step();

            deviation += fabs((data[2] + 1.) - (net.value(6) + 1.));
        }

        results.push_back(deviation / maxDeviation);
    }

    return results;
}

int main() {

    XorNet base;
    // input 0 - to hidden
    base[0][2] = 0;
    base[0][3] = 0;
    base[0][4] = 0;
    base[0][5] = 0;

    // input 1 - to hidden
    base[1][2] = 0;
    base[1][3] = 0;
    base[1][4] = 0;
    base[1][5] = 0;

    // hidden to output
    base[2][6] = 0;
    base[3][6] = 0;
    base[4][6] = 0;
    base[5][6] = 0;

    vector<XorNet> nets(10, base);
    for_each(nets.begin(), nets.end(), neuron::random<7>);

    while (1) {
        auto grades = grade(nets);
        vector<int> sorted(grades.size());
        int c = 0;
        for (auto & i : sorted) { i = c++; }

        sort(sorted.begin(), sorted.end(), [&grades] (int left, int right) {
            return grades[left] > grades[right];
        });

        for (int c = 0; c < grades.size(); ++c) {
            cout << grades[sorted[c]] <<  endl;
        }

        XorNet & best = nets[sorted.back()];

        if (grades[sorted.back()] < MAX_ERROR) {
            cout << "Best error: " << grades[sorted.back()] << endl;

            test(best);
            return 0;
        }

        auto randNet = [&nets]() -> XorNet & {
            return nets[randMax(nets.size() - 1)];
        };

        // cross the lower half with low chance of mutation
        for (int c = 0; c < grades.size() / 2; ++c) {
            auto idx = sorted[c];

            nets[idx] = cross(best, randNet());
            if (chance(0.1)) {
                mutate(nets[idx], 0.5);
            }
        }

        // mutate 20% of the middle
        for (int c = 0; c < grades.size() / 5; ++c) {
            mutate(nets[idx + grades.size() / 2], 0.5);
        }

    }

    return 0;
}
<|endoftext|>


<commit_before>e0b3daa8-2747-11e6-a0cc-e0f84713e7b8<commit_msg>TODO: Add a beter commit message<commit_after>e0bfb954-2747-11e6-a55c-e0f84713e7b8<|endoftext|>


<commit_before>a5c6aa8c-ad5a-11e7-ab4f-ac87a332f658<commit_msg>roselyn broke it<commit_after>a6656d7d-ad5a-11e7-8f3b-ac87a332f658<|endoftext|>


<commit_before>0314041e-ad5d-11e7-b699-ac87a332f658<commit_msg>Typical bobby<commit_after>038318fd-ad5d-11e7-83ec-ac87a332f658<|endoftext|>


<commit_before>e1c4e157-ad58-11e7-b92d-ac87a332f658<commit_msg>compiles now<commit_after>e2214463-ad58-11e7-9686-ac87a332f658<|endoftext|>


<commit_before>4ad02d33-ad58-11e7-9d8d-ac87a332f658<commit_msg>Typical bobby<commit_after>4b436b9c-ad58-11e7-9f96-ac87a332f658<|endoftext|>


<commit_before>/*
 * noice - ...
 * Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cstdio>
#include <cstring>

#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

// --------------------------------------------------------------------------------------------------------------------

#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"

// --------------------------------------------------------------------------------------------------------------------

static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd   = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd   = 63;
static const int kJoystickMaxAnalog   = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton   = kJoystickButtonEnd-kJoystickButtonStart;

// --------------------------------------------------------------------------------------------------------------------

struct js_event {
    unsigned int time;      /* event timestamp in milliseconds */
    short value;            /* value */
    unsigned char type;     /* event type */
    unsigned char number;   /* axis/button number */
};

JackData::JackData() noexcept
    : joystick(false),
      device(kNull),
      fd(-1),
      nr(-1),
      thread(0),
      client(nullptr),
      midiport(nullptr)
{
    pthread_mutex_init(&mutex, nullptr);
    std::memset(buf, 0, kBufSize);
    std::memset(oldbuf, 0, kBufSize);
}

JackData::~JackData()
{
    if (client != nullptr)
    {
        jack_deactivate(client);
        jack_client_close(client);
    }

    if (fd >= 0)
        close(fd);

    pthread_mutex_destroy(&mutex);
}

// --------------------------------------------------------------------------------------------------------------------

static void shutdown_callback(void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
}

static int process_callback(const jack_nframes_t frames, void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    // try lock asap, not fatal yet
    bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

    // stack data
    unsigned char tmpbuf[JackData::kBufSize];

    // get jack midi port buffer
    void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
    jack_midi_clear_buffer(midibuf);

    // try lock again
    if (! locked)
    {
        locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

        // could not try-lock until here, stop
        if (! locked)
            return 0;
    }

    // copy buf data into a temp location so we can release the lock
    std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        PS3::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kDualShock4:
        PS4::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kGuitarHero:
        GuitarHero::process(jackdata, midibuf, tmpbuf);
        break;
    }

    // cache current buf for comparison on next call
    std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static bool noice_init(JackData* const jackdata, const char* const device)
{
    if (device == nullptr || device[0] == '\0')
        return false;

    int nr;
    unsigned char buf[JackData::kBufSize];

    jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;

    if ((jackdata->fd = open(device, O_RDONLY)) < 0)
    {
        fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
        return false;
    }

    const char* const deviceNum = device+(strlen(device)-1);

    if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
    {
        fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
        return false;
    }

    printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);

    if (jackdata->joystick)
    {
        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        memset(buf, 0, JackData::kBufSize);

        // TODO - ask joystick to know what it is
        jackdata->device = JackData::kGuitarHero;
        jackdata->nr = 9;
    }
    else
    {
        switch (nr)
        {
        case 49:
            jackdata->device = JackData::kDualShock3;
            break;
        case 64:
            jackdata->device = JackData::kDualShock4;
            break;
        default:
            fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        jackdata->nr = nr;
    }

    char tmpName[32];
    std::strcpy(tmpName, "noice");
    std::strcat(tmpName, deviceNum);

    if (jackdata->client == nullptr)
    {
        jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);

        if (jackdata->client == nullptr)
        {
            fprintf(stderr, "noice:: failed to register jack client\n");
            return false;
        }
    }

    std::strcpy(tmpName, "noice_capture_");
    std::strcat(tmpName, deviceNum);

    jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);

    if (jackdata->midiport == nullptr)
    {
        fprintf(stderr, "noice:: failed to register jack midi port\n");
        return false;
    }

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
        break;
    case JackData::kDualShock4:
        jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
        break;
    case JackData::kGuitarHero:
        jack_port_set_alias(jackdata->midiport, "Guitar Hero");
        break;
    }

    std::memcpy(jackdata->buf, buf, jackdata->nr);

    jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
    jack_set_process_callback(jackdata->client, process_callback, jackdata);
    jack_activate(jackdata->client);

    return true;
}

static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
    if (jackdata->client == nullptr)
        return false;

    if (jackdata->joystick)
    {
        js_event ev;
        const int nr = read(jackdata->fd, &ev, sizeof(js_event));

        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }

        // ignore synthetic events
        ev.type &= ~0x80;

        // put data into buf to simulate a raw device
        switch (ev.type)
        {
        case 1: { // button
            if (ev.number > kJoystickMaxButton)
                break;
            if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
                --ev.number;

            const int mask = 1 << ev.number;
            const int offs = kJoystickButtonStart + (ev.number / 8);

            if (ev.value)
                buf[offs] |= mask;
            else
                buf[offs] &= ~mask;
            break;
        }
        case 2: { // axis
            if (ev.number > kJoystickMaxAnalog)
                break;
            const int offs = kJoystickAnalogStart + ev.number;

            buf[offs] = (ev.value + 32767) / 256;
            break;
        }
        }
    }
    else
    {
        const int nr = read(jackdata->fd, buf, jackdata->nr);

        if (nr != jackdata->nr)
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }
    }

    pthread_mutex_lock(&jackdata->mutex);
    std::memcpy(jackdata->buf, buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

#if 1
        printf("\n==========================================\n");
        for (int j=0; j<jackdata->nr; j++)
        {
            printf("%02X ", buf[j]);

            if ((j+1) % 16 == 0)
                printf("\n");
        }
#endif

    return true;
}

// --------------------------------------------------------------------------------------------------------------------

static volatile bool gRunning;

static void signalHandler(int)
{
    gRunning = false;
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
        return 1;
    }

    JackData jackdata;

    if (! noice_init(&jackdata, argv[1]))
        return 1;

    gRunning = true;

    struct sigaction sig;
    sig.sa_handler  = signalHandler;
    sig.sa_flags    = SA_RESTART;
    sig.sa_restorer = nullptr;
    sigemptyset(&sig.sa_mask);
    sigaction(SIGINT,  &sig, nullptr);
    sigaction(SIGTERM, &sig, nullptr);

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (gRunning && noice_idle(&jackdata, buf)) {}

    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static void* gInternalClientRun(void* arg)
{
    JackData* const jackdata = (JackData*)arg;

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (noice_idle(jackdata, buf)) {}

    return nullptr;
}

extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);

int jack_initialize(jack_client_t* client, const char* load_init)
{
    JackData* const jackdata = new JackData();

    jackdata->client = client;
    if (! noice_init(jackdata, load_init))
        return 1;

    pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
    return 0;
}

extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);

void jack_finish(void* arg)
{
    if (arg == nullptr)
        return;

    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
    pthread_join(jackdata->thread, nullptr);

    delete jackdata;
}

// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Disable debug print<commit_after>/*
 * noice - ...
 * Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cstdio>
#include <cstring>

#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

// --------------------------------------------------------------------------------------------------------------------

#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"

// --------------------------------------------------------------------------------------------------------------------

static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd   = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd   = 63;
static const int kJoystickMaxAnalog   = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton   = kJoystickButtonEnd-kJoystickButtonStart;

// --------------------------------------------------------------------------------------------------------------------

struct js_event {
    unsigned int time;      /* event timestamp in milliseconds */
    short value;            /* value */
    unsigned char type;     /* event type */
    unsigned char number;   /* axis/button number */
};

JackData::JackData() noexcept
    : joystick(false),
      device(kNull),
      fd(-1),
      nr(-1),
      thread(0),
      client(nullptr),
      midiport(nullptr)
{
    pthread_mutex_init(&mutex, nullptr);
    std::memset(buf, 0, kBufSize);
    std::memset(oldbuf, 0, kBufSize);
}

JackData::~JackData()
{
    if (client != nullptr)
    {
        jack_deactivate(client);
        jack_client_close(client);
    }

    if (fd >= 0)
        close(fd);

    pthread_mutex_destroy(&mutex);
}

// --------------------------------------------------------------------------------------------------------------------

static void shutdown_callback(void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
}

static int process_callback(const jack_nframes_t frames, void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    // try lock asap, not fatal yet
    bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

    // stack data
    unsigned char tmpbuf[JackData::kBufSize];

    // get jack midi port buffer
    void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
    jack_midi_clear_buffer(midibuf);

    // try lock again
    if (! locked)
    {
        locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

        // could not try-lock until here, stop
        if (! locked)
            return 0;
    }

    // copy buf data into a temp location so we can release the lock
    std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        PS3::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kDualShock4:
        PS4::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kGuitarHero:
        GuitarHero::process(jackdata, midibuf, tmpbuf);
        break;
    }

    // cache current buf for comparison on next call
    std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static bool noice_init(JackData* const jackdata, const char* const device)
{
    if (device == nullptr || device[0] == '\0')
        return false;

    int nr;
    unsigned char buf[JackData::kBufSize];

    jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;

    if ((jackdata->fd = open(device, O_RDONLY)) < 0)
    {
        fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
        return false;
    }

    const char* const deviceNum = device+(strlen(device)-1);

    if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
    {
        fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
        return false;
    }

    printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);

    if (jackdata->joystick)
    {
        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        memset(buf, 0, JackData::kBufSize);

        // TODO - ask joystick to know what it is
        jackdata->device = JackData::kGuitarHero;
        jackdata->nr = 9;
    }
    else
    {
        switch (nr)
        {
        case 49:
            jackdata->device = JackData::kDualShock3;
            break;
        case 64:
            jackdata->device = JackData::kDualShock4;
            break;
        default:
            fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        jackdata->nr = nr;
    }

    char tmpName[32];
    std::strcpy(tmpName, "noice");
    std::strcat(tmpName, deviceNum);

    if (jackdata->client == nullptr)
    {
        jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);

        if (jackdata->client == nullptr)
        {
            fprintf(stderr, "noice:: failed to register jack client\n");
            return false;
        }
    }

    std::strcpy(tmpName, "noice_capture_");
    std::strcat(tmpName, deviceNum);

    jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);

    if (jackdata->midiport == nullptr)
    {
        fprintf(stderr, "noice:: failed to register jack midi port\n");
        return false;
    }

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
        break;
    case JackData::kDualShock4:
        jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
        break;
    case JackData::kGuitarHero:
        jack_port_set_alias(jackdata->midiport, "Guitar Hero");
        break;
    }

    std::memcpy(jackdata->buf, buf, jackdata->nr);

    jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
    jack_set_process_callback(jackdata->client, process_callback, jackdata);
    jack_activate(jackdata->client);

    return true;
}

static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
    if (jackdata->client == nullptr)
        return false;

    if (jackdata->joystick)
    {
        js_event ev;
        const int nr = read(jackdata->fd, &ev, sizeof(js_event));

        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }

        // ignore synthetic events
        ev.type &= ~0x80;

        // put data into buf to simulate a raw device
        switch (ev.type)
        {
        case 1: { // button
            if (ev.number > kJoystickMaxButton)
                break;
            if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
                --ev.number;

            const int mask = 1 << ev.number;
            const int offs = kJoystickButtonStart + (ev.number / 8);

            if (ev.value)
                buf[offs] |= mask;
            else
                buf[offs] &= ~mask;
            break;
        }
        case 2: { // axis
            if (ev.number > kJoystickMaxAnalog)
                break;
            const int offs = kJoystickAnalogStart + ev.number;

            buf[offs] = (ev.value + 32767) / 256;
            break;
        }
        }
    }
    else
    {
        const int nr = read(jackdata->fd, buf, jackdata->nr);

        if (nr != jackdata->nr)
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }
    }

    pthread_mutex_lock(&jackdata->mutex);
    std::memcpy(jackdata->buf, buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

#if 0
        printf("\n==========================================\n");
        for (int j=0; j<jackdata->nr; j++)
        {
            printf("%02X ", buf[j]);

            if ((j+1) % 16 == 0)
                printf("\n");
        }
#endif

    return true;
}

// --------------------------------------------------------------------------------------------------------------------

static volatile bool gRunning;

static void signalHandler(int)
{
    gRunning = false;
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
        return 1;
    }

    JackData jackdata;

    if (! noice_init(&jackdata, argv[1]))
        return 1;

    gRunning = true;

    struct sigaction sig;
    sig.sa_handler  = signalHandler;
    sig.sa_flags    = SA_RESTART;
    sig.sa_restorer = nullptr;
    sigemptyset(&sig.sa_mask);
    sigaction(SIGINT,  &sig, nullptr);
    sigaction(SIGTERM, &sig, nullptr);

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (gRunning && noice_idle(&jackdata, buf)) {}

    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static void* gInternalClientRun(void* arg)
{
    JackData* const jackdata = (JackData*)arg;

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (noice_idle(jackdata, buf)) {}

    return nullptr;
}

extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);

int jack_initialize(jack_client_t* client, const char* load_init)
{
    JackData* const jackdata = new JackData();

    jackdata->client = client;
    if (! noice_init(jackdata, load_init))
        return 1;

    pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
    return 0;
}

extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);

void jack_finish(void* arg)
{
    if (arg == nullptr)
        return;

    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
    pthread_join(jackdata->thread, nullptr);

    delete jackdata;
}

// --------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>b9b21363-2747-11e6-a6de-e0f84713e7b8<commit_msg>updated some files<commit_after>b9c0b470-2747-11e6-bed4-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

#include "using.h"
#include "foobar.h"

using using_delegate::using_;

template<typename T>
class Property : public using_<Property<T>, T>
{
public:
    operator T &()
    {
        return data;
    }

private:
    T data;
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;

    Property<std::vector<int>> v;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    //v.push_back(1, 2, 3);

    for (auto x : v)
    {
        std::cout << x << std::endl;
    }

    Property<int> x{};
    Property<int> y{};

    auto z = x + y;

    std::cout << z << std::endl;
    std::cout << typeid(z).name() << std::endl;

    Property<foobar::Foo> foo;
    foo.foo();

    Property<foobar::Bar> bar;
    bar.bar();
    bar.bar2();
    bar.bar3();
}
<commit_msg>Added additional test for intrusive reflection of Baz::baz().<commit_after>#include <iostream>
#include <vector>

#include "using.h"
#include "foobar.h"

using using_delegate::using_;

template<typename T>
class Property : public using_<Property<T>, T>
{
public:
    operator T &()
    {
        return data;
    }

private:
    T data;
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;

    Property<std::vector<int>> v;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    //v.push_back(1, 2, 3);

    for (auto x : v)
    {
        std::cout << x << std::endl;
    }

    Property<int> x{};
    Property<int> y{};

    auto z = x + y;

    std::cout << z << std::endl;
    std::cout << typeid(z).name() << std::endl;

    Property<foobar::Foo> foo;
    foo.foo();

    Property<foobar::Bar> bar;
    bar.bar();
    bar.bar2();
    bar.bar3();

    Property<foobar::Baz> baz;
    baz.baz();
}
<|endoftext|>


<commit_before>3c307394-2748-11e6-a721-e0f84713e7b8<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>3c436b2b-2748-11e6-97e1-e0f84713e7b8<|endoftext|>


<commit_before>/*

	Please see LICENSE_flynda

*/
#include "inotify-cxx.h"
#include<string>
int main(){
	using namespace std;
	/*

	watching a directory

	*/
	string dir = "/tmp";
	string dir2 = "/proc/33/fd";

	//creating the watcher -- adding directory
	Inotify notify;
	InotifyWatch watch(dir, IN_ALL_EVENTS);
	watch.setNonBlock(false);
	notify.Add(watch);

	//wating for a response
	while(true){
		notify.waitForEvents();
		//dealing with fired events
		num_events = notify.GetEventCount();
		for (int i=num_events; i>0; --i){
			InotifyEvent event;
			//getting current fired event
			if (notify.GetEvent(&event)){
				string event_name = event.GetName();
				uint32_t mask = event.GetMask();
				//do something here
				cout << event_name << " : " << mask << endl;
			}
			else{
				//event retrieval failed
				cerr << "event retrieval failed" << endl;
			}
		}
	}
	return 0;
}
<commit_msg>quick debugging<commit_after>/*

	Please see LICENSE_flynda

*/
#include "inotify-cxx.h"
#include<string>
#include<iostream>
int main(){
	using namespace std;
	/*

	watching a directory

	*/
	string dir = "/tmp";
	string dir2 = "/proc/33/fd";

	//creating the watcher -- adding directory
	Inotify notify;
	InotifyWatch watch(dir, IN_ALL_EVENTS);
	notify.setNonBlock(false);
	notify.Add(watch);

	//wating for a response
	while(true){
		notify.WaitForEvents();
		//dealing with fired events
		num_events = notify.GetEventCount();
		for (int i=num_events; i>0; --i){
			InotifyEvent event;
			//getting current fired event
			if (notify.GetEvent(&event)){
				string event_name = event.GetName();
				uint32_t mask = event.GetMask();
				//do something here
				cout << event_name << " : " << mask << endl;
			}
			else{
				//event retrieval failed
				cerr << "event retrieval failed" << endl;
			}
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/**
 * Main controller for an electronic longboard (long skateboard) project.
 * Inteded for Arduino Nano (v3.0).
 *
 * ESC control:     PWM            pins D9 (any pwm: D3, 5, 6, 9, 10, 11)
 * Accelerometer:   I2C (library)  pins A4 (SDA), A5 (SCL)
 * Bluetooth:       Serial         pins RX0, TX1, 3V3
 */

#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

// Bluetooth pins 0, 1, 3V3
#define Bluetooth Serial
// default
#define BluetoothSerialSpeed 9600
// serial config is default: 8, 1, n

// +- 2, +- 4, +- 8
#define AccelerationRange MMA8451_RANGE_2_G
// #define AccelerationDataRate MMA8451_DATARATE_200_HZ

// Used for blinking on error
#define StatusLed 13

// Accelerometer
Adafruit_MMA8451 mma = Adafruit_MMA8451();

void setup() {
    pinMode(StatusLed, OUTPUT);

    // Connect i2c accelerometer
    setupAccelerometer();

    // Connect bluetooth serial
    setupBluetooth();
}

// MAINLOOP
void loop() {

}

// Stop and blink when error occurs
void errorStop() {
    while (1) {
        digitalWrite(StatusLed, LOW);
        delay(1000);
        digitalWrite(StatusLed, HIGH);
        delay(1000);
    }
}

bool setupAccelerometer() {

    if (! mma.begin()) {
        // Serial.println("Couldnt start");
        errorStop();
    }

    mma.setRange(AccelerationRange);
    //mma.setDataRate(AccelerationDataRate);
}

void setupBluetooth() {
    Bluetooth.begin(BluetoothSerialSpeed);
}

<commit_msg>old status stuff<commit_after>/**
 * Main controller for an electronic longboard (long skateboard) project.
 * Inteded for Arduino Nano (v3.0).
 *
 * ESC control:     PWM            pins D9 (any pwm: D3, 5, 6, 9, 10, 11)
 * Accelerometer:   I2C (library)  pins A4 (SDA), A5 (SCL)
 * Bluetooth:       Serial         pins RX0, TX1, 3V3
 */

#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

// Bluetooth pins 0, 1, 3V3
#define Bluetooth Serial
// default
#define BluetoothSerialSpeed 9600
// serial config is default: 8, 1, n

// +- 2, +- 4, +- 8
#define AccelerationRange MMA8451_RANGE_2_G
// #define AccelerationDataRate MMA8451_DATARATE_200_HZ

// Used for blinking on error
#define StatusLed 13

// Accelerometer
Adafruit_MMA8451 mma = Adafruit_MMA8451();

void setup() {
    pinMode(StatusLed, OUTPUT);
    digitalWrite(StatusLed, HIGH); // High until setup ends

    // Connect i2c accelerometer
    setupAccelerometer();

    // Connect bluetooth serial
    setupBluetooth();

    digitalWrite(StatusLed, LOW);
}

// MAINLOOP
void loop() {

    // mma.read();
    // mma.x; mma.y; mma.z;
}

// Stop and blink when error occurs
void errorStop() {
    while (1) {
        digitalWrite(StatusLed, LOW);
        delay(1000);
        digitalWrite(StatusLed, HIGH);
        delay(1000);
    }
}

bool setupAccelerometer() {

    if (! mma.begin()) {
        // Serial.println("Couldnt start");
        errorStop();
    }

    mma.setRange(AccelerationRange);
    //mma.setDataRate(AccelerationDataRate);
}

void setupBluetooth() {
    Bluetooth.begin(BluetoothSerialSpeed);
}

<|endoftext|>


<commit_before>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 3.1b-dev1
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24	1.0b		Patrick Rye		-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24	1.1b		Patrick Rye		-Attempted to allow movement on map through arrow keys.
										-Could not get this to work and broke everything. Rolling back to previous version.
										-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25	1.2b		Patrick Rye		-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26	1.3b		Patrick Rye		-Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27	2.0b		Patrick Rye		-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27	2.1b		Patrick Rye		-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
2015/03/02	2.2b		Patrick Rye		-Improved code a bit.
										-Added version number tracker.
										-Prompt for loading save.
										-Prompt for incorrect save version.
										-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02	2.2.1b		Patrick Rye		-Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03	2.3b		Patrick Rye		-Added more comments.
										-Changed some wording to better explain stuff.
										-Added a debug mode to game, detects if source code exists.
										-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04	2.4b		Patrick Rye		-Debug mode can be set by loading a debug save.
										-Grammar & spelling fixes.
										-Improved map menu.
										-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06	2.5ß		Patrick Rye		-Changed some debug commands.
										-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
										-Added better opening message.
										-Replaced all system("pause") with getchar();
=============================================================================================================================================================
2015/03/06	3.0b		Patrick Rye		-Redid some calculations in battle.h
										-Added better winning message.
										-Added spells.h does nothing currently just for testing.
=============================================================================================================================================================
2015/03/09	3.1b		Patrick Rye		-
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
//#include "spells.h" //Functions that deal with spells and magic, a possible future addition.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "3.1b-dev1"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//Some constant string for different messages that appear as large ASCII text.
const string OpeningMessage[16] = {"                                                             \n",
								   ",--.   ,--.       ,--.                                       \n",
								   "|  |   |  | ,---. |  | ,---. ,---. ,--,--,--. ,---.          \n",
								   "|  |.'.|  || .-. :|  || .--'| .-. ||        || .-. :         \n",
								   "|   ,'.   |\\   --.|  |\\ `--.' '-' '|  |  |  |\\   --.         \n",
								   "'--'   '--' `----'`--' `---' `---' `--`--`--' `----'         \n",
								   "  ,--.                                                       \n",
								   ",-'  '-. ,---.                                               \n",
								   "'-.  .-'| .-. |                                              \n",
								   "  |  |  ' '-' '                                              \n",
								   "  `--'   `---'                                               \n",
								   "  ,---.    ,--.    ,--.                ,--.                  \n",
								   " /  O  \\ ,-'  '-.,-'  '-. ,--,--. ,---.|  |,-. ,---. ,--.--. \n",
								   "|  .-.  |'-.  .-''-.  .-'' ,-.  || .--'|     /| .-. :|  .--' \n",
								   "|  | |  |  |  |    |  |  \\ '-'  |\\ `--.|  \\  \\\\   --.|  |    \n",
								   "`--' `--'  `--'    `--'   `--`--' `---'`--'`--'`----'`--'    \n"};

const string WinningMessage[6] = {"__   __            _    _ _       _ _ \n",
								 "\\ \\ / /           | |  | (_)     | | |\n",
								 " \\ V /___  _   _  | |  | |_ _ __ | | |\n",
								 "  \\ // _ \\| | | | | |/\\| | | '_ \\| | |\n",
								 "  | | (_) | |_| | \\  /\\  / | | | |_|_|\n",
								 "  \\_/\\___/ \\__,_|  \\/  \\/|_|_| |_(_|_)\n"};

/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.

	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }

	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true);} //Sets debug mode for both rooms.h & battle.h

	for (int i = 0; i < 16; i++){cout<<OpeningMessage[i];}
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);

			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	for (int i = 0; i < 6; i++) {cout<<WinningMessage[i];}
	getchar();
	return 0;
//End of main
}
<commit_msg>Update main to V3.1b-dev4<commit_after>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 3.1b-dev4
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24	1.0b		Patrick Rye		-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24	1.1b		Patrick Rye		-Attempted to allow movement on map through arrow keys.
										-Could not get this to work and broke everything. Rolling back to previous version.
										-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25	1.2b		Patrick Rye		-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26	1.3b		Patrick Rye		-Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27	2.0b		Patrick Rye		-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27	2.1b		Patrick Rye		-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
2015/03/02	2.2b		Patrick Rye		-Improved code a bit.
										-Added version number tracker.
										-Prompt for loading save.
										-Prompt for incorrect save version.
										-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02	2.2.1b		Patrick Rye		-Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03	2.3b		Patrick Rye		-Added more comments.
										-Changed some wording to better explain stuff.
										-Added a debug mode to game, detects if source code exists.
										-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04	2.4b		Patrick Rye		-Debug mode can be set by loading a debug save.
										-Grammar & spelling fixes.
										-Improved map menu.
										-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06	2.5ß		Patrick Rye		-Changed some debug commands.
										-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
										-Added better opening message.
										-Replaced all system("pause") with getchar();
=============================================================================================================================================================
2015/03/06	3.0b		Patrick Rye		-Redid some calculations in battle.h
										-Added better winning message.
										-Added spells.h does nothing currently just for testing.
=============================================================================================================================================================
2015/03/09	3.1b		Patrick Rye		-Edits to spells.h, more testing on adding spells.
										-Sets debug mode in spells.h
										-Win / opening messages moved to basic.h
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
#include "spells.h" //Functions that deal with spells and magic, a possible future addition.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "3.1b-dev4"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.

	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }

	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);} //Sets debug mode for both rooms.h, battle.h, & spells.h

	ShowOpeningMessage();
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);

			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	ShowWinningMessage();
	getchar();
	return 0;
//End of main
}
<|endoftext|>


<commit_before>//
// Created by volundr on 7/19/16.
//

#include <iostream>
#include <iomanip>
#include "Bno055Interface.h"
#include "bno055DataSheet.h"

#define BNO055_DEVICE_FILE "/dev/ttyS0"

using namespace bno055;

int main() {
    Bno055Interface bno055;
    bno055.init(BNO055_DEVICE_FILE);
    if (bno055.isLive()) {
        std::cout << "BNO055 is live.\n";
    } else {
        std::cout << "Could not contact BNO055!\n";
        return 1;
    }

    vec3_16 orient;
    vec3_f orientDeg;
    while(bno055.updateOrientation(&orient)) {
        orientDeg = orient.toFloatsDeg();
        std::cout << "-> ";
        std::cout << std::setiosflags(std::ios::right);
        std::cout << std::setiosflags(std::ios::fixed);
        std::cout << std::setw(8) << std::setprecision(4) << orientDeg.heading
                  << std::setw(8) << std::setprecision(4) << orientDeg.roll
                  << std::setw(8) << std::setprecision(4) << orientDeg.pitch;
        std::cout << std::endl;
    }

//    ImuData_16 imuData;
//    while(bno055.updateImuData(&imuData)) {
//        std::cout << "-> " << imuData.names.orient.heading << " "
//                  << imuData.names.orient.roll << " "
//                  << imuData.names.orient.pitch << std::endl;
//    }

    std::cout << "Data gathering halted, exiting!\n";

    return 0;
}

<commit_msg>updated orientation output<commit_after>//
// Created by volundr on 7/19/16.
//

#include <iostream>
#include <iomanip>
#include "Bno055Interface.h"
#include "bno055DataSheet.h"

#define BNO055_DEVICE_FILE "/dev/ttyS0"

using namespace bno055;

int main() {
    Bno055Interface bno055;
    bno055.init(BNO055_DEVICE_FILE);
    if (bno055.isLive()) {
        std::cout << "BNO055 is live.\n";
    } else {
        std::cout << "Could not contact BNO055!\n";
        return 1;
    }

    vec3_16 orient;
    vec3_f orientDeg;
    while(bno055.updateOrientation(&orient)) {
        orientDeg = orient.toFloatsDeg();
        std::cout << "-> ";
        std::cout << std::setiosflags(std::ios::right);
        std::cout << std::setiosflags(std::ios::fixed);
        std::cout << std::setw(10) << std::setprecision(4) << orientDeg.heading
                  << std::setw(10) << std::setprecision(4) << orientDeg.roll
                  << std::setw(10) << std::setprecision(4) << orientDeg.pitch;
        std::cout << std::endl;
    }

//    ImuData_16 imuData;
//    while(bno055.updateImuData(&imuData)) {
//        std::cout << "-> " << imuData.names.orient.heading << " "
//                  << imuData.names.orient.roll << " "
//                  << imuData.names.orient.pitch << std::endl;
//    }

    std::cout << "Data gathering halted, exiting!\n";

    return 0;
}

<|endoftext|>


<commit_before>a92528fa-4b02-11e5-b687-28cfe9171a43<commit_msg>Typical lynda<commit_after>a9323678-4b02-11e5-9518-28cfe9171a43<|endoftext|>


<commit_before>#include "SDL.h"
#include "input.h"

SDL_Event Input::event;
bool Input::fDown;
bool Input::wDown;
bool Input::aDown;
bool Input::sDown;
bool Input::dDown;
bool Input::mQuit;

Input::Input(){
	mQuit = false;
}
Input::~Input(){}
void Input::PollEvent(){
	while(SDL_PollEvent(&event)){
		if (event.type == SDL_QUIT)
			mQuit = true;
		if (event.type == SDL_KEYDOWN){
			switch (event.key.keysym.sym){
				case SDLK_w:
					wDown = true;
					break;
				case SDLK_a:
					aDown = true;
					break;
				case SDLK_s:
					sDown = true;
					break;
				case SDLK_d:
					dDown = true;
					break;
				case SDLK_f:
					fDown = true;
					break;
				case SDLK_ESCAPE:
					mQuit = true;
					break;
				default:
					break;
			}
		}
		if (event.type == SDL_KEYUP){
			switch (event.key.keysym.sym){
				case SDLK_w:
					wDown = false;
					break;
				case SDLK_a:
					aDown = false;
					break;
				case SDLK_s:
					sDown = false;
					break;
				case SDLK_d:
					dDown = false;
					break;
				case SDLK_f:
					fDown = false;
					break;
				default:
					break;
			}
		}
	}
}
bool Input::KeyDown(char keyCode){
	switch (keyCode){
		case 'w':
			return wDown;
		case 'a':
			return aDown;
		case 's':
			return sDown;
		case 'd':
			return dDown;
		case 'f':
			return fDown;
		default:
			return false;
	}
}
bool Input::Quit(){
	return mQuit;
}<commit_msg>Added Window::HandleEvents into the Input::PollEvent function, but this is a pretty lazy method to do this<commit_after>#include "SDL.h"
#include "window.h"
#include "input.h"

SDL_Event Input::event;
bool Input::fDown;
bool Input::wDown;
bool Input::aDown;
bool Input::sDown;
bool Input::dDown;
bool Input::mQuit;

Input::Input(){
	mQuit = false;
}
Input::~Input(){}
void Input::PollEvent(){
	while(SDL_PollEvent(&event)){
		//this is an ok method to do this. But maybe not the best
		Window::HandleEvents(event);

		if (event.type == SDL_QUIT)
			mQuit = true;
		if (event.type == SDL_KEYDOWN){
			switch (event.key.keysym.sym){
				case SDLK_w:
					wDown = true;
					break;
				case SDLK_a:
					aDown = true;
					break;
				case SDLK_s:
					sDown = true;
					break;
				case SDLK_d:
					dDown = true;
					break;
				case SDLK_f:
					fDown = true;
					break;
				case SDLK_ESCAPE:
					mQuit = true;
					break;
				default:
					break;
			}
		}
		if (event.type == SDL_KEYUP){
			switch (event.key.keysym.sym){
				case SDLK_w:
					wDown = false;
					break;
				case SDLK_a:
					aDown = false;
					break;
				case SDLK_s:
					sDown = false;
					break;
				case SDLK_d:
					dDown = false;
					break;
				case SDLK_f:
					fDown = false;
					break;
				default:
					break;
			}
		}
	}
}
bool Input::KeyDown(char keyCode){
	switch (keyCode){
		case 'w':
			return wDown;
		case 'a':
			return aDown;
		case 's':
			return sDown;
		case 'd':
			return dDown;
		case 'f':
			return fDown;
		default:
			return false;
	}
}
bool Input::Quit(){
	return mQuit;
}<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "headeredtextedit.h"
#include <QDebug>
#include <MLocale>

HeaderedTextEdit::HeaderedTextEdit(QGraphicsItem *parent)
    : MTextEdit(MTextEditModel::MultiLine, QString(), parent),
    headerLabel(0)
{
    connect(document(), SIGNAL(blockCountChanged(int)), this, SLOT(_q_resetNewBlockMargin()));
    connect(this, SIGNAL(geometryChanged()), this, SLOT(_q_updateLabelPosition()));
}

HeaderedTextEdit::~HeaderedTextEdit()
{
}

void HeaderedTextEdit::setHeaderText(const QString &text)
{
    if (!headerLabel) {
        headerLabel = new MLabel(this);
        headerLabel->setObjectName("headerLabel");
        headerLabel->setStyleName("CommonEditorInputFieldLabel");
        headerLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
        headerLabel->setPos(0, 0);
        headerLabel->setPreferredHeight(effectiveSizeHint(Qt::PreferredSize).height());
        headerLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    }
    headerLabel->setText(text);

    _q_updateTextLeftMargin();
}

QString HeaderedTextEdit::staticHeaderText() const
{
    if(headerLabel) {
    	return headerLabel->text();
    } else {
	return QString();
    }
}

void HeaderedTextEdit::_q_updateTextLeftMargin()
{
    QSizeF labelSize = headerLabel->sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
    QTextCursor cursor(document());
    cursor.setPosition(0);
    QTextBlockFormat tbf = cursor.blockFormat();

    // Will not overwrite label if LeftMargin for
    // text block format is set. Usefuly for only inputs
    // such as emails.
    // tbf.setLeftMargin(labelSize.width());
    tbf.setTextIndent(labelSize.width());
    Qt::LayoutDirection dir = MLocale::directionForText(headerLabel->text());
    setLayoutDirection(dir);
    _q_updateLabelPosition();
    cursor.setBlockFormat(tbf);
}

void HeaderedTextEdit::_q_updateLabelPosition()
{
    if (layoutDirection() == Qt::RightToLeft) {
	QRectF geometry;
	QSizeF labelSize = headerLabel->sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
	geometry.setSize(labelSize);
	QSizeF textSize = sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
	geometry.setX(textSize.width() - labelSize.width());
	headerLabel->setGeometry(geometry);
    }
}

void HeaderedTextEdit::_q_resetNewBlockMargin()
{
    // This method shouldn't be used if text block format has LeftMargin set.
    QTextBlockFormat tbf = textCursor().blockFormat();
    if (textCursor().blockNumber() == 0) {
        tbf.setTextIndent(headerLabel->size().width());
    } else {
        tbf.setTextIndent(0);
    }
    textCursor().setBlockFormat(tbf);
}
<commit_msg>Changes: CC: removed tabs<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "headeredtextedit.h"
#include <QDebug>
#include <MLocale>

HeaderedTextEdit::HeaderedTextEdit(QGraphicsItem *parent)
    : MTextEdit(MTextEditModel::MultiLine, QString(), parent),
    headerLabel(0)
{
    connect(document(), SIGNAL(blockCountChanged(int)), this, SLOT(_q_resetNewBlockMargin()));
    connect(this, SIGNAL(geometryChanged()), this, SLOT(_q_updateLabelPosition()));
}

HeaderedTextEdit::~HeaderedTextEdit()
{
}

void HeaderedTextEdit::setHeaderText(const QString &text)
{
    if (!headerLabel) {
        headerLabel = new MLabel(this);
        headerLabel->setObjectName("headerLabel");
        headerLabel->setStyleName("CommonEditorInputFieldLabel");
        headerLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
        headerLabel->setPos(0, 0);
        headerLabel->setPreferredHeight(effectiveSizeHint(Qt::PreferredSize).height());
        headerLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    }
    headerLabel->setText(text);

    _q_updateTextLeftMargin();
}

QString HeaderedTextEdit::staticHeaderText() const
{
    if(headerLabel) {
        return headerLabel->text();
    } else {
        return QString();
    }
}

void HeaderedTextEdit::_q_updateTextLeftMargin()
{
    QSizeF labelSize = headerLabel->sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
    QTextCursor cursor(document());
    cursor.setPosition(0);
    QTextBlockFormat tbf = cursor.blockFormat();

    // Will not overwrite label if LeftMargin for
    // text block format is set. Usefuly for only inputs
    // such as emails.
    // tbf.setLeftMargin(labelSize.width());
    tbf.setTextIndent(labelSize.width());
    Qt::LayoutDirection dir = MLocale::directionForText(headerLabel->text());
    setLayoutDirection(dir);
    _q_updateLabelPosition();
    cursor.setBlockFormat(tbf);
}

void HeaderedTextEdit::_q_updateLabelPosition()
{
    if (layoutDirection() == Qt::RightToLeft) {
        QRectF geometry;
        QSizeF labelSize = headerLabel->sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
        geometry.setSize(labelSize);
        QSizeF textSize = sizeHint(Qt::PreferredSize, QSizeF(-1, -1));
        geometry.setX(textSize.width() - labelSize.width());
        headerLabel->setGeometry(geometry);
    }
}

void HeaderedTextEdit::_q_resetNewBlockMargin()
{
    // This method shouldn't be used if text block format has LeftMargin set.
    QTextBlockFormat tbf = textCursor().blockFormat();
    if (textCursor().blockNumber() == 0) {
        tbf.setTextIndent(headerLabel->size().width());
    } else {
        tbf.setTextIndent(0);
    }
    textCursor().setBlockFormat(tbf);
}
<|endoftext|>