<commit_before>/*
 * main.cpp
 *
 * Copyright (c) 2013, Thomas Buck <xythobuz@xythobuz.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "mbed.h"
#include "sensors.h"
#include "attitude.h"
#include "remote.h"
#include "altitude.h"
#include "errors.h"
#include "pid.h"
#include "motor.h"

#include <stdlib.h>

#define ERROR_ANIMATION_x 150 // IOOI <-> OIIO --> Used by Bootloader + Runtime
#define ERROR_ANIMATION_1 165 // IOIO <-> OIOI --> Gyro Init Error
#define ERROR_ANIMATION_2 135 // IOOO <-> OIII --> Acc Init Error
#define ERROR_ANIMATION_3 75  // OIOO <-> IOII --> Altitude Init Error
#define ERROR_ANIMATION_4 45  // OOIO <-> IIOI --> Attitude Handler Error
#define ERROR_ANIMATION_5 30  // OOOI <-> IIIO --> Too slow to keep up with calculations
#define ERROR_ANIMATION_6 240 // IIII <-> OOOO --> Ran out of Memory

const static int remoteChannels = 6;
const static float defaultP = 5.0;
const static float defaultI = 0.0015;
const static float defaultD = -13.0;
const static float defaultMin = -255.0;
const static float defaultMax = 255.0;
const static int attitudeFrequency = 100; // Attitude and Control Frequency in Hz
const static int remoteFrequency = 10; // Remote Read Frequency in Hz

int attitudeFlag = 0; // Attitude Execution Flag
int remoteFlag = 0;

int *remoteData = NULL;
int remoteError = 0;

DigitalOut statusLED[] = { DigitalOut(LED1), DigitalOut(LED2), DigitalOut(LED3), DigitalOut(LED4) };
Serial pc(USBTX, USBRX);
Ticker ticker;
I2C i2c(p28, p27);

Gyro gyro(&i2c);
Acc acc(&i2c);
Attitude attitude(&gyro, &acc, attitudeFrequency);
Altitude altitude(&i2c);
Remote remote(p6, remoteChannels);
PID rollPID(defaultP, defaultI, defaultD, defaultMin, defaultMax);
PID pitchPID(defaultP, defaultI, defaultD, defaultMin, defaultMax);
Motor motor(&i2c);

void display(uint8_t anim) {
    statusLED[0] = ((anim & 0x08) >> 3);
    statusLED[1] = ((anim & 0x04) >> 2);
    statusLED[2] = ((anim & 0x02) >> 1);
    statusLED[3] = (anim & 0x01);
}

void errorLoop(uint8_t anim) {
    while(1) {
        display(anim >> 4);
        wait(0.25);
        display(anim);
        wait(0.25);
    }
}

void attitudeHandler() {
    attitudeFlag++;
}

void remoteHandler() {
    remoteFlag++;
}

int main() {
    display(0x0F); // All LEDs on

    i2c.frequency(400 * 1000);
    pc.baud(38400);

    if (error_t error = gyro.init(Gyro::r2000DPS)) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_1);
    }

    if (error_t error = acc.init(Acc::r8G)) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_2);
    }

    if (error_t error = altitude.init()) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_3);
    }

    pc.printf("mbedCopter initialized!\n");
    ticker.attach_us(&attitudeHandler, (1000000 / attitudeFrequency));
    ticker.attach_us(&remoteHandler, (1000000 / remoteFrequency));
    display(0);

    while(1) {
        // Remote Control Reading
        if (remoteFlag > 0) {
            if (remoteFlag > 1) {
                pc.printf("!! Too slow for Remote (%d) !!\n", remoteFlag - 1);
                //errorLoop(ERROR_ANIMATION_5);
            }
            remoteFlag = 0;

            if (remoteData != NULL)
                free(remoteData);

            remoteError = 0;
            remoteData = remote.get();
            if (remoteData == NULL)
                errorLoop(ERROR_ANIMATION_6);
            for (int i = 0; i < remote.channels; i++) {
                if (remoteData[i] < remote.fail)
                    remoteError = 1;
            }
        }

        // Flight Control Code
        if (attitudeFlag > 0) {
            if (attitudeFlag > 1) {
                pc.printf("!! Too slow for Attitude (%d) !!\n", attitudeFlag - 1);
                //errorLoop(ERROR_ANIMATION_5);
            }
            attitudeFlag = 0;

            if (error_t error = attitude.calculate()) {
                pc.printf("%s\n", getErrorString(error));
                errorLoop(ERROR_ANIMATION_4);
            }

            // To-Do: Properly set target angles
            float rollDiff = rollPID.execute(0, attitude.roll);
            float pitchDiff = pitchPID.execute(0, attitude.pitch);
        }

        // UART Menu
        if(pc.readable()) {
            switch (pc.getc()) {
            case 'a':
                pc.printf("R %.2f\nP %.2f\nY %.2f\n", attitude.roll, attitude.pitch, attitude.yaw);
                break;

            case 'r':
                int *data;
                data = remote.get();
                if (data == NULL) {
                    pc.printf("Out of Memory!\n");
                    break;
                }
                for (int i = 0; i < remote.channels; i++) {
                    pc.printf("%d: %d --> ", i + 1, data[i]);
                    if (data[i] < remote.fail)
                        pc.printf("Fail!\n");
                    else
                        pc.printf("%d%%\n", (data[i] - remote.min) * 100 / (remote.max - remote.min));
                }
                free(data);
                break;

            case 'p':
                uint16_t temperature;
                int32_t pressure;
                altitude.read(&temperature, &pressure);
                pc.printf("Temp: %.1fC\n", temperature * 0.1f);
                pc.printf("Pres: %dPa\n", pressure);
                pc.printf("Alti: %.2fm\n", altitude.calculateAltitude(pressure));
                break;

            default:
                pc.printf("??\n");
                break;
            }
        }
    }

    return 0;
}
<commit_msg>First Flight Control code version finished<commit_after>/*
 * main.cpp
 *
 * Copyright (c) 2013, Thomas Buck <xythobuz@xythobuz.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "mbed.h"
#include "sensors.h"
#include "attitude.h"
#include "remote.h"
#include "altitude.h"
#include "errors.h"
#include "pid.h"
#include "motor.h"

#include <stdlib.h>

#define  MOTOR_PITCH_PLUS 0
#define MOTOR_PITCH_MINUS 2
#define   MOTOR_ROLL_PLUS 1
#define  MOTOR_ROLL_MINUS 3

#define    CHANNEL_SPEED 2
#define     CHANNEL_ROLL 0
#define    CHANNEL_PITCH 1
#define      CHANNEL_YAW 3
#define  CHANNEL_POTLEFT 5
#define CHANNEL_POTRIGHT 4

#define     STICK_POS_MIN -40
#define     STICK_POS_MAX 40
#define YAW_INFLUENCE_MIN -20
#define YAW_INFLUENCE_MAX 20

#define ERROR_ANIMATION_x 150 // IOOI <-> OIIO --> Used by Bootloader + Runtime
#define ERROR_ANIMATION_1 165 // IOIO <-> OIOI --> Gyro Init Error
#define ERROR_ANIMATION_2 135 // IOOO <-> OIII --> Acc Init Error
#define ERROR_ANIMATION_3 75  // OIOO <-> IOII --> Altitude Init Error
#define ERROR_ANIMATION_4 45  // OOIO <-> IIOI --> Attitude Handler Error
#define ERROR_ANIMATION_5 30  // OOOI <-> IIIO --> Too slow to keep up with calculations
#define ERROR_ANIMATION_6 240 // IIII <-> OOOO --> Ran out of Memory
#define ERROR_ANIMATION_7 195 // IIOO <-> OOII --> Motor Send Error

const static int remoteChannels = 6;
const static float defaultP = 0.0;
const static float defaultI = 0.0;
const static float defaultD = 0.0;
const static float defaultMin = -128.0;
const static float defaultMax = 128.0;
const static int attitudeFrequency = 100; // Attitude and Control Frequency in Hz
const static int remoteFrequency = 10; // Remote Read Frequency in Hz

int attitudeFlag = 0; // Attitude Execution Flag
int remoteFlag = 0;

int remoteError = 0;
int baseSpeed = 0;
int rollTarget = 0;
int pitchTarget = 0;
int yawTarget = 0;
int potLeft = 0;
int potRight = 0;

DigitalOut statusLED[] = { DigitalOut(LED1), DigitalOut(LED2), DigitalOut(LED3), DigitalOut(LED4) };
Serial pc(USBTX, USBRX);
Ticker ticker;
I2C i2c(p28, p27);

Gyro gyro(&i2c);
Acc acc(&i2c);
Attitude attitude(&gyro, &acc, attitudeFrequency);
Altitude altitude(&i2c);
Remote remote(p6, remoteChannels);
PID rollPID(defaultP, defaultI, defaultD, defaultMin, defaultMax);
PID pitchPID(defaultP, defaultI, defaultD, defaultMin, defaultMax);
Motor motor(&i2c);

template <typename T>
T map(T x, T in_min, T in_max, T out_min, T out_max) {
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void display(uint8_t anim) {
    statusLED[0] = ((anim & 0x08) >> 3);
    statusLED[1] = ((anim & 0x04) >> 2);
    statusLED[2] = ((anim & 0x02) >> 1);
    statusLED[3] = (anim & 0x01);
}

void errorLoop(uint8_t anim) {
    motor.set(4, 0);
    motor.send();
    while(1) {
        display(anim >> 4);
        wait(0.25);
        display(anim);
        wait(0.25);
    }
}

void attitudeHandler() {
    attitudeFlag++;
}

void remoteHandler() {
    remoteFlag++;
}

int main() {
    display(0x0F); // All LEDs on

    i2c.frequency(400 * 1000);
    pc.baud(38400);

    if (error_t error = gyro.init(Gyro::r2000DPS)) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_1);
    }

    if (error_t error = acc.init(Acc::r8G)) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_2);
    }

    if (error_t error = altitude.init()) {
        pc.printf("%s\n", getErrorString(error));
        errorLoop(ERROR_ANIMATION_3);
    }

    pc.printf("Init!\n");
    ticker.attach_us(&attitudeHandler, (1000000 / attitudeFrequency));
    ticker.attach_us(&remoteHandler, (1000000 / remoteFrequency));
    display(0);

    while(1) {
        // Remote Control Reading
        if (remoteFlag > 0) {
            if (remoteFlag > 1) {
                pc.printf("!! Too slow for Remote (%d) !!\n", remoteFlag - 1);
                //errorLoop(ERROR_ANIMATION_5);
            }
            remoteFlag = 0;
            remoteError = 0;
            int *remoteData = remote.get();
            if (remoteData == NULL) {
                pc.printf("No Memory!\n");
                errorLoop(ERROR_ANIMATION_6);
            }
            for (int i = 0; i < remote.channels; i++) {
                if (remoteData[i] < remote.fail)
                    remoteError = 1;
            }
            if (remoteError == 0) {
                // Convert Stick Positions - 1 Degree Resolution!
                baseSpeed = map<int>(remoteData[CHANNEL_SPEED], remote.min, remote.max, 0, 255);
                rollTarget = map<int>(remoteData[CHANNEL_ROLL], remote.min, remote.max, STICK_POS_MIN, STICK_POS_MAX);
                pitchTarget = map<int>(remoteData[CHANNEL_PITCH], remote.min, remote.max, STICK_POS_MIN, STICK_POS_MAX);
                yawTarget = map<int>(remoteData[CHANNEL_YAW], remote.min, remote.max, YAW_INFLUENCE_MIN, YAW_INFLUENCE_MAX);
                potLeft = map<int>(remoteData[CHANNEL_POTLEFT], remote.min, remote.max, 0, 255);
                potRight = map<int>(remoteData[CHANNEL_POTRIGHT], remote.min, remote.max, 0, 255);
            }
            free(remoteData);
        }

        // Flight Control Code
        if (attitudeFlag > 0) {
            if (attitudeFlag > 1) {
                pc.printf("!! Too slow for Attitude (%d) !!\n", attitudeFlag - 1);
                //errorLoop(ERROR_ANIMATION_5);
            }
            attitudeFlag = 0;

            if (error_t error = attitude.calculate()) {
                pc.printf("%s\n", getErrorString(error));
                errorLoop(ERROR_ANIMATION_4);
            }

            int rollDiff, pitchDiff;
            if (remoteError) {
                // Fail-Safe
                baseSpeed = 0;
                rollDiff = 0;
                pitchDiff = 0;
            } else {
                // Execute PID
                rollDiff = rollPID.execute(rollTarget, attitude.roll);
                pitchDiff = pitchPID.execute(pitchTarget, attitude.pitch);
            }

            // Mix it!
            motor.set(MOTOR_ROLL_PLUS, (baseSpeed + rollDiff) + (yawTarget / 2));
            motor.set(MOTOR_ROLL_MINUS, (baseSpeed - rollDiff) + (yawTarget / 2));
            motor.set(MOTOR_PITCH_PLUS, (baseSpeed + pitchDiff) - (yawTarget / 2));
            motor.set(MOTOR_PITCH_MINUS, (baseSpeed - pitchDiff) - (yawTarget / 2));
            if (error_t error = motor.send()) {
                pc.printf("%s\n", getErrorString(error));
                errorLoop(ERROR_ANIMATION_7);
            }
        }

        // UART Menu
        if(pc.readable()) {
            switch (pc.getc()) {
            case 'a':
                pc.printf("R %.2f\nP %.2f\nY %.2f\n", attitude.roll, attitude.pitch, attitude.yaw);
                break;

            case 'r':
                int *data;
                data = remote.get();
                if (data == NULL) {
                    pc.printf("No Memory!\n");
                    break;
                }
                for (int i = 0; i < remote.channels; i++) {
                    pc.printf("%d: %d --> ", i + 1, data[i]);
                    if (data[i] < remote.fail)
                        pc.printf("Fail!\n");
                    else
                        pc.printf("%d%%\n", (data[i] - remote.min) * 100 / (remote.max - remote.min));
                }
                free(data);
                break;

            case 'p':
                uint16_t temperature;
                int32_t pressure;
                altitude.read(&temperature, &pressure);
                pc.printf("Temp: %.1fC\n", temperature * 0.1f);
                pc.printf("Pres: %dPa\n", pressure);
                pc.printf("Alti: %.2fm\n", altitude.calculateAltitude(pressure));
                break;

            default:
                pc.printf("??\n");
                break;
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>a48e7738-4b02-11e5-874b-28cfe9171a43<commit_msg>Now it no longer crashes if X<commit_after>a49c5314-4b02-11e5-9ac0-28cfe9171a43<|endoftext|>


<commit_before>// Garry's Mod Lua Cache Extractor
// See LICENSE distributed with this file
// for licensing details.

#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	CommandLine::Set( argc, argv );

	BString strInFolder = CommandLine::GetArg( 0, Platform::CurrentDir() );
	BString strOutFolder = CommandLine::GetArg( 1, Platform::CurrentDir() );

	String::List listFiles;
	File::GetFilesInFolder(strInFolder, listFiles, false);

	Output::Msg( "Converting %i files.\n", listFiles.size() );

	BOOTIL_FOREACH_CONST(f, listFiles, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}<commit_msg>Cater for idiots.<commit_after>#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	CommandLine::Set( argc, argv );

	BString strInFolder = CommandLine::GetArg( 0, "" );
	BString strOutFolder = CommandLine::GetArg( 1, strInFolder );

	if (strInFolder == "")
		Output::Error("Usage: gmluaextract <in> [out]");

	String::List files;
	String::List folders;
	File::Find( &files, &folders, strInFolder + "/*.lua", false );

	Output::Msg( "Converting %i files.\n", files.size() );

	BOOTIL_FOREACH_CONST(f, files, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}
<|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();

int main(int argc, char *argv[]) {
    reusable_array_test();
    byte_array_test();
    multithread_test(4);
    range_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;
    }
};

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;
        for(auto i : bbb::range(2, 10)) {
            vec.push_back(i);
        }

        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;
        }
    }
    std::cout << std::endl;
    {
        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<const std::string> svec{"a", "hoge", "foo"};
        for (const 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;
        }
    }
}<commit_msg>update tests<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();
void enumerate_test();

int main(int argc, char *argv[]) {
    reusable_array_test();
    byte_array_test();
    multithread_test();
    enumerate_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;
    }
};

void multithread_test() {
    const std::size_t num = 4;
    std::size_t sum = 0;
    bool is_run = true;
    bbb::stop_watch watch;
    watch.start();
    bbb::multithread::manager manager(num, [&sum, &is_run](std::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 enumerate_test() {
    {
        std::vector<int> vec;
        for(auto i : bbb::range(2, 10)) {
            vec.push_back(i);
        }

        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;
        }
    }
    std::cout << std::endl;
    {
        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<const std::string> svec{"a", "hoge", "foo"};
//        for (const 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;
//        }
    }
}<|endoftext|>


<commit_before>021e809e-2748-11e6-bc58-e0f84713e7b8<commit_msg>more fixes<commit_after>0230487d-2748-11e6-926e-e0f84713e7b8<|endoftext|>


<commit_before>96a8fb8c-ad5b-11e7-b588-ac87a332f658<commit_msg>add file<commit_after>97157e19-ad5b-11e7-a5ee-ac87a332f658<|endoftext|>


<commit_before>#include "pin.H"

#include <sys/syscall.h>
#include <stdint.h>

#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <set>
#include <map>

#include "db.h"
#include "mysql.h"

/* ===================================================================== */
/* Names of malloc and free */
/* ===================================================================== */
#define STR_CALLOC "calloc"
#define STR_MALLOC "malloc"
#define STR_FREE "free"
#define STR_REALLOC "realloc"

VOID *range_start = NULL;
VOID *range_end = NULL;

std::map<void *, unsigned char> mem_queue;
MySQL *db;

bool sys_brk_called = false;

PIN_LOCK lock;

void flush_queue(THREADID tid)
{
    PIN_GetLock(&lock, tid+1);
    if (mem_queue.size() == 0) {
        PIN_ReleaseLock(&lock);
        return;
    }

    std::map<void*, unsigned char>::iterator it = mem_queue.begin();
    for (; it != mem_queue.end(); it++) {
        it->second = *(unsigned char*)it->first;
    }

    snapshot_t id = db->addSnapshot(snapshot_reason::MEM_WRITE);
    db->addMemoryWrites(id, mem_queue);

    mem_queue.clear();
    PIN_ReleaseLock(&lock);
}

VOID RecordMemWrite(VOID *ip, VOID *addr, ADDRINT size, THREADID tid)
{
    if (!range_start|| !range_end)
        return;

    if ((ADDRINT)addr < (ADDRINT)range_start ||
            (ADDRINT)addr > (ADDRINT)range_end)
        return;

    PIN_GetLock(&lock, tid+1);

    for (ADDRINT i=0; i<size; i++) {
        if (mem_queue.find((char*)addr+i) != mem_queue.end()) {
            PIN_ReleaseLock(&lock);
            flush_queue(tid);
            PIN_GetLock(&lock, tid+1);
        }

        mem_queue[((char*)addr+i)] = 0;
    }

    PIN_ReleaseLock(&lock);
}

VOID* WrapperMalloc(CONTEXT *ctxt, AFUNPTR pf_malloc, size_t size, THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_malloc, &param,
            PIN_PARG(void *), &res, PIN_PARG(size_t), size,
            PIN_PARG_END());

    PIN_GetLock(&lock, tid+1);
    snapshot_t id = db->addSnapshot(snapshot_reason::MALLOC);
    db->addReasonMalloc(id, res, size);
    PIN_ReleaseLock(&lock);

    flush_queue(tid);

    return res;
}

VOID WrapperFree(CONTEXT *ctxt, AFUNPTR pf_free, void *ptr, THREADID tid)
{
    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_free, &param, PIN_PARG(void),
            PIN_PARG(void *), ptr,
            PIN_PARG_END());

    PIN_GetLock(&lock, tid+1);
    snapshot_t id = db->addSnapshot(snapshot_reason::FREE);
    db->addReasonFree(id, ptr);
    PIN_ReleaseLock(&lock);

    flush_queue(tid);
}

VOID* WrapperCalloc(CONTEXT *ctxt, AFUNPTR pf_calloc, size_t nmemb, size_t size,
        THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_calloc, &param,
            PIN_PARG(void *), &res, PIN_PARG(size_t), nmemb,
            PIN_PARG(size_t), size,
            PIN_PARG_END());

    PIN_GetLock(&lock, tid+1);
    snapshot_t id = db->addSnapshot(snapshot_reason::CALLOC);
    db->addReasonCalloc(id, res, nmemb, size);
    PIN_ReleaseLock(&lock);

    flush_queue(tid);

    return res;
}

VOID* WrapperRealloc(CONTEXT *ctxt, AFUNPTR pf_realloc, void *ptr, size_t size,
        THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_realloc,
            &param, PIN_PARG(void *), &res,
            PIN_PARG(void *), ptr, PIN_PARG(size_t), size,
            PIN_PARG_END());

    PIN_GetLock(&lock, tid+1);
    snapshot_t id = db->addSnapshot(snapshot_reason::REALLOC);
    db->addReasonRealloc(id, ptr, res, size);
    PIN_ReleaseLock(&lock);

    flush_queue(tid);

    return res;
}

VOID SysBrk(ADDRINT arg0)
{
    sys_brk_called = true;
}

/* ===================================================================== */
/* Instrumentation routines                                              */
/* ===================================================================== */

VOID Instruction(INS ins, VOID *v)
{
    if (INS_IsMemoryWrite(ins)) {
        INS_InsertPredicatedCall(ins, IPOINT_BEFORE,
                (AFUNPTR) RecordMemWrite,
                IARG_INST_PTR, IARG_MEMORYWRITE_EA,
                IARG_MEMORYWRITE_SIZE,
                IARG_THREAD_ID,
                IARG_END);
    }
}

VOID ImageLoad(IMG img, VOID *v)
{
    // replace malloc singature
    RTN rtn_malloc = RTN_FindByName(img, STR_MALLOC);
    if (RTN_Valid(rtn_malloc)) {
        PROTO proto_malloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_MALLOC, PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_malloc, AFUNPTR(WrapperMalloc),
                IARG_PROTOTYPE, proto_malloc, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_THREAD_ID,
                IARG_END);
    }

    // replace free singature
    RTN rtn_free = RTN_FindByName(img, STR_FREE);
    if (RTN_Valid(rtn_free)) {
        PROTO proto_free = PROTO_Allocate(PIN_PARG(void),
                CALLINGSTD_DEFAULT, STR_FREE, PIN_PARG(void *),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_free, AFUNPTR(WrapperFree),
                IARG_PROTOTYPE, proto_free, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_THREAD_ID,
                IARG_END);
    }
    // replace calloc singature
    RTN rtn_calloc = RTN_FindByName(img, STR_CALLOC);
    if (RTN_Valid(rtn_calloc)) {
        PROTO proto_calloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_CALLOC, PIN_PARG(size_t),
                PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_calloc, AFUNPTR(WrapperCalloc),
                IARG_PROTOTYPE, proto_calloc, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
                IARG_THREAD_ID,
                IARG_END);
    }

    // replace realloc singature
    RTN rtn_realloc = RTN_FindByName(img, STR_REALLOC);
    if (RTN_Valid(rtn_realloc)) {
        PROTO proto_realloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_REALLOC, PIN_PARG(void *),
                PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_realloc, AFUNPTR(WrapperRealloc),
                IARG_PROTOTYPE, proto_realloc,
                IARG_CONTEXT, IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
                IARG_THREAD_ID,
                IARG_END);
    }
}

VOID SyscallEntry(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)
{
    PIN_GetLock(&lock, tid+1);
    if (PIN_GetSyscallNumber(ctxt, std) == SYS_brk)
        SysBrk(PIN_GetSyscallArgument(ctxt, std, 0));

    PIN_ReleaseLock(&lock);
}

VOID SyscallLeave(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)
{
    PIN_GetLock(&lock, tid+1);
    if (sys_brk_called) {
        if (!range_start)
            range_start = (VOID*)PIN_GetSyscallReturn(ctxt, std);

        range_end = (VOID*)PIN_GetSyscallReturn(ctxt, std);

        sys_brk_called = false;
    }

    PIN_ReleaseLock(&lock);
}

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

VOID Fini(INT32 code, VOID *v)
{
}

/* ===================================================================== */
/* Print Help Message                                                    */
/* ===================================================================== */

INT32 Usage()
{
    PIN_ERROR("This Pintool traces heap changes\n"
            + KNOB_BASE::StringKnobSummary() + "\n");
    return -1;
}

/* ===================================================================== */
/* Main                                                                  */
/* ===================================================================== */

int main(int argc, char *argv[])
{
    PIN_InitLock(&lock);

    // Initialize pin & symbol manager
    PIN_InitSymbols();
    if (PIN_Init(argc,argv)) {
        return Usage();
    }

    db = new MySQL("localhost", "root", "root", "ihv");

    IMG_AddInstrumentFunction(ImageLoad, 0);
    INS_AddInstrumentFunction(Instruction, 0);

    PIN_AddSyscallEntryFunction(SyscallEntry, 0);
    PIN_AddSyscallExitFunction(SyscallLeave, 0);

    PIN_AddFiniFunction(Fini, 0);

    // Never returns
    PIN_StartProgram();

    return 0;
}

/* ===================================================================== */
/* eof */
/* ===================================================================== */
<commit_msg>Fixed #4 by only logging when a valid heap range is set<commit_after>#include "pin.H"

#include <sys/syscall.h>
#include <stdint.h>

#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include <set>
#include <map>

#include "db.h"
#include "mysql.h"

/* ===================================================================== */
/* Names of malloc and free */
/* ===================================================================== */
#define STR_CALLOC "calloc"
#define STR_MALLOC "malloc"
#define STR_FREE "free"
#define STR_REALLOC "realloc"

VOID *range_start = NULL;
VOID *range_end = NULL;

std::map<void *, unsigned char> mem_queue;
MySQL *db;

bool sys_brk_called = false;

PIN_LOCK lock;

void flush_queue(THREADID tid)
{
    PIN_GetLock(&lock, tid+1);
    if (mem_queue.size() == 0) {
        PIN_ReleaseLock(&lock);
        return;
    }

    std::map<void*, unsigned char>::iterator it = mem_queue.begin();
    for (; it != mem_queue.end(); it++) {
        it->second = *(unsigned char*)it->first;
    }

    snapshot_t id = db->addSnapshot(snapshot_reason::MEM_WRITE);
    db->addMemoryWrites(id, mem_queue);

    mem_queue.clear();
    PIN_ReleaseLock(&lock);
}

VOID RecordMemWrite(VOID *ip, VOID *addr, ADDRINT size, THREADID tid)
{
    if (!range_start|| !range_end)
        return;

    if ((ADDRINT)addr < (ADDRINT)range_start ||
            (ADDRINT)addr > (ADDRINT)range_end)
        return;

    PIN_GetLock(&lock, tid+1);

    for (ADDRINT i=0; i<size; i++) {
        if (mem_queue.find((char*)addr+i) != mem_queue.end()) {
            PIN_ReleaseLock(&lock);
            flush_queue(tid);
            PIN_GetLock(&lock, tid+1);
        }

        mem_queue[((char*)addr+i)] = 0;
    }

    PIN_ReleaseLock(&lock);
}

VOID* WrapperMalloc(CONTEXT *ctxt, AFUNPTR pf_malloc, size_t size, THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_malloc, &param,
            PIN_PARG(void *), &res, PIN_PARG(size_t), size,
            PIN_PARG_END());

    if ((ADDRINT)range_end - (ADDRINT)range_start) {
        PIN_GetLock(&lock, tid+1);
        snapshot_t id = db->addSnapshot(snapshot_reason::MALLOC);
        db->addReasonMalloc(id, res, size);
        PIN_ReleaseLock(&lock);
    }

    flush_queue(tid);

    return res;
}

VOID WrapperFree(CONTEXT *ctxt, AFUNPTR pf_free, void *ptr, THREADID tid)
{
    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_free, &param, PIN_PARG(void),
            PIN_PARG(void *), ptr,
            PIN_PARG_END());

    if ((ADDRINT)range_end - (ADDRINT)range_start) {
        PIN_GetLock(&lock, tid+1);
        snapshot_t id = db->addSnapshot(snapshot_reason::FREE);
        db->addReasonFree(id, ptr);
        PIN_ReleaseLock(&lock);
    }

    flush_queue(tid);
}

VOID* WrapperCalloc(CONTEXT *ctxt, AFUNPTR pf_calloc, size_t nmemb, size_t size,
        THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_calloc, &param,
            PIN_PARG(void *), &res, PIN_PARG(size_t), nmemb,
            PIN_PARG(size_t), size,
            PIN_PARG_END());

    if ((ADDRINT)range_end - (ADDRINT)range_start) {
        PIN_GetLock(&lock, tid+1);
        snapshot_t id = db->addSnapshot(snapshot_reason::CALLOC);
        db->addReasonCalloc(id, res, nmemb, size);
        PIN_ReleaseLock(&lock);
    }

    flush_queue(tid);

    return res;
}

VOID* WrapperRealloc(CONTEXT *ctxt, AFUNPTR pf_realloc, void *ptr, size_t size,
        THREADID tid)
{
    void *res;

    CALL_APPLICATION_FUNCTION_PARAM param;
    memset((void*)&param, 0x00, sizeof(param));

    flush_queue(tid);

    PIN_CallApplicationFunction(ctxt, PIN_ThreadId(),
            CALLINGSTD_DEFAULT, pf_realloc,
            &param, PIN_PARG(void *), &res,
            PIN_PARG(void *), ptr, PIN_PARG(size_t), size,
            PIN_PARG_END());

    if ((ADDRINT)range_end - (ADDRINT)range_start) {
        PIN_GetLock(&lock, tid+1);
        snapshot_t id = db->addSnapshot(snapshot_reason::REALLOC);
        db->addReasonRealloc(id, ptr, res, size);
        PIN_ReleaseLock(&lock);
    }

    flush_queue(tid);

    return res;
}

VOID SysBrk(ADDRINT arg0)
{
    sys_brk_called = true;
}

/* ===================================================================== */
/* Instrumentation routines                                              */
/* ===================================================================== */

VOID Instruction(INS ins, VOID *v)
{
    if (INS_IsMemoryWrite(ins)) {
        INS_InsertPredicatedCall(ins, IPOINT_BEFORE,
                (AFUNPTR) RecordMemWrite,
                IARG_INST_PTR, IARG_MEMORYWRITE_EA,
                IARG_MEMORYWRITE_SIZE,
                IARG_THREAD_ID,
                IARG_END);
    }
}

VOID ImageLoad(IMG img, VOID *v)
{
    // replace malloc singature
    RTN rtn_malloc = RTN_FindByName(img, STR_MALLOC);
    if (RTN_Valid(rtn_malloc)) {
        PROTO proto_malloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_MALLOC, PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_malloc, AFUNPTR(WrapperMalloc),
                IARG_PROTOTYPE, proto_malloc, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_THREAD_ID,
                IARG_END);
    }

    // replace free singature
    RTN rtn_free = RTN_FindByName(img, STR_FREE);
    if (RTN_Valid(rtn_free)) {
        PROTO proto_free = PROTO_Allocate(PIN_PARG(void),
                CALLINGSTD_DEFAULT, STR_FREE, PIN_PARG(void *),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_free, AFUNPTR(WrapperFree),
                IARG_PROTOTYPE, proto_free, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_THREAD_ID,
                IARG_END);
    }
    // replace calloc singature
    RTN rtn_calloc = RTN_FindByName(img, STR_CALLOC);
    if (RTN_Valid(rtn_calloc)) {
        PROTO proto_calloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_CALLOC, PIN_PARG(size_t),
                PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_calloc, AFUNPTR(WrapperCalloc),
                IARG_PROTOTYPE, proto_calloc, IARG_CONTEXT,
                IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
                IARG_THREAD_ID,
                IARG_END);
    }

    // replace realloc singature
    RTN rtn_realloc = RTN_FindByName(img, STR_REALLOC);
    if (RTN_Valid(rtn_realloc)) {
        PROTO proto_realloc = PROTO_Allocate(PIN_PARG(void*),
                CALLINGSTD_DEFAULT, STR_REALLOC, PIN_PARG(void *),
                PIN_PARG(size_t),
                PIN_PARG_END());

        RTN_ReplaceSignature(rtn_realloc, AFUNPTR(WrapperRealloc),
                IARG_PROTOTYPE, proto_realloc,
                IARG_CONTEXT, IARG_ORIG_FUNCPTR,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
                IARG_THREAD_ID,
                IARG_END);
    }
}

VOID SyscallEntry(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)
{
    PIN_GetLock(&lock, tid+1);
    if (PIN_GetSyscallNumber(ctxt, std) == SYS_brk)
        SysBrk(PIN_GetSyscallArgument(ctxt, std, 0));

    PIN_ReleaseLock(&lock);
}

VOID SyscallLeave(THREADID tid, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)
{
    PIN_GetLock(&lock, tid+1);
    if (sys_brk_called) {
        if (!range_start)
            range_start = (VOID*)PIN_GetSyscallReturn(ctxt, std);

        range_end = (VOID*)PIN_GetSyscallReturn(ctxt, std);

        sys_brk_called = false;
    }

    PIN_ReleaseLock(&lock);
}

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

VOID Fini(INT32 code, VOID *v)
{
}

/* ===================================================================== */
/* Print Help Message                                                    */
/* ===================================================================== */

INT32 Usage()
{
    PIN_ERROR("This Pintool traces heap changes\n"
            + KNOB_BASE::StringKnobSummary() + "\n");
    return -1;
}

/* ===================================================================== */
/* Main                                                                  */
/* ===================================================================== */

int main(int argc, char *argv[])
{
    PIN_InitLock(&lock);

    // Initialize pin & symbol manager
    PIN_InitSymbols();
    if (PIN_Init(argc,argv)) {
        return Usage();
    }

    db = new MySQL("localhost", "root", "root", "ihv");

    IMG_AddInstrumentFunction(ImageLoad, 0);
    INS_AddInstrumentFunction(Instruction, 0);

    PIN_AddSyscallEntryFunction(SyscallEntry, 0);
    PIN_AddSyscallExitFunction(SyscallLeave, 0);

    PIN_AddFiniFunction(Fini, 0);

    // Never returns
    PIN_StartProgram();

    return 0;
}

/* ===================================================================== */
/* eof */
/* ===================================================================== */
<|endoftext|>


<commit_before>8d926b4a-4b02-11e5-896c-28cfe9171a43<commit_msg>Fixed that one bug<commit_after>8da023ab-4b02-11e5-90a6-28cfe9171a43<|endoftext|>


<commit_before>#include "uWS.h"

std::string buffer;

//#define USE_SSL

int main() {

    buffer = "Hello world!";

    //buffer.resize(512);

    //uWS::init();
    //uWS::Loop loop();

#ifdef USE_SSL
    uWS::SSLApp app(uWS::SSLOptions()
                  .keyFileName("/home/alexhultman/uWebSockets/misc/ssl/key.pem")
                  .certFileName("/home/alexhultman/uWebSockets/misc/ssl/cert.pem")
                  .passphrase("1234"));
#else
    uWS::App app;
#endif

    app.onGet("/", [](auto *s, auto *req, auto *args) {

        s->writeStatus("200 OK")->write([](int offset) {
            return std::string_view(buffer.data() + offset, buffer.length() - offset);
        }, buffer.length());

    }).onWebSocket("/wsApi", []() {

    }).listen("localhost", 3000, 0);

    uWS::run();
    // loop.run();
}
<commit_msg>Dynamically set response size from terminal<commit_after>#include "uWS.h"

std::string buffer;

//#define USE_SSL

int main(int argc, char **argv) {

    // dynamically set respinse size from arguments
    if (argc == 2) {
        int bytes = atoi(argv[1]);
        std::cout << "Server going to respond with " << bytes << " bytes of data" << std::endl;
        buffer.resize(bytes);
    } else {
        std::cout << "Usage: uWS_test bytesInResponse" << std::endl;
        return -1;
    }

    //uWS::init();
    //uWS::Loop loop();

#ifdef USE_SSL
    uWS::SSLApp app(uWS::SSLOptions()
                  .keyFileName("/home/alexhultman/uWebSockets/misc/ssl/key.pem")
                  .certFileName("/home/alexhultman/uWebSockets/misc/ssl/cert.pem")
                  .passphrase("1234"));
#else
    uWS::App app;
#endif

    app.onGet("/", [](auto *s, auto *req, auto *args) {

        s->writeStatus("200 OK")->write([](int offset) {
            return std::string_view(buffer.data() + offset, buffer.length() - offset);
        }, buffer.length());

    }).onWebSocket("/wsApi", []() {

    }).listen("localhost", 3000, 0);

    uWS::run();
    // loop.run();
}
<|endoftext|>


<commit_before>ad10975c-2747-11e6-8d4f-e0f84713e7b8<commit_msg>fix for the previous fix<commit_after>ad499497-2747-11e6-b70a-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdint>
#include <cstring>
#include <iostream>

typedef std::uint8_t  u8;
typedef std::uint16_t u16;
typedef std::uint32_t u32;
typedef std::uint64_t u64;

template <typename T> class fib_traits { };

template <> class fib_traits<u8>
{
  public:
    static const u8 fib_max   = 13;
    static const u8 prime     = 239;
    static const u8 sqrt5     = 31;
    static const u8 inv_sqrt5 = 54;
};

template <> class fib_traits<u16>
{
  public:
    static const u16 fib_max   = 24;
    static const u16 prime     = 46381;
    static const u16 sqrt5     = 22501;
    static const u16 inv_sqrt5 = 41605;
};

template <> class fib_traits<u32>
{
  public:
    static const u32 fib_max   = 47;
    static const u32 prime     = 2971215179;
    static const u32 sqrt5     = 492315461;
    static const u32 inv_sqrt5 = 692706128;
};

template <> class fib_traits<u64>
{
  public:
    static const u64 fib_max   = 93;
    static const u64 prime     = 12200160415121876909;
    static const u64 sqrt5     = 833731445503647576;
    static const u64 inv_sqrt5 = 2606778372125104897;
};

/* If your platform supports unsigned __int128, you can try this one as well.
template <> class fib_traits<u128>
{
  public:
    static const u128 fib_max   = 186;
    static const u128 prime     = 332825110087067562321196029789634457911;
    static const u128 sqrt5     = 10426323296737204245551694426008962215;
    static const u128 inv_sqrt5 = 2085264659347440849110338885201792443;
};
*/

template <typename T> T mulmod(T a, T b, T m)
{
  T r = 0;
  T s = 0;

  while (b > 0)
  {
    s = ((m - r) > a) ? r + a : r + a - m;
    r = (b & 1) * s + (1 - (b & 1)) * r;
    b >>= 1;
    a = ((m - a) > a) ? a + a : a + a - m;
  }

  return r;
}

template <typename T> T powmod(T a, T e, T m)
{
  T r = 1;

  while (e > 0)
  {
    r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r;
    e >>= 1;
    a = mulmod(a, a, m);
  }

  return r;
}

template <typename T> T fib(T n)
{
  const T prime = fib_traits<T>::prime;
  const T sqrt5 = fib_traits<T>::sqrt5;
  const T sqrt5inv = fib_traits<T>::inv_sqrt5;

  const T a = powmod<T>(1 + sqrt5, n, prime);
  const T b = powmod<T>(prime + 1 - sqrt5, n, prime);
  const T invpow2 = powmod<T>(2, prime - 1 - n, prime);

  const T phin_minus_psin = (a > b) ? a - b : (prime - b) + a;
  const T factor = mulmod(sqrt5inv, invpow2, prime);

  return mulmod(phin_minus_psin, factor, prime);
}

template <typename T> void bench()
{
  T acc[] = { 0, 0, 0, 0 };

  // The actual numbers are not very important here, just loop a lot,
  // so it takes a few seconds to complete.
  for (int j = 0; j < 4096 * 64 / (fib_traits<T>::fib_max + 1); j++)
  {
    for (T i = 0; i <= fib_traits<T>::fib_max; i++)
    {
      // The xor here is also not very important, it is only used to create
      // some data dependencies to avoid optimising it away. It is done on
      // four independent values so that data dependencies will not be the
      // bottleneck.
      acc[i % 4] ^= fib(i);
    }

    // This just creates some data dependencies between loops (because xor is
    // symmetric, so we have to use some operation that does not commute with
    // xor.)
    acc[0] |= acc[1] & acc[3];
    acc[2] |= acc[1] & acc[3];
  }

  std::cout << acc[0] + acc[1] + acc[2] + acc[3] << std::endl;
}

template <typename T> void print()
{
  for (T i = 0; i <= fib_traits<T>::fib_max; i++)
  {
    std::cout << fib(i) << std::endl;
  }
}

template <> void print<u8>()
{
  for (u8 i = 0; i <= fib_traits<u8>::fib_max; i++)
  {
    std::cout << static_cast<int>(fib<u8>(i)) << std::endl;
  }
}

int main(int argc, char** argv)
{
  if (argc > 2)
  {
    if (0 == strcmp(argv[1], "bench"))
    {
      if (0 == strcmp(argv[2], "8"))  bench<u8>();
      if (0 == strcmp(argv[2], "16")) bench<u16>();
      if (0 == strcmp(argv[2], "32")) bench<u32>();
      if (0 == strcmp(argv[2], "64")) bench<u64>();
    }

    if (0 == strcmp(argv[1], "print"))
    {
      if (0 == strcmp(argv[2], "8"))  print<u8>();
      if (0 == strcmp(argv[2], "16")) print<u16>();
      if (0 == strcmp(argv[2], "32")) print<u32>();
      if (0 == strcmp(argv[2], "64")) print<u64>();
    }
  }

  return 0;
}
<commit_msg>build benchmark timer into the program<commit_after>#include <cstdint>
#include <cstring>
#include <iostream>
#include <chrono>

typedef std::uint8_t  u8;
typedef std::uint16_t u16;
typedef std::uint32_t u32;
typedef std::uint64_t u64;

template <typename T> class fib_traits { };

template <> class fib_traits<u8>
{
  public:
    static const u8 fib_max   = 13;
    static const u8 prime     = 239;
    static const u8 sqrt5     = 31;
    static const u8 inv_sqrt5 = 54;
};

template <> class fib_traits<u16>
{
  public:
    static const u16 fib_max   = 24;
    static const u16 prime     = 46381;
    static const u16 sqrt5     = 22501;
    static const u16 inv_sqrt5 = 41605;
};

template <> class fib_traits<u32>
{
  public:
    static const u32 fib_max   = 47;
    static const u32 prime     = 2971215179;
    static const u32 sqrt5     = 492315461;
    static const u32 inv_sqrt5 = 692706128;
};

template <> class fib_traits<u64>
{
  public:
    static const u64 fib_max   = 93;
    static const u64 prime     = 12200160415121876909;
    static const u64 sqrt5     = 833731445503647576;
    static const u64 inv_sqrt5 = 2606778372125104897;
};

/* If your platform supports unsigned __int128, you can try this one as well.
template <> class fib_traits<u128>
{
  public:
    static const u128 fib_max   = 186;
    static const u128 prime     = 332825110087067562321196029789634457911;
    static const u128 sqrt5     = 10426323296737204245551694426008962215;
    static const u128 inv_sqrt5 = 2085264659347440849110338885201792443;
};
*/

template <typename T> T mulmod(T a, T b, T m)
{
  T r = 0;
  T s = 0;

  while (b > 0)
  {
    s = ((m - r) > a) ? r + a : r + a - m;
    r = (b & 1) * s + (1 - (b & 1)) * r;
    b >>= 1;
    a = ((m - a) > a) ? a + a : a + a - m;
  }

  return r;
}

template <typename T> T powmod(T a, T e, T m)
{
  T r = 1;

  while (e > 0)
  {
    r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r;
    e >>= 1;
    a = mulmod(a, a, m);
  }

  return r;
}

template <typename T> T fib(T n)
{
  const T prime = fib_traits<T>::prime;
  const T sqrt5 = fib_traits<T>::sqrt5;
  const T sqrt5inv = fib_traits<T>::inv_sqrt5;

  const T a = powmod<T>(1 + sqrt5, n, prime);
  const T b = powmod<T>(prime + 1 - sqrt5, n, prime);
  const T invpow2 = powmod<T>(2, prime - 1 - n, prime);

  const T phin_minus_psin = (a > b) ? a - b : (prime - b) + a;
  const T factor = mulmod(sqrt5inv, invpow2, prime);

  return mulmod(phin_minus_psin, factor, prime);
}

template <typename T> void bench()
{
  T acc[] = { 0, 0, 0, 0 };

  using std::chrono::high_resolution_clock;
  using std::chrono::duration_cast;
  using std::chrono::milliseconds;

  auto begin = high_resolution_clock::now();

  // The actual numbers are not very important here, just loop a lot,
  // so it takes a few seconds to complete.
  for (int j = 0; j < 4096 * 64 / (fib_traits<T>::fib_max + 1); j++)
  {
    for (T i = 0; i <= fib_traits<T>::fib_max; i++)
    {
      // The xor here is also not very important, it is only used to create
      // some data dependencies to avoid optimising it away. It is done on
      // four independent values so that data dependencies will not be the
      // bottleneck.
      acc[i % 4] ^= fib(i);
    }

    // This just creates some data dependencies between loops (because xor is
    // symmetric, so we have to use some operation that does not commute with
    // xor.)
    acc[0] |= acc[1] & acc[3];
    acc[2] |= acc[1] & acc[3];
  }

  auto end = high_resolution_clock::now();

  auto duration = duration_cast<milliseconds>(end - begin);
  std::cout << duration.count() << std::endl;

  std::cout << acc[0] + acc[1] + acc[2] + acc[3] << std::endl;
}

template <typename T> void print()
{
  for (T i = 0; i <= fib_traits<T>::fib_max; i++)
  {
    std::cout << fib(i) << std::endl;
  }
}

template <> void print<u8>()
{
  for (u8 i = 0; i <= fib_traits<u8>::fib_max; i++)
  {
    std::cout << static_cast<int>(fib<u8>(i)) << std::endl;
  }
}

int main(int argc, char** argv)
{
  if (argc > 2)
  {
    if (0 == strcmp(argv[1], "bench"))
    {
      if (0 == strcmp(argv[2], "8"))  bench<u8>();
      if (0 == strcmp(argv[2], "16")) bench<u16>();
      if (0 == strcmp(argv[2], "32")) bench<u32>();
      if (0 == strcmp(argv[2], "64")) bench<u64>();
    }

    if (0 == strcmp(argv[1], "print"))
    {
      if (0 == strcmp(argv[2], "8"))  print<u8>();
      if (0 == strcmp(argv[2], "16")) print<u16>();
      if (0 == strcmp(argv[2], "32")) print<u32>();
      if (0 == strcmp(argv[2], "64")) print<u64>();
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>d31d4c80-2747-11e6-8aa5-e0f84713e7b8<commit_msg>Bug fixes and performance improvements<commit_after>d332657a-2747-11e6-ba81-e0f84713e7b8<|endoftext|>


<commit_before>dabbf305-2747-11e6-b112-e0f84713e7b8<commit_msg>more fixes<commit_after>daca8bb5-2747-11e6-84ee-e0f84713e7b8<|endoftext|>


<commit_before>d5a41b23-4b02-11e5-b2a3-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>d5ad302b-4b02-11e5-ba21-28cfe9171a43<|endoftext|>


<commit_before>#include <FEHLCD.h>
#include <FEHIO.h>
#include <FEHUtility.h>

#include "global.h"
#include "robot.h"
#include "ui.h"

int main(void)
{
    G8::DefineConstants();
    using namespace G8;

    Robot * pRob = new Robot();

    LCD.Clear();

    char* pItems[] = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7",
                       "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13", "Item 14"};
    while(true)
    {
        size_t s = UI::MenuSelect("Test menu", pItems, 14);
        LCD.Clear();
        LCD.WriteLine((int)s);
        Sleep(3000);
    }

    delete pRob;

    return 0;
}

<commit_msg>Uses TASK menu at startup<commit_after>#include <FEHLCD.h>
#include <FEHIO.h>
#include <FEHUtility.h>

#include "robot.h"
#include "global.h"

int main(void)
{
    using namespace G8;

    LCD.Clear();

    DefineConstants();
    DefineTasks();

    Robot * pRob = new Robot();

    while(TASK.RunTaskFromMenu(pRob) != TASK_RESULT_FAIL);

    delete pRob;

    return 0;
}

<|endoftext|>


<commit_before>8350d64c-4b02-11e5-83ab-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>835f06c5-4b02-11e5-a956-28cfe9171a43<|endoftext|>


<commit_before>#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>
#include <typeinfo>

#include <unistd.h>

extern "C" {
#include <firmata.h>
}

using namespace cv;
using namespace std;

#define DIPIN 2 // Direction pin
#define ACPIN 3 // Activate pin
#define PNPIN 4 // Pne pin

#define KEY_ESC     27
#define KEY_P       116

#define WIDTH       800
#define HEIGHT      600
#define STOPAREA    40
#define CHECKROUNDS 3
#define TIME        200000

int main(int argc, char *argv[])
{
    int rounds_ac, rounds_di;
    int total_x, total_y;
    int average_x, average_y;

    int rounds = 0;
    int key = -1;
    bool pnstate = false;

    vector<Rect> faces;
    vector<Rect>::const_iterator i;

    CascadeClassifier cas;
    Mat src_img, gray_img, eq_img;

    t_firmata *firmata;

    // Check arguments
    if (argc < 2) {
        cout << "Please specify a cascade file." << endl;
        return 1;
    }

    // Load cascade file
    if  (!cas.load(string(argv[1]))) {
        cout << "Cannot read cascade file: " << argv[1] << endl;
        return 1;
    }
/*
    // Init Firmata
    firmata = firmata_new((char*)"/dev/ttyACM99");

    // Wait until device is up
    while(!firmata->isReady) {
        firmata_pull(firmata);
    }

    // Direction pin
    firmata_pinMode(firmata, DIPIN, MODE_OUTPUT);

    // Activate pin
    firmata_pinMode(firmata, ACPIN, MODE_OUTPUT);

    // Pneumatic cylinder pin
    firmata_pinMode(firmata, PNPIN, MODE_OUTPUT);
  */
    // Setup window
    namedWindow("track-tv", WINDOW_NORMAL);

    // Use 4 theads in OpenCV
    setNumThreads(4);
    // Use optimizations in OpenCV
    cvUseOptimized(1);

    // Open the default camera
    VideoCapture cam(0);
    if(!cam.isOpened()) {
        cout << "Cannot open cam!" << endl;
        return -1;
    }

    do
    {
        // Get key input
        key = waitKey(1);

        // Get a new frame from camera
        cam >> src_img;

        // Simplify image for cas analysis
        cvtColor(src_img, gray_img, CV_RGB2GRAY);
        equalizeHist(gray_img, eq_img);

        // Analyse image
        cas.detectMultiScale(eq_img, faces, 1.3, 5);

        // Reset total x & y values
        total_x  = 0;
        total_y  = 0;

        // Calc total x & y values for face positions and draw rect around faces.
        for (i = faces.begin(); i!= faces.end(); ++i) {
            total_x += i->x+i->width/2;
            total_y += i->y+i->height/2;
                rectangle(
                    src_img,
                    Point(i->x,i->y),
                    Point(i->x + i->width, i->y + i->height),
                    CV_RGB(255,0,0),
                    2);
            }

        // If any faces is found
        if (faces.size())
        {
            rounds++;

            // Calc average x & y value for faces
            average_x = total_x / faces.size();
            average_y = total_y / faces.size();

            if (average_x > WIDTH / 2 + STOPAREA)
            {
                rounds_ac++;
                rounds_di++;
            }
            else if (average_x < WIDTH / 2 - STOPAREA)
                rounds_ac++;
        }

        // If all rounds suggested to activate the motor
        if (rounds_ac == CHECKROUNDS)
        {
            //firmata_digitalWrite(firmata, ACPIN, HIGH);

            // If all rounds suggested to go right
            if (rounds_di == CHECKROUNDS)
            {
                //firmata_digitalWrite(firmata, DIPIN, HIGH);
                usleep(TIME);
                //firmata_digitalWrite(firmata, ACPIN, LOW);
                cout << "Go right" <<  endl;
            }
            // If all rounds suggested to go left
            else if (rounds_di == 0)
            {
                //firmata_digitalWrite(firmata, DIPIN, LOW);
                usleep(TIME);
                //firmata_digitalWrite(firmata, ACPIN, LOW);
                cout << "Go left" <<  endl;
            }
        }
        // If any rounds suggested to stop the motor
        else
        {
            //firmata_digitalWrite(firmata, ACPIN, LOW);
            cout << "Stay" <<  endl;
        }

        // Reset rounds if CHECKROUNDS is reached.
        if (rounds == CHECKROUNDS) {
            rounds_ac = 0;
            rounds_di = 0;

            rounds = 0;
        }

        // Show image
        imshow("track-tv", src_img);

        // Activate pneumatic cylinder
        if (key == KEY_P) {
            pnstate = !pnstate;
            //firmata_digitalWrite(firmata, PNPIN, pnstate);
        }
    }
    while (key != KEY_ESC);

    // Stop motor
    //firmata_digitalWrite(firmata, ACPIN, LOW);

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}
<commit_msg>track-tv: uncomment firmata calls<commit_after>#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>
#include <typeinfo>

#include <unistd.h>

extern "C" {
#include <firmata.h>
}

using namespace cv;
using namespace std;

#define DIPIN 2 // Direction pin
#define ACPIN 3 // Activate pin
#define PNPIN 4 // Pne pin

#define KEY_ESC     27
#define KEY_P       116

#define WIDTH       800
#define HEIGHT      600
#define STOPAREA    40
#define CHECKROUNDS 3
#define TIME        200000

int main(int argc, char *argv[])
{
    int rounds_ac, rounds_di;
    int total_x, total_y;
    int average_x, average_y;

    int rounds = 0;
    int key = -1;
    bool pnstate = false;

    vector<Rect> faces;
    vector<Rect>::const_iterator i;

    CascadeClassifier cas;
    Mat src_img, gray_img, eq_img;

    t_firmata *firmata;

    // Check arguments
    if (argc < 2) {
        cout << "Please specify a cascade file." << endl;
        return 1;
    }

    // Load cascade file
    if  (!cas.load(string(argv[1]))) {
        cout << "Cannot read cascade file: " << argv[1] << endl;
        return 1;
    }

    // Init Firmata
    firmata = firmata_new((char*)"/dev/ttyACM99");

    // Wait until device is up
    while(!firmata->isReady) {
        firmata_pull(firmata);
    }

    // Direction pin
    firmata_pinMode(firmata, DIPIN, MODE_OUTPUT);

    // Activate pin
    firmata_pinMode(firmata, ACPIN, MODE_OUTPUT);

    // Pneumatic cylinder pin
    firmata_pinMode(firmata, PNPIN, MODE_OUTPUT);

    // Setup window
    namedWindow("track-tv", WINDOW_NORMAL);

    // Use 4 theads in OpenCV
    setNumThreads(4);
    // Use optimizations in OpenCV
    cvUseOptimized(1);

    // Open the default camera
    VideoCapture cam(0);
    if(!cam.isOpened()) {
        cout << "Cannot open cam!" << endl;
        return -1;
    }

    do
    {
        // Get key input
        key = waitKey(1);

        // Get a new frame from camera
        cam >> src_img;

        // Simplify image for cas analysis
        cvtColor(src_img, gray_img, CV_RGB2GRAY);
        equalizeHist(gray_img, eq_img);

        // Analyse image
        cas.detectMultiScale(eq_img, faces, 1.3, 5);

        // Reset total x & y values
        total_x  = 0;
        total_y  = 0;

        // Calc total x & y values for face positions and draw rect around faces.
        for (i = faces.begin(); i!= faces.end(); ++i) {
            total_x += i->x+i->width/2;
            total_y += i->y+i->height/2;
                rectangle(
                    src_img,
                    Point(i->x,i->y),
                    Point(i->x + i->width, i->y + i->height),
                    CV_RGB(255,0,0),
                    2);
            }

        // If any faces is found
        if (faces.size())
        {
            rounds++;

            // Calc average x & y value for faces
            average_x = total_x / faces.size();
            average_y = total_y / faces.size();

            if (average_x > WIDTH / 2 + STOPAREA)
            {
                rounds_ac++;
                rounds_di++;
            }
            else if (average_x < WIDTH / 2 - STOPAREA)
                rounds_ac++;
        }

        // If all rounds suggested to activate the motor
        if (rounds_ac == CHECKROUNDS)
        {
            firmata_digitalWrite(firmata, ACPIN, HIGH);

            // If all rounds suggested to go right
            if (rounds_di == CHECKROUNDS)
            {
                firmata_digitalWrite(firmata, DIPIN, HIGH);
                usleep(TIME);
                firmata_digitalWrite(firmata, ACPIN, LOW);
                cout << "Go right" <<  endl;
            }
            // If all rounds suggested to go left
            else if (rounds_di == 0)
            {
                firmata_digitalWrite(firmata, DIPIN, LOW);
                usleep(TIME);
                firmata_digitalWrite(firmata, ACPIN, LOW);
                cout << "Go left" <<  endl;
            }
        }
        // If any rounds suggested to stop the motor
        else
        {
            firmata_digitalWrite(firmata, ACPIN, LOW);
            cout << "Stay" <<  endl;
        }

        // Reset rounds if CHECKROUNDS is reached.
        if (rounds == CHECKROUNDS) {
            rounds_ac = 0;
            rounds_di = 0;

            rounds = 0;
        }

        // Show image
        imshow("track-tv", src_img);

        // Activate pneumatic cylinder
        if (key == KEY_P) {
            pnstate = !pnstate;
            firmata_digitalWrite(firmata, PNPIN, pnstate);
        }
    }
    while (key != KEY_ESC);

    // Stop motor
    firmata_digitalWrite(firmata, ACPIN, LOW);

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

struct Room {
	Room(RoomID idnum, string i_description) : ID(idnum) {
		description = i_description;
	}
	virtual string describe() {
    stringstream ss;
    ss << description << "\n";
    ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
    ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
    ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
		return ss.str();
	}
  const RoomID ID; //unique id of the room
	string description; //general description of the room for the player
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>made Player location aware<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

struct Room {
	Room(RoomID idnum, string i_description) : ID(idnum) {
		description = i_description;
	}
	virtual string describe() {
    stringstream ss;
    ss << description << "\n";
    ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
    ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
    ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
		return ss.str();
	}
  const RoomID ID; //unique id of the room
	string description; //general description of the room for the player
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>c40b3e07-2747-11e6-a9c4-e0f84713e7b8<commit_msg>The previous fix has been fixed<commit_after>c42d53dc-2747-11e6-b4b4-e0f84713e7b8<|endoftext|>


<commit_before>cbd4e29e-2747-11e6-91e0-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>cbf2350f-2747-11e6-b4da-e0f84713e7b8<|endoftext|>


<commit_before>83692930-2749-11e6-a874-e0f84713e7b8<commit_msg>compiles now<commit_after>8374e523-2749-11e6-adbf-e0f84713e7b8<|endoftext|>