<commit_before>/*
    This file is part of WARG's computer-vision

    Copyright (c) 2015, Waterloo Aerial Robotics Group (WARG)
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. 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.
    3. Usage of this code MUST be explicitly referenced to WARG and this code
       cannot be used in any competition against WARG.
    4. Neither the name of the WARG nor the names of its contributors may be used
       to endorse or promote products derived from this software without specific
       prior written permission.

    THIS SOFTWARE IS PROVIDED BY WARG ''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 WARG 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 <boost/lexical_cast.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/program_options.hpp>
#include <queue>
#include <iostream>
#include <fstream>
#include "frame.h"
#include "target_identifier.h"
#include "imgimport.h"
#include "vidimport.h"
#include "pictureimport.h"
#include "target.h"

using namespace std;
using namespace boost;
using namespace cv;
namespace logging = boost::log;
namespace po = boost::program_options;

const int BUFFER_SIZE = 20;

Frame* next_image();
int handle_args(int argc, char** argv);
queue<Frame*> in_buffer;
queue<Target*> out_buffer;
queue<Frame*> intermediate_buffer;

boost::asio::io_service ioService;
boost::thread_group threadpool;

vector<string> file_names;
int workers = 0;
bool hasMoreFrames = true;
string outputDir = "./";
bool intermediate = false;

// Processing module classes
ImageImport * importer = NULL;
TargetIdentifier identifier;

void worker(Frame* f) {
    workers++;
    assert(!f->get_img().empty());
    identifier.process_frame(f);
    if (intermediate && f->get_objects().size() > 0) {
        intermediate_buffer.push(f);
    }

    workers--;
}

void read_images() {
    Frame* currentFrame;
    while (hasMoreFrames) {
        if (in_buffer.size() < BUFFER_SIZE) {
            Frame* f = importer->next_frame();
            if (f) {
                in_buffer.push(f);
            }
            else {
                hasMoreFrames = false;
            }
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(30));
    }
}

void assign_workers() {
    Frame* current;
    while (hasMoreFrames || in_buffer.size() > 0) {
        if (in_buffer.size() > 0) {
            current = in_buffer.front();
            // spawn worker to process image;
            BOOST_LOG_TRIVIAL(trace) << "Spawning worker...";
            ioService.post(boost::bind(worker, current));
            in_buffer.pop();
        }

        boost::this_thread::sleep(boost::posix_time::milliseconds(30));
    }
}

void output() {
    filebuf fb;
    while (hasMoreFrames || out_buffer.size() > 0 || intermediate_buffer.size() > 0 || workers > 0) {
        if (out_buffer.size() > 0) {
            fb.open("out.txt", ios::app);
            ostream out(&fb);

            out << out_buffer.front();
            // Output
            out_buffer.pop();
            fb.close();
        }
        if (intermediate_buffer.size() > 0) {
            Frame * f = intermediate_buffer.front();
            f->save(outputDir);
            intermediate_buffer.pop();
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(30));
    }
    ioService.stop();
}

void init() {
#ifdef RELEASE
    logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
#else
    logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug);
#endif
}

int main(int argc, char** argv) {
    init();
    int retArg;
    if (retArg = handle_args(argc, argv) != 0)
        return retArg;

    int processors = boost::thread::hardware_concurrency();

    ioService.post(boost::bind(read_images));
    ioService.post(boost::bind(assign_workers));
    ioService.post(boost::bind(output));

    boost::asio::io_service::work work(ioService);
    for (int i = 0; i < processors; i++) {
        threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
    }
    threadpool.join_all();
    return 0;
}

int handle_args(int argc, char** argv) {
    try {
        po::options_description description("Usage: warg-cv [OPTION]");

        description.add_options()("help,h", "Display this help message")
            ("images,i", po::value<string>(), "Directory containing image files to be processed")
            ("video,v", po::value<int>(), "Video device to capture images from")
#ifdef HAS_DECKLINK
            ("decklink,d", "Use this option to capture video from a connected Decklink card")
#endif // HAS_DECKLINK
            ("telemetry,t", po::value<string>(), "Path of the telemetry log for the given image source")
            ("output,o", po::value<string>(), "Directory to store output files; default is current directory")
            ("intermediate", "When this is enabled, program will output intermediary frames that contain objects of interest");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, description), vm);
        po::notify(vm);

        if (vm.count("help") || vm.size() == 0) {
            cout << description << endl;
            return 1;
        }
        int devices = vm.count("video") + vm.count("decklink") + vm.count("images");
        if (devices > 1) {
            cout << "Invalid options: You can only specify one image source at a time" << endl;
            return 1;
        } else if(devices == 0) {
            cout << "Error: You must specify an image source!" << endl;
            return 1;
        }
        if (!vm.count("telemetry")) {
            cout << "Invalid options; You must specify a telemetry file" << endl;
            return 1;
        }
        string telemetry = vm["telemetry"].as<string>();

#ifdef HAS_DECKLINK
        if (vm.count("decklink")) {
            importer = new VideoImport();
        }
#endif // HAS_DECKLINK

        if (vm.count("images")) {
            string path = vm["images"].as<string>();
            importer = new PictureImport(telemetry, path);
        }

        if (vm.count("output")) {
            outputDir = vm["output"].as<string>();
        }

        if (vm.count("intermediate")) {
            intermediate = true;
        }
    }
    catch (std::exception& e) {
        cout << e.what() << endl;
        return 1;
    }

    return 0;
}
<commit_msg>Made warg-cv stagger reading images based on average time used to process each frame<commit_after>/*
    This file is part of WARG's computer-vision

    Copyright (c) 2015, Waterloo Aerial Robotics Group (WARG)
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. 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.
    3. Usage of this code MUST be explicitly referenced to WARG and this code
       cannot be used in any competition against WARG.
    4. Neither the name of the WARG nor the names of its contributors may be used
       to endorse or promote products derived from this software without specific
       prior written permission.

    THIS SOFTWARE IS PROVIDED BY WARG ''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 WARG 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 <boost/lexical_cast.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/program_options.hpp>
#include <queue>
#include <chrono>
#include <iostream>
#include <fstream>
#include "frame.h"
#include "target_identifier.h"
#include "imgimport.h"
#include "vidimport.h"
#include "pictureimport.h"
#include "target.h"

using namespace std;
using namespace boost;
using namespace cv;
namespace logging = boost::log;
namespace po = boost::program_options;

const int BUFFER_SIZE = 20;

Frame* next_image();
int handle_args(int argc, char** argv);
queue<Frame*> in_buffer;
queue<Target*> out_buffer;
queue<Frame*> intermediate_buffer;

boost::asio::io_service ioService;
boost::thread_group threadpool;

vector<string> file_names;
int workers = 0;
bool hasMoreFrames = true;
string outputDir = "./";
bool intermediate = false;
int processors;

// Processing module classes
ImageImport * importer = NULL;
TargetIdentifier identifier;
double aveFrameTime = 1000;
int frameCount = 0;

void worker(Frame* f) {
    auto start = std::chrono::steady_clock::now();
    workers++;
    assert(!f->get_img().empty());
    identifier.process_frame(f);
    if (intermediate && f->get_objects().size() > 0) {
        intermediate_buffer.push(f);
    }

    workers--;
    auto end = std::chrono::steady_clock::now();
    auto diff = end - start;
    aveFrameTime = (std::chrono::duration <double, std::milli>(diff).count() + aveFrameTime*frameCount)/++frameCount;
}

void read_images() {
    Frame* currentFrame;
    while (hasMoreFrames) {
        if (in_buffer.size() < BUFFER_SIZE) {
            Frame* f = importer->next_frame();
            if (f) {
                in_buffer.push(f);
            }
            else {
                hasMoreFrames = false;
            }
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(aveFrameTime/processors));
    }
}

void assign_workers() {
    Frame* current;
    while (hasMoreFrames || in_buffer.size() > 0) {
        if (in_buffer.size() > 0) {
            current = in_buffer.front();
            // spawn worker to process image;
            BOOST_LOG_TRIVIAL(trace) << "Spawning worker...";
            ioService.post(boost::bind(worker, current));
            in_buffer.pop();
        }

        boost::this_thread::sleep(boost::posix_time::milliseconds(30));
    }
}

void output() {
    filebuf fb;
    while (hasMoreFrames || out_buffer.size() > 0 || intermediate_buffer.size() > 0 || workers > 0) {
        if (out_buffer.size() > 0) {
            fb.open("out.txt", ios::app);
            ostream out(&fb);

            out << out_buffer.front();
            // Output
            out_buffer.pop();
            fb.close();
        }
        if (intermediate_buffer.size() > 0) {
            Frame * f = intermediate_buffer.front();
            f->save(outputDir);
            intermediate_buffer.pop();
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(30));
    }
    ioService.stop();
}

void init() {
#ifdef RELEASE
    logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
#else
    logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug);
#endif
}

int main(int argc, char** argv) {
    init();
    int retArg;
    if (retArg = handle_args(argc, argv) != 0)
        return retArg;

    processors = boost::thread::hardware_concurrency();

    ioService.post(boost::bind(read_images));
    ioService.post(boost::bind(assign_workers));
    ioService.post(boost::bind(output));

    boost::asio::io_service::work work(ioService);
    for (int i = 0; i < processors; i++) {
        threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
    }
    threadpool.join_all();
    return 0;
}

int handle_args(int argc, char** argv) {
    try {
        po::options_description description("Usage: warg-cv [OPTION]");

        description.add_options()("help,h", "Display this help message")
            ("images,i", po::value<string>(), "Directory containing image files to be processed")
            ("video,v", po::value<int>(), "Video device to capture images from")
#ifdef HAS_DECKLINK
            ("decklink,d", "Use this option to capture video from a connected Decklink card")
#endif // HAS_DECKLINK
            ("telemetry,t", po::value<string>(), "Path of the telemetry log for the given image source")
            ("output,o", po::value<string>(), "Directory to store output files; default is current directory")
            ("intermediate", "When this is enabled, program will output intermediary frames that contain objects of interest");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, description), vm);
        po::notify(vm);

        if (vm.count("help") || vm.size() == 0) {
            cout << description << endl;
            return 1;
        }
        int devices = vm.count("video") + vm.count("decklink") + vm.count("images");
        if (devices > 1) {
            cout << "Invalid options: You can only specify one image source at a time" << endl;
            return 1;
        } else if(devices == 0) {
            cout << "Error: You must specify an image source!" << endl;
            return 1;
        }
        if (!vm.count("telemetry")) {
            cout << "Invalid options; You must specify a telemetry file" << endl;
            return 1;
        }
        string telemetry = vm["telemetry"].as<string>();

#ifdef HAS_DECKLINK
        if (vm.count("decklink")) {
            importer = new VideoImport();
        }
#endif // HAS_DECKLINK

        if (vm.count("images")) {
            string path = vm["images"].as<string>();
            importer = new PictureImport(telemetry, path);
        }

        if (vm.count("output")) {
            outputDir = vm["output"].as<string>();
        }

        if (vm.count("intermediate")) {
            intermediate = true;
        }
    }
    catch (std::exception& e) {
        cout << e.what() << endl;
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>

using namespace std;

/*
 * The function returns directories found in directory.
 * First parameter is path where you want to find directories.
 * You can also use double slashes like this ...../dir/dir//dir. Not recomanded!
 */
vector<string> getDirs(string dirPath)
{
    // Converting path to const char* because the function opendir is programmed in c
    // and c methods parameters accepts only const char* so I must convert it.
    const char* DIR_PATH = dirPath.c_str();

    // Declaration of dynamic array that contains found directories by path.
    vector<string> directories;

    // Call a function to try to open the dir by path.
    // If it doesnt exists the function will return segmentation error.
    DIR *dir = opendir(DIR_PATH);

    // Then try to read the dir
    struct dirent *entry = readdir(dir);

    // While dir has a directory.
    while (entry != NULL)
    {
        // If type of stream is directory.
        if (entry->d_type == DT_DIR) {
            // If the "directory" name is not ".." or ".".
            if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {

            } else {
                // push the actual dir path PLUS actual directory to the dynamic array.
                directories.push_back(dirPath + "/" + entry->d_name);
            }
        }

        entry = readdir(dir);
    }

    // Close the dir.
    closedir(dir);

    return directories;
}

int main(void)
{
    // A root path where you want to start searching.
    string searchedDir = "/home/simon/Plocha/Simon";

    stack<string> actDir;

    actDir.push(searchedDir);

    string actSearchedDir;

    vector<string> dirFound;

    int dirCount = 0;

    while(actDir.size() > 0) {
        actSearchedDir = actDir.top();actDir.pop();

        cout << actSearchedDir << endl;

        dirFound = getDirs(actSearchedDir.c_str());

        for(unsigned i = 0; i < dirFound.size(); i++) {
            if(!dirFound.empty()) {
                actDir.push(dirFound.at(i));
            } else {
                break;
            }
        }
        dirCount++;
    }

    cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";

    return 0;
}
<commit_msg>Hledani souboru vyvojova verze<commit_after>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

using namespace std;

/*
 * The function returns directories found in directory.
 * First parameter is path where you want to find directories.
 * You can also use double slashes like this ...../dir/dir//dir. Not reomanded!
 */
vector<string> getDirs(string dirPath)
{
    // Converting path to const char* because the function opendir is programmed in c
    // and c methods parameters accepts only const char* so I must convert it.
    const char* DIR_PATH = dirPath.c_str();

    // Declaration of dynamic array that contains found directories by path.
    vector<string> directories;

    // Call a function to try to open the dir by path.
    // If it doesnt exists the function will return segmentation error.
    DIR *dir = opendir(DIR_PATH);

    // Then try to read the dir
    struct dirent *entry = readdir(dir);

    // While dir has a directory.
    while (entry != NULL)
    {
        // If type of stream is directory.
        if (entry->d_type == DT_DIR) {
            // If the "directory" name is not ".." or ".".
            if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {

            } else {
                // push the actual dir path PLUS actual directory to the dynamic array.
                directories.push_back(dirPath + "/" + entry->d_name);
            }
        }

        entry = readdir(dir);
    }

    // Close the dir.
    closedir(dir);

    return directories;
}

vector<string> getFiles(string dirPath)
{
    // Converting path to const char* because the function opendir is programmed in c
    // and c methods parameters accepts only const char* so I must convert it.
    const char* DIR_PATH = dirPath.c_str();

    // Declaration of dynamic array that contains found directories by path.
    vector<string> files;

    // Call a function to try to open the dir by path.
    // If it doesnt exists the function will return segmentation error.
    DIR *dir = opendir(DIR_PATH);

    // Then try to read the dir
    struct dirent *entry = readdir(dir);

    // While dir has a directory.
    while (entry != NULL)
    {
        // If type of stream is directory.
        if (entry->d_type != DT_DIR) {
                // If the "directory" name is not ".." or ".".
                if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {

                } else {
                    // push the actual dir path PLUS actual directory to the dynamic array.
                    files.push_back(entry->d_name);
                }
        }

        entry = readdir(dir);
    }

    // Close the dir.
    closedir(dir);

    return files;
}

int main(void)
{
    // A root path where you want to start searching.
    // User will specify (UWS).
    string searchedDir = "/home/simon/Plocha/Simon/Data/Pokus";

    // UWS
    string searchedFile = "VEPR.TXT";

    stack<string> actDir;

    actDir.push(searchedDir);

    string actSearchedDir;

    vector<string> dirFound;
    vector<string> fileFound;

    int dirCount = 0;

    while(actDir.size() > 0) {
        actSearchedDir = actDir.top();actDir.pop();

        cout << actSearchedDir << endl;

        dirFound = getDirs(actSearchedDir.c_str());
        fileFound = getFiles(actSearchedDir.c_str());

        for(unsigned j = 0; j < fileFound.size(); j++) {
            cout << "Soubor: " << fileFound.at(j) << endl;
            cout << "POROVNAVAM: " << fileFound.at(j) << " a " << searchedFile << endl;
            if(fileFound.at(j) == searchedFile) {
                cout << "Soubor nalezen ve slozce " << actSearchedDir << "." << endl;
                cout << "Soubor se tedy nachází v" << actSearchedDir << "/" << searchedFile << endl;
                return 0;
            }
        }

        for(unsigned i = 0; i < dirFound.size(); i++) {
            if(!dirFound.empty()) {
                actDir.push(dirFound.at(i));
            } else {
                break;
            }
        }
        dirCount++;
    }

    cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";

    return 0;
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "multiboot.h"

#include "gdt.h"
#include "idt.h"
#include "irq.h"
#include "keyboard.h"
#include "screen.h"
#include "timer.h"

/**
 * @brief Debugging function to print Multiboot info
 * @param mbootInfo pointer to Multiboot info struct
 */
void printMultibootInfo(const multiboot_info* mbootInfo);

/**
 * @brief 32-bit x86 kernel main
 */
extern "C"
void kernelMain(const uint32_t MULTIBOOT_MAGIC_NUM, const multiboot_info* mbootInfo)
{
    screen.init();
    screen.setBackgroundColor(os::Screen::EColor::eBlack);
    screen.setForegroundColor(os::Screen::EColor::eLightGreen);
    screen.clear();

    // ensure we were booted by a Multiboot-compliant boot loader
    if (MULTIBOOT_MAGIC_NUM != MULTIBOOT_BOOTLOADER_MAGIC)
    {
        screen << "Invalid Multiboot magic number: "
               << os::Screen::hex << MULTIBOOT_MAGIC_NUM
               << '\n';
        return;
    }

    initGdt();
    initIdt();
    initIrq();

    os::Timer::init(18);

    os::Keyboard::init();

    // enable interrupts
    asm volatile ("sti");

    screen.write("Sandbox OS\n");

    printMultibootInfo(mbootInfo);

    while (true)
    {
        os::Keyboard::processQueue();

        // halt CPU until an interrupt occurs
        asm volatile ("hlt");
    }
}

void printMultibootInfo(const multiboot_info* mbootInfo)
{
    screen << "Multiboot info:\n";

    // print flags
    screen << os::Screen::bin
           << "Flags: " << mbootInfo->flags << '\n'
           << os::Screen::dec;

    uint32_t bit = 1;
    for (int i = 0; i < 32; ++i)
    {
        bool isSet = (mbootInfo->flags & bit);
        if (isSet)
        {
            screen << "Bit " << i << ": ";
            switch (bit)
            {
            case MULTIBOOT_INFO_MEMORY:
                screen << mbootInfo->mem_lower << " KB, " << mbootInfo->mem_upper << " KB\n";
                break;

            case MULTIBOOT_INFO_BOOTDEV:
                screen << os::Screen::hex
                       << mbootInfo->boot_device << '\n'
                       << os::Screen::dec;
                break;

            case MULTIBOOT_INFO_CMDLINE:
                screen << reinterpret_cast<const char*>(mbootInfo->cmdline) << '\n';
                break;

            case MULTIBOOT_INFO_MODS:
                screen << mbootInfo->mods_count << " boot module" << (mbootInfo->mods_count == 1 ? "" : "s") << " were loaded\n";
                break;

            case MULTIBOOT_INFO_AOUT_SYMS:
                screen << "AOUT\n";
                break;

            case MULTIBOOT_INFO_ELF_SHDR:
                screen << "ELF\n";
                break;

            case MULTIBOOT_INFO_DRIVE_INFO:
                screen << mbootInfo->drives_length << '\n';
                break;

            case MULTIBOOT_INFO_CONFIG_TABLE:
                screen << os::Screen::hex
                       << mbootInfo->config_table << '\n'
                       << os::Screen::dec;
                break;

            case MULTIBOOT_INFO_MEM_MAP:
                screen << mbootInfo->mmap_length << '\n';
                break;

            case MULTIBOOT_INFO_BOOT_LOADER_NAME:
                screen << reinterpret_cast<const char*>(mbootInfo->boot_loader_name) << '\n';
                break;

            default:
                screen << '\n';
                break;
            }
        }

        bit <<= 1;
    }
}
<commit_msg>Printing mem map<commit_after>#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "multiboot.h"

#include "gdt.h"
#include "idt.h"
#include "irq.h"
#include "keyboard.h"
#include "screen.h"
#include "timer.h"

/**
 * @brief Debugging function to print Multiboot info
 * @param mbootInfo pointer to Multiboot info struct
 */
void printMultibootInfo(const multiboot_info* mbootInfo);

void printMemMap(uint32_t addr, uint32_t len);

/**
 * @brief 32-bit x86 kernel main
 */
extern "C"
void kernelMain(const uint32_t MULTIBOOT_MAGIC_NUM, const multiboot_info* mbootInfo)
{
    screen.init();
    screen.setBackgroundColor(os::Screen::EColor::eBlack);
    screen.setForegroundColor(os::Screen::EColor::eLightGreen);
    screen.clear();

    // ensure we were booted by a Multiboot-compliant boot loader
    if (MULTIBOOT_MAGIC_NUM != MULTIBOOT_BOOTLOADER_MAGIC)
    {
        screen << "Invalid Multiboot magic number: "
               << os::Screen::hex << MULTIBOOT_MAGIC_NUM
               << '\n';
        return;
    }

    initGdt();
    initIdt();
    initIrq();

    os::Timer::init(18);

    os::Keyboard::init();

    // enable interrupts
    asm volatile ("sti");

    screen.write("Sandbox OS\n");

    printMultibootInfo(mbootInfo);
    printMemMap(mbootInfo->mmap_addr, mbootInfo->mmap_length);

    while (true)
    {
        os::Keyboard::processQueue();

        // halt CPU until an interrupt occurs
        asm volatile ("hlt");
    }
}

void printMultibootInfo(const multiboot_info* mbootInfo)
{
    screen << "Multiboot info:\n";

    // print flags
    screen << os::Screen::bin
           << "Flags: " << mbootInfo->flags << '\n'
           << os::Screen::dec;

    uint32_t bit = 1;
    for (int i = 0; i < 32; ++i)
    {
        bool isSet = (mbootInfo->flags & bit);
        if (isSet)
        {
            screen << "Bit " << i << ": ";
            switch (bit)
            {
            case MULTIBOOT_INFO_MEMORY:
                screen << mbootInfo->mem_lower << " KB, " << mbootInfo->mem_upper << " KB\n";
                break;

            case MULTIBOOT_INFO_BOOTDEV:
                screen << os::Screen::hex
                       << mbootInfo->boot_device << '\n'
                       << os::Screen::dec;
                break;

            case MULTIBOOT_INFO_CMDLINE:
                screen << reinterpret_cast<const char*>(mbootInfo->cmdline) << '\n';
                break;

            case MULTIBOOT_INFO_MODS:
                screen << mbootInfo->mods_count << " boot module" << (mbootInfo->mods_count == 1 ? "" : "s") << " were loaded\n";
                break;

            case MULTIBOOT_INFO_AOUT_SYMS:
                screen << "AOUT\n";
                break;

            case MULTIBOOT_INFO_ELF_SHDR:
                screen << "ELF\n";
                break;

            case MULTIBOOT_INFO_DRIVE_INFO:
                screen << mbootInfo->drives_length << '\n';
                break;

            case MULTIBOOT_INFO_CONFIG_TABLE:
                screen << os::Screen::hex
                       << mbootInfo->config_table << '\n'
                       << os::Screen::dec;
                break;

            case MULTIBOOT_INFO_MEM_MAP:
                screen << mbootInfo->mmap_length << '\n';
                break;

            case MULTIBOOT_INFO_BOOT_LOADER_NAME:
                screen << reinterpret_cast<const char*>(mbootInfo->boot_loader_name) << '\n';
                break;

            default:
                screen << '\n';
                break;
            }
        }

        bit <<= 1;
    }
}

void printMemMap(uint32_t addr, uint32_t len)
{
    uint32_t offset = 0;
    while (offset < len)
    {
        const multiboot_mmap_entry* entry = reinterpret_cast<const multiboot_mmap_entry*>(addr + offset);

        uint64_t startAddr = entry->addr;
        uint64_t endAddr = entry->addr + entry->len - 1;

        screen << os::Screen::hex
               << "0x" << startAddr << " - " << "0x" << endAddr
               << os::Screen::dec
               << " (" << (entry->len / 1024) << " KB)\n";

        offset += entry->size + sizeof(entry->size);
    }
}
<|endoftext|>


<commit_before>c865cb78-2747-11e6-8977-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>c87162e3-2747-11e6-9771-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int level,pv,vel,exp_agg,exp,num,inum,lunghezza,nums;
unsigned int Pokemonum;
char a[100];
string Pokemon,Shiny,scheda,fisico=":fisico:",mosse_apprese,azione,lista_mosse_if,nome_pokemon,nome_pokemonm,typing,mossa[4],snum;
int mosse();
int dati();
int shiny();
int main()
{
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\n");
	// printf("Quanti Pokemon vuoi creare?");
	// cin>>snum;
	// for(int i=1;i<=inum;i++)
	// {
		do
		{
		printf("\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Poke'mon: ");
		cin >> Pokemonum;
		}while(Pokemonum<=0 or Pokemonum>802);
		dati();
		shiny();
		do
		{
		    printf("Digita il livello del Pokemon!\n");
	 	    cin >> level;
		} while(level<=0 or level>100);
		vel = vel + level - 1;
		int pot_da_aggiungere;
		if (level >= 51)
		{
			pv = (49 * 3) + ((level - 50) * 5) + pv;
			pot_da_aggiungere = 49 + (level - 50) * 2;
		}
		else
		{
			pv = (level - 1) * 3 + pv;
			pot_da_aggiungere = level - 1;
		}
		int pot_azione = 4 + pot_da_aggiungere;
		printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
		cin >>	 lista_mosse_if;
		if ((lista_mosse_if.compare("Sì") or lista_mosse_if.compare("sì") or lista_mosse_if.compare("Si") or lista_mosse_if.compare("si")) == 0)
		{
			mosse();
			cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
		}
		printf("Inserisci la mossa numero 1\n");
	 	cin>>mossa[0];
	 	printf("Inserisci la mossa numero 2\n");
	 	cin>>mossa[1];
	 	printf("Inserisci la mossa numero 3\n");
	 	cin>>mossa[2];
	 	printf("Inserisci la mossa numero 4\n");
	 	cin>>mossa[3];
	 	exp = exp_agg * level;
	 	FILE * fp;
	 	fp = fopen("num.txt","a+");
		fclose(fp);
		ofstream ofs;
		ifstream ifs;
		ifs.open("num.txt", ios::binary);
		ifs.seekg(0, ios::end);
		lunghezza = ifs.tellg();
		ifs.close();
		if (lunghezza == 0)
		{
			fp = fopen("num.txt","a+");
			nums = 1;
			fprintf(fp,"%d", nums);
			fclose(fp);
		}
		else
		{
			fp = fopen("num.txt","a+");
			rewind(fp);
			fscanf(fp,"%s",a);
			fclose(fp);
			ofs.open("num.txt");
			nums = std::stoi(a);
			nums++;
			ofs.close();
			ofs.open("num.txt",ios::trunc);
			fprintf(fp, "%d", nums);
			ofs.close();
    	}

	 	scheda = "Scheda numero " + to_string(nums) + ":\n\n\n" +  Pokemon + "Lv: " + to_string(level) + "\n" + "Pv: " + to_string(pv) + "\n" + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "\n" + "EXP: 0/" + to_string(exp) + "\n\n\n";
	 	FILE * schedaF;
	 	schedaF = fopen("Scheda.txt", "a+");
		fputs(scheda.c_str(), schedaF);
		fclose(schedaF);
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt', il numero della scheda è %d.\n", nums);
	cin.get();
 }

int dati()
{
	switch(Pokemonum)
	{
		case 1:
		nome_pokemon = "bulbasaur";
		nome_pokemonm = "Bulbasaur";
		pv = 23;
		vel = 45;
		typing=":erba: :veleno:";
		exp_agg = 2;
		break;

		case 2:
		nome_pokemon = "ivysaur";
		nome_pokemonm = "Ivysaur";
		pv = 23;
		vel = 45;
		typing=":erba: :veleno:";
		exp_agg = 2;
		break;

		case 3:
		nome_pokemon = "venusaur";
		nome_pokemonm = "Venusaur";
		pv = 23;
		vel = 45;
		typing=":erba: :veleno:";
		exp_agg=2;
		break;

		case 4:
		nome_pokemon = "charmander";
		nome_pokemonm = "Charmander";
		pv = 15;
		vel = 65;
		typing=":fuoco:";
		exp_agg=2;
		break;

		case 7:
		nome_pokemon = "squirtle";
		nome_pokemonm = "Squirtle";
		pv = 15;
		vel = 65;
		typing=":acqua:";
		exp_agg=2;
		break;

		default:
		printf("Non implementato\n");
		cin.get();
	}
}

int mosse()
{
	switch(Pokemonum)
	{
		case 1:
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 2:
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 3:
		mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
		break;

		case 4:
		mosse_apprese= "Graffio\nRuggito\nBraciere\nMuro di Fumo\nIra di Drago\nVisotruce\nRogodenti\nPirolancio\nLacerazione\nLanciafiamme\nTurbofuoco\nMarchiatura";
		break;

		case 7:
		mosse_apprese= "Azione\nColpocoda\nPistolacqua\nRitirata\nBolla\nMorso\nRapigiro\nProtezione\nIdropulsar\nIdrondata\nCapocciata\nFerroscudo\nPioggiadanza\nIdropompa";
		break;
	}
}

int shiny()
{
	cout<<"Hai scelto "<<nome_pokemonm<<"!\nIl Poke'mon e' shiny? Rispondi con 'Si' o 'No'\n";
	cin >> Shiny;
	if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
	{
		cout<<"Ok, hai selezionato "<<nome_pokemonm<<" shiny!\n";
		Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/"+nome_pokemon+".gif]\n"+nome_pokemonm+""+typing+"\n";
	}
	if (Shiny == "No" or Shiny == "no")
	{
		cout<<"Ok, hai selezionato "<<nome_pokemonm<<" NON shiny!\n";
		Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/"+nome_pokemon+".gif]\n"+nome_pokemonm+""+typing+"\n";
	}
}
<commit_msg>Rimosse le variabili globali<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int level,pv,vel,exp_agg,exp,num,inum,lunghezza,nums;
unsigned int Pokemonum;
char a[100];
string Pokemon,Shiny,scheda,fisico=":fisico:",mosse_apprese,azione,lista_mosse_if,nome_pokemon,nome_pokemonm,typing,mossa[4],snum;
int main()
{
	printf("Benvenuto nel generatore schede di Bestfast!\nIniziamo!\n");
	// printf("Quanti Pokemon vuoi creare?");
	// cin>>snum;
	// for(int i=1;i<=inum;i++)
	// {
		do
		{
		printf("\nInserisci il numero Pokedex del Pokemon, guarda 'LISTA_POKEMON.txt' per la lista dei Pokemon: ");
		cin >> Pokemonum;
		}while(Pokemonum<=0 or Pokemonum>802);
		switch(Pokemonum)
			{
				case 1:
				nome_pokemon = "bulbasaur";
				nome_pokemonm = "Bulbasaur";
				pv = 23;
				vel = 45;
				typing=":erba: :veleno:";
				exp_agg = 2;
				break;

				case 2:
				nome_pokemon = "ivysaur";
				nome_pokemonm = "Ivysaur";
				pv = 23;
				vel = 45;
				typing=":erba: :veleno:";
				exp_agg = 2;
				break;

				case 3:
				nome_pokemon = "venusaur";
				nome_pokemonm = "Venusaur";
				pv = 23;
				vel = 45;
				typing=":erba: :veleno:";
				exp_agg=2;
				break;

				case 4:
				nome_pokemon = "charmander";
				nome_pokemonm = "Charmander";
				pv = 15;
				vel = 65;
				typing=":fuoco:";
				exp_agg=2;
				break;

				case 7:
				nome_pokemon = "squirtle";
				nome_pokemonm = "Squirtle";
				pv = 15;
				vel = 65;
				typing=":acqua:";
				exp_agg=2;
				break;

				default:
				printf("Non implementato\n");
				cin.get();
			}
			cout<<"Hai scelto "<<nome_pokemonm<<"!\nIl Poke'mon e' shiny? Rispondi con 'Si' o 'No'\n";
			cin >> Shiny;
			if (Shiny == "Sì" or Shiny == "sì" or Shiny == "Si" or Shiny == "si")
			{
				cout<<"Ok, hai selezionato "<<nome_pokemonm<<" shiny!\n";
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani-shiny/"+nome_pokemon+".gif]\n"+nome_pokemonm+""+typing+"\n";
			}
			if (Shiny == "No" or Shiny == "no")
			{
				cout<<"Ok, hai selezionato "<<nome_pokemonm<<" NON shiny!\n";
				Pokemon = "[IMG=https://play.pokemonshowdown.com/sprites/xyani/"+nome_pokemon+".gif]\n"+nome_pokemonm+""+typing+"\n";
			}
		do
		{
		    printf("Digita il livello del Pokemon!\n");
	 	    cin >> level;
		} while(level<=0 or level>100);
		vel = vel + level - 1;
		int pot_da_aggiungere;
		if (level >= 51)
		{
			pv = (49 * 3) + ((level - 50) * 5) + pv;
			pot_da_aggiungere = 49 + (level - 50) * 2;
		}
		else
		{
			pv = (level - 1) * 3 + pv;
			pot_da_aggiungere = level - 1;
		}
		int pot_azione = 4 + pot_da_aggiungere;
		printf("Vuoi vedere la lista delle mosse che puo' imparare questo Pokemon?\n");
		cin >>	 lista_mosse_if;
		if ((lista_mosse_if.compare("Sì") or lista_mosse_if.compare("sì") or lista_mosse_if.compare("Si") or lista_mosse_if.compare("si")) == 0)
		{
			switch(Pokemonum)
			{
				case 1:
				mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
				break;

				case 2:
				mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
				break;

				case 3:
				mosse_apprese = "Affannoseme\nAmnesia\nAttrazione\nAzione\nBullo\nCampo Erboso\nCapocciata\nConfidenza\nCoro\nCrescita\nCuordileone\nDanzaspada\nDoppioteam\nEccheggiavoce\nEnergipalla\nErbapatto\nFacciata\nFango\nFangobomba\nFascino\nFogliamagica\nFoglielama\nFrustata\nFrustazione\nGigassorbimento\nGiornodisole\nIntroforza\nLaccioerboso\nLegatutto\nMaledizione\nMeloderba\nNaturforza\nPetalodanza\nPrivazione\nProfumino\nProtezione\nRadicamento\nResistenza\nRiduttore\nRiposo\nRitorno\nRuggito\nRussare\nSalvaguardia\nSchermoluce\nSdoppiatore\nSemebomba\nSintesi\nSolarraggio\nSonnifero\nSonnolalia\nSostituto\nTossina\nVelenoshock\nVelenpolvere\nVerdebufera\nVigorcolpo";
				break;

				case 4:
				mosse_apprese= "Graffio\nRuggito\nBraciere\nMuro di Fumo\nIra di Drago\nVisotruce\nRogodenti\nPirolancio\nLacerazione\nLanciafiamme\nTurbofuoco\nMarchiatura";
				break;

				case 7:
				mosse_apprese= "Azione\nColpocoda\nPistolacqua\nRitirata\nBolla\nMorso\nRapigiro\nProtezione\nIdropulsar\nIdrondata\nCapocciata\nFerroscudo\nPioggiadanza\nIdropompa";
				break;
			}
			cout << nome_pokemon << " puo' imparare queste mosse:\n" << mosse_apprese << "\n";
		}
		printf("Inserisci la mossa numero 1\n");
	 	cin>>mossa[0];
	 	printf("Inserisci la mossa numero 2\n");
	 	cin>>mossa[1];
	 	printf("Inserisci la mossa numero 3\n");
	 	cin>>mossa[2];
	 	printf("Inserisci la mossa numero 4\n");
	 	cin>>mossa[3];
	 	exp = exp_agg * level;
	 	FILE * fp;
	 	fp = fopen("num.txt","a+");
		fclose(fp);
		ofstream ofs;
		ifstream ifs;
		ifs.open("num.txt", ios::binary);
		ifs.seekg(0, ios::end);
		lunghezza = ifs.tellg();
		ifs.close();
		if (lunghezza == 0)
		{
			fp = fopen("num.txt","a+");
			nums = 1;
			fprintf(fp,"%d", nums);
			fclose(fp);
		}
		else
		{
			fp = fopen("num.txt","a+");
			rewind(fp);
			fscanf(fp,"%s",a);
			fclose(fp);
			ofs.open("num.txt");
			nums = std::stoi(a);
			nums++;
			ofs.close();
			ofs.open("num.txt",ios::trunc);
			fprintf(fp, "%d", nums);
			ofs.close();
    	}

	 	scheda = "Scheda numero " + to_string(nums) + ":\n\n\n" +  Pokemon + "Lv: " + to_string(level) + "\n" + "Pv: " + to_string(pv) + "\n" + "Vel " + to_string(vel) + "\n" + mossa[0] + "\n" + mossa[1] + "\n" + mossa[2] + "\n" + mossa[3] + "\n" + "EXP: 0/" + to_string(exp) + "\n\n\n";
	 	FILE * schedaF;
	 	schedaF = fopen("Scheda.txt", "a+");
		fputs(scheda.c_str(), schedaF);
		fclose(schedaF);
	printf("Ben fatto! Trovi la scheda nel file 'Scheda.txt', il numero della scheda è %d.\n", nums);
	cin.get();
 }
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define HOSTPORT 31415

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTADDR "10.3.14.15"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;

    #ifdef MASTER

    int addrlen, master_socket, new_socket, clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    master_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (master_socket < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(master_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(master_socket, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(master_socket, &fds);
        int ms = master_socket;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(master_socket, &fds))
        {
            int newsock = accept(master_socket, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!\n";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                char buf[1025];
                int val = read(s, buf, 1024);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 1] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message\n";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        #endif
    }

    #ifdef MASTER

    #endif
}
<commit_msg>Fixed client buffer printing on server<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define HOSTPORT 31415

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTADDR "10.3.14.15"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;

    #ifdef MASTER

    int addrlen, master_socket, new_socket, clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    master_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (master_socket < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(master_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(master_socket, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(master_socket, &fds);
        int ms = master_socket;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(master_socket, &fds))
        {
            int newsock = accept(master_socket, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!\n";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                char buf[1025];
                int val = read(s, buf, 1024);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 2] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message\n";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        #endif
    }

    #ifdef MASTER

    #endif
}
<|endoftext|>


<commit_before>#include <boost/asio.hpp>
#include <iostream>
//#include <functional>

using namespace std;

int main()
{
	auto f = [](string s){ cout << s << endl; };
	f("Hello, world!");
	return 0;
}
<commit_msg>Attempt at fix for building on Travis.<commit_after>#define BOOST_ASIO_HAS_MOVE
#include <boost/asio.hpp>
#include <iostream>
//#include <functional>

using namespace std;

int main()
{
	auto f = [](string s){ cout << s << endl; };
	f("Hello, world!");
	return 0;
}
<|endoftext|>


<commit_before>391fdaba-ad58-11e7-9dcb-ac87a332f658<commit_msg>Tuesday, turns out it was tuesday<commit_after>397ebfb0-ad58-11e7-bce8-ac87a332f658<|endoftext|>


<commit_before> #include <iostream>
  #include "MagicLamp.h"

  namespace arabiannights {
    class Genie;
    class RecyclableDemon;
  }

  int main() {
    // 1. Criar uma lâmpada mágica com capacidade para 4 génios.
    // Magic lamp is created in the stack.
    arabiannights::MagicLamp ml(4);

    // Items 2. through 7. are simply executed in a cycle.
    int wishes[] = { 2, 3, 4, 5, 1 };  // number of wishes per genie
    arabiannights::Genie *genies[5];                  // vector for genies

    // 2. Esfregar 5 vezes a lâmpada, indicando os números de desejos 2, 3, 4, 5, 1.
    for (size_t gx = 0; gx < 5; gx++) genies[gx] = ml.rub(wishes[gx]);

    // 3. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 4. Pedir um desejo a cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) genies[gx]->grantWish();

    // 5. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 6. Pedir um desejo a cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) genies[gx]->grantWish();

    // 7. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 8. Colocar o demónio reciclável na lâmpada.
    // tricky (how can we be certain the demon is in the 5th position?)
    ml.feedDemon((arabiannights::RecyclableDemon*)genies[4]);

    // 9. Esfregar a lâmpada, indicando 7 como número de desejos.
    arabiannights::Genie *g = ml.rub(7);

    // 10. Imprimir em std::cout (utilizando o operador <<) o génio obtido.
    std::cout << *g << std::endl;

    return 0;
  }
<commit_msg>Update<commit_after> #include <iostream>
 #include "MagicLamp.h"

  namespace arabiannights {
    class Genie;
    class RecyclableDemon;
  }

  int main() {
    // 1. Criar uma lâmpada mágica com capacidade para 4 génios.
    // Magic lamp is created in the stack.
    arabiannights::MagicLamp ml(4);

    // Items 2. through 7. are simply executed in a cycle.
    int wishes[] = { 2, 3, 4, 5, 1 };  // number of wishes per genie
    arabiannights::Genie *genies[5];                  // vector for genies

    // 2. Esfregar 5 vezes a lâmpada, indicando os números de desejos 2, 3, 4, 5, 1.
    for (size_t gx = 0; gx < 5; gx++) genies[gx] = ml.rub(wishes[gx]);

    // 3. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 4. Pedir um desejo a cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) genies[gx]->grantWish();

    // 5. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 6. Pedir um desejo a cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) genies[gx]->grantWish();

    // 7. Imprimir em std::cout (utilizando o operador <<) cada um dos génios.
    for (size_t gx = 0; gx < 5; gx++) std::cout << *genies[gx] << std::endl;

    // 8. Colocar o demónio reciclável na lâmpada.
    // tricky (how can we be certain the demon is in the 5th position?)
    ml.feedDemon((arabiannights::RecyclableDemon*)genies[4]);

    // 9. Esfregar a lâmpada, indicando 7 como número de desejos.
    arabiannights::Genie *g = ml.rub(7);

    // 10. Imprimir em std::cout (utilizando o operador <<) o génio obtido.
    std::cout << *g << std::endl;

    return 0;
  }
<|endoftext|>


<commit_before>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>

using namespace std;
using namespace boost;

//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
	//different connectors
	string semicolon = ";";
	string needfirst = "&&";
	string needfirstfail = "||";
	int i = 0;

	//finding connectors
	while (command.size() != 0)
	{
		int semi = 0;//command.find(semicolon);
		int needf = 0;//command.find(needfirst);
		int needff = 0;//command.find(needfirstfail);

		//test for cases where connectors are gone
		if (command.find(semicolon) != string::npos)
		{
			semi = command.find(semicolon);
		}
		else
		{
			semi = 10000;
		}
		if (command.find(needfirst) != string::npos)
		{
			needf = command.find(needfirst);
		}
		else
		{
			needf = 10000;
		}
		if (command.find(needfirstfail) != string::npos)
		{
			needff = command.find(needfirstfail);
		}
		else
		{
			needff = 10000;
		}

		vector<string> temp;
		if (semi > needf)
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(needfirst);
				temp.push_back(command.substr(0, needf));
				command = command.substr(needf + 2, command.size() - needf - 2);
				++i;
			}
		}
		else if (needf > semi)
		{
			if (semi > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(semicolon);
				temp.push_back(command.substr(0, semi));
				command = command.substr(semi + 1, command.size() - semi - 1);
				++i;
			}
		}
		else if ( (needf == semi) && (needff != 10000) )
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
		}
		else
		{
			//used when out of connectors
			temp.push_back(command);
			cmd.push_back(temp);
			return;
		}
		cmd.push_back(temp);
	}
}

//tokenizer function
void token(vector< vector<string> > &cmdl)
{
	string f;
	for (int i = 0; i < cmdl.size(); ++i)
	{
		int j = 0;
		typedef tokenizer< char_separator<char> > tokenizer;
		char_separator<char> sep(" ");
		tokenizer tokens(cmdl.at(i).at(0), sep);
		cmdl.at(i).pop_back();
		for (tokenizer::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
		{
			f = *iter;
			cmdl.at(i).push_back(f);
			++j;
		}
	}
}
/*
//main run function, will prepare the command line
void run()
{
	//sentinel for while loop
	while (true)
	{
		//take in a command into a variable
		string command;
		cout << "$ ";
		getline(cin, command);
		cout << endl;

		//exit command
		if (command == "exit")
		{
			exit(0);
		}
		else
		{
			//call to parse
			vector< vector<string> > cmdline;
			vector<string> connectors;
			parseconnect(cmdline, connectors, command);

		}
	}
}
*/
//main function, will contain test cases

int main()
{
    int gethostname(char* name, size_t len);
    int sethostname(const char* name, size_t len);

	string command = "ls -a && echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
	vector< vector<string> > cmdline;
	vector<string> connectors;
	parseconnect(cmdline, connectors, command);

	for (int i = 0; i < cmdline.size() - 1; ++i)
	{
		cout << cmdline.at(i).at(0);
		for (int j = i; j < i + 1; ++j)
		{
			cout << connectors.at(j);
		}
	}
	cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
	token(cmdline);
	for (int i = 0; i < cmdline.size(); ++i)
	{
		for (int j = 0; j < cmdline.at(i).size(); ++j)
		{
			cout << "<" << cmdline.at(i).at(j) << ">" << endl;
		}
	}
	return 0;
}
<commit_msg>Implemented the login function where we output the login name @ hostname<commit_after>#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <vector>

using namespace std;
using namespace boost;

//function used to seperate commands
void parseconnect(vector< vector<string> > &cmd, vector<string> &connect, string command)
{
	//different connectors
	string semicolon = ";";
	string needfirst = "&&";
	string needfirstfail = "||";
	int i = 0;

	//finding connectors
	while (command.size() != 0)
	{
		int semi = 0;//command.find(semicolon);
		int needf = 0;//command.find(needfirst);
		int needff = 0;//command.find(needfirstfail);

		//test for cases where connectors are gone
		if (command.find(semicolon) != string::npos)
		{
			semi = command.find(semicolon);
		}
		else
		{
			semi = 10000;
		}
		if (command.find(needfirst) != string::npos)
		{
			needf = command.find(needfirst);
		}
		else
		{
			needf = 10000;
		}
		if (command.find(needfirstfail) != string::npos)
		{
			needff = command.find(needfirstfail);
		}
		else
		{
			needff = 10000;
		}

		vector<string> temp;
		if (semi > needf)
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(needfirst);
				temp.push_back(command.substr(0, needf));
				command = command.substr(needf + 2, command.size() - needf - 2);
				++i;
			}
		}
		else if (needf > semi)
		{
			if (semi > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
			else
			{
				connect.push_back(semicolon);
				temp.push_back(command.substr(0, semi));
				command = command.substr(semi + 1, command.size() - semi - 1);
				++i;
			}
		}
		else if ( (needf == semi) && (needff != 10000) )
		{
			if (needf > needff)
			{
				connect.push_back(needfirstfail);
				temp.push_back(command.substr(0, needff));
				command = command.substr(needff + 2, command.size() - needff - 2);
				++i;
			}
		}
		else
		{
			//used when out of connectors
			temp.push_back(command);
			cmd.push_back(temp);
			return;
		}
		cmd.push_back(temp);
	}
}

//tokenizer function
void token(vector< vector<string> > &cmdl)
{
	string f;
	for (int i = 0; i < cmdl.size(); ++i)
	{
		int j = 0;
		typedef tokenizer< char_separator<char> > tokenizer;
		char_separator<char> sep(" ");
		tokenizer tokens(cmdl.at(i).at(0), sep);
		cmdl.at(i).pop_back();
		for (tokenizer::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
		{
			f = *iter;
			cmdl.at(i).push_back(f);
			++j;
		}
	}
}
/*
//main run function, will prepare the command line
void run()
{
	//sentinel for while loop
	while (true)
	{
		//take in a command into a variable
		string command;
		cout << "$ ";
		getline(cin, command);
		cout << endl;

		//exit command
		if (command == "exit")
		{
			exit(0);
		}
		else
		{
			//call to parse
			vector< vector<string> > cmdline;
			vector<string> connectors;
			parseconnect(cmdline, connectors, command);

		}
	}
}
*/
//main function, will contain test cases

void startline()
{
    char hostname[128];
    int hostnameStatus = gethostname(hostname, sizeof(hostname)); //passes in an array named hostname & it basically makes a copy of the hostname stored
                                                                  //somewhere else and passes it back by reference (default b/c its an array).
    if(hostnameStatus == -1)
    {
        perror(hostname);
    }
    else
    {
         char* login = getlogin();
         cout << login << "@" << hostname << " $ ";
    }
}

int main()
{
    startline();

	string command = "ls -a && echo asdfkasdfjasdf ; echo asdfjjenenc || aasdfaf";
	vector< vector<string> > cmdline;
	vector<string> connectors;
	parseconnect(cmdline, connectors, command);

	for (int i = 0; i < cmdline.size() - 1; ++i)
	{
		cout << cmdline.at(i).at(0);
		for (int j = i; j < i + 1; ++j)
		{
			cout << connectors.at(j);
		}
	}
	cout << cmdline.at(cmdline.size() - 1).at(0) << endl;
	token(cmdline);
	for (int i = 0; i < cmdline.size(); ++i)
	{
		for (int j = 0; j < cmdline.at(i).size(); ++j)
		{
			cout << "<" << cmdline.at(i).at(j) << ">" << endl;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>85e83221-2749-11e6-9b82-e0f84713e7b8<commit_msg>more bug fix<commit_after>85f59991-2749-11e6-b779-e0f84713e7b8<|endoftext|>


<commit_before>b466cb07-4b02-11e5-8fa8-28cfe9171a43<commit_msg>my cat is cute<commit_after>b47276f5-4b02-11e5-981f-28cfe9171a43<|endoftext|>


<commit_before>#include "MainWindow.h"
#include "Emulator.h"
#include "Random.h"

#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	Random::setRandomSeed();

	QApplication a(argc, argv);

	Chip8GUI::MainWindow w;
	w.show();

	return a.exec();
}
<commit_msg>Removed unnecessary #include<commit_after>#include "MainWindow.h"
#include "Random.h"

#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	Random::setRandomSeed();

	QApplication a(argc, argv);

	Chip8GUI::MainWindow w;
	w.show();

	return a.exec();
}
<|endoftext|>


<commit_before>73f2388f-ad58-11e7-8850-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>744a5407-ad58-11e7-af69-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <time.h>

using namespace std;

/**
 * @brief quickSort
 * @param array
 * @param firstElementNumder
 * @param lastElementNumder
 */
void quickSort(int *array, int firstElementNumder, int lastElementNumder) {
    int mid, count;
    int f = firstElementNumder, l = lastElementNumder;
    mid = array[(f + l) / 2];
    do {
        while (array[f] < mid) f++;
        while (array[l] > mid) l--;
        if (f <= l) {
            count = array[f];
            array[f] = array[l];
            array[l] = count;
            f++;
            l--;
        }
    } while (f < l);
    if (firstElementNumder < l) quickSort(array, firstElementNumder, l);
    if (f < lastElementNumder) quickSort(array, f, lastElementNumder);
}

/**
 * @brief insertionSort
 * @param array
 * @param elementsCount
 */
void insertionSort(int *array, int elementsCount) {
    for (int firstElementNumder = 1; firstElementNumder < elementsCount; firstElementNumder++) {
        for (int numberElement = firstElementNumder; numberElement > 0
                                                     &&
                                                     array[numberElement - 1] > array[numberElement]; numberElement--) {
            array[numberElement - 1] = array[numberElement - 1] + array[numberElement];
            array[numberElement] = array[numberElement - 1] - array[numberElement];
            array[numberElement - 1] = array[numberElement - 1] - array[numberElement];
        }
    }
}

/**
 * @brief bubbleSort
 * @param array
 * @param elementsCount
 */
void bubbleSort(int *array, int elementsCount) {
    bool sorted = false;
    while (!sorted) {
        sorted = true;
        for (int numberElement = 0; numberElement < (elementsCount - 1); numberElement++)
            if (array[numberElement] > array[numberElement + 1]) {
                array[numberElement + 1] = array[numberElement + 1] + array[numberElement];
                array[numberElement] = array[numberElement + 1] - array[numberElement];
                array[numberElement + 1] = array[numberElement + 1] - array[numberElement];
                sorted = false;
            }
    }
}

/**
 * @brief fillArray
 * @param array
 * @param elementsCount
 */
void fillArray(int *array, int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        array[numberElement] = rand() % 65535;
    }
}

/**
 * @brief print
 * @param array
 * @param elementsCount
 */
void print(int *array, int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        cout << setw(2) << array[numberElement] << "  ";
    }
    cout << endl;
}

/**
 * @brief arrayDuplicator void
 * @param arrayIn array
 * @param arrayOut array
 * @param elementsCount int
 */
void arrayDuplicator(int arrayIn[], int arrayOut[], int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        arrayOut[numberElement] = arrayIn[numberElement];
    }
}

int main() {
    int elementsCount;
    cout << "Enter array elements count: ";
    cin >> elementsCount;

    srand(time(NULL));
    clock_t timerClock = 0;
    double sortTime[3];

    int *array = new int[elementsCount];
    int *arrayTemp = new int[elementsCount];
    fillArray(array, elementsCount);

    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    quickSort(arrayTemp, 0, elementsCount - 1);
    timerClock = clock() - timerClock;
    sortTime[0] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock quickSort: " << sortTime[0] << " milliseconds" << "\n\n";

    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    insertionSort(arrayTemp, elementsCount);
    timerClock = clock() - timerClock;
    sortTime[1] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock insertionSort: " << sortTime[1] << " milliseconds" << "\n\n";

    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    bubbleSort(arrayTemp, elementsCount);
    timerClock = clock() - timerClock;
    sortTime[2] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock bubbleSort: " << sortTime[2] << " milliseconds" << "\n\n";

    system("pause");
    return 0;
}
<commit_msg>Добавленна запись массивов в файлы<commit_after>#include <iostream>
#include <iomanip>
#include <time.h>
#include <fstream>
#include <cstring>

using namespace std;

/**
 * @brief quickSort
 * @param array
 * @param firstElementNumder
 * @param lastElementNumder
 */
void quickSort(int *array, int firstElementNumder, int lastElementNumder) {
    int mid, count;
    int f = firstElementNumder, l = lastElementNumder;
    mid = array[(f + l) / 2];
    do {
        while (array[f] < mid) f++;
        while (array[l] > mid) l--;
        if (f <= l) {
            count = array[f];
            array[f] = array[l];
            array[l] = count;
            f++;
            l--;
        }
    } while (f < l);
    if (firstElementNumder < l) quickSort(array, firstElementNumder, l);
    if (f < lastElementNumder) quickSort(array, f, lastElementNumder);
}

/**
 * @brief insertionSort
 * @param array
 * @param elementsCount
 */
void insertionSort(int *array, int elementsCount) {
    for (int firstElementNumder = 1; firstElementNumder < elementsCount; firstElementNumder++) {
        for (int numberElement = firstElementNumder; numberElement > 0
                                                     &&
                                                     array[numberElement - 1] > array[numberElement]; numberElement--) {
            array[numberElement - 1] = array[numberElement - 1] + array[numberElement];
            array[numberElement] = array[numberElement - 1] - array[numberElement];
            array[numberElement - 1] = array[numberElement - 1] - array[numberElement];
        }
    }
}

/**
 * @brief bubbleSort
 * @param array
 * @param elementsCount
 */
void bubbleSort(int *array, int elementsCount) {
    bool sorted = false;
    while (!sorted) {
        sorted = true;
        for (int numberElement = 0; numberElement < (elementsCount - 1); numberElement++)
            if (array[numberElement] > array[numberElement + 1]) {
                array[numberElement + 1] = array[numberElement + 1] + array[numberElement];
                array[numberElement] = array[numberElement + 1] - array[numberElement];
                array[numberElement + 1] = array[numberElement + 1] - array[numberElement];
                sorted = false;
            }
    }
}

/**
 * @brief fillArray
 * @param array
 * @param elementsCount
 */
void fillArray(int *array, int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        array[numberElement] = rand() % 65535;
    }
}

/**
 * @brief print
 * @param array
 * @param elementsCount
 */
void print(int *array, int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        cout << setw(2) << array[numberElement] << "  ";
    }
    cout << endl;
}

/**
 * @brief arrayDuplicator void
 * @param arrayIn array
 * @param arrayOut array
 * @param elementsCount int
 */
void arrayDuplicator(int arrayIn[], int arrayOut[], int elementsCount) {
    for (int numberElement = 0; numberElement < elementsCount; numberElement++) {
        arrayOut[numberElement] = arrayIn[numberElement];
    }
}

void write(int *array, int elementsCount, char *fileName) {
    ofstream fileStream;

    char fileTimePrefix[256];
    time_t seconds = time(NULL);
    tm *timeinfo = localtime(&seconds);
    strftime(fileTimePrefix, 128, "%d%m%Y_%I%M%S-", timeinfo);

    strcat(fileTimePrefix,fileName);
    strcat(fileTimePrefix,".csv");

    cout<<fileTimePrefix<<endl;
    fileStream.open(fileTimePrefix, ios_base::out | ios_base::trunc);
    for (int i = 0; i < elementsCount; i++) {
        fileStream << array[i] << ';' << endl;
    }
    fileStream.close();
}

int main() {
    int elementsCount;
    cout << "Enter array elements count: ";
    cin >> elementsCount;

    srand(time(NULL));
    clock_t timerClock = 0;
    double sortTime[3];
    int *array = new int[elementsCount];
    int *arrayTemp = new int[elementsCount];
    fillArray(array, elementsCount);

    write(array, elementsCount, "array");
    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    quickSort(arrayTemp, 0, elementsCount - 1);
    timerClock = clock() - timerClock;
    write(arrayTemp, elementsCount, "quickSort");
    sortTime[0] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock quickSort: " << sortTime[0] << " milliseconds" << "\n\n";

    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    insertionSort(arrayTemp, elementsCount);
    timerClock = clock() - timerClock;
    write(arrayTemp, elementsCount, "insertionSort");
    sortTime[1] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock insertionSort: " << sortTime[1] << " milliseconds" << "\n\n";

    arrayDuplicator(array, arrayTemp, elementsCount);

    timerClock = clock();
    bubbleSort(arrayTemp, elementsCount);
    timerClock = clock() - timerClock;
    write(arrayTemp, elementsCount, "bubbleSort");
    sortTime[2] = (((double) timerClock) / (double) CLOCKS_PER_SEC) * 1000;
    cout << "Clock bubbleSort: " << sortTime[2] << " milliseconds" << "\n\n";

    system("pause");
    return 0;
}
<|endoftext|>


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

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define PI 3.1415926

//Uncomment this line at run-time to skip GUI rendering
#define _DEBUG

using namespace cv;
using namespace std;

const string CAM_PATH="/dev/video0";
const string MAIN_WINDOW_NAME="Processed Image";
const string CANNY_WINDOW_NAME="Canny";

const int CANNY_LOWER_BOUND=50;
const int CANNY_UPPER_COUND=250;
const int HOUGH_THRESHOLD=130;

const int FORWARD=0,STOP=1,LEFT=2,RIGHT=3;
const char COMMANDS[][32]={	"sudo echo -n \"F\">/dev/ttyUSB0",
							"sudo echo -n \"S\">/dev/ttyUSB0",
							"sudo echo -n \"L\">/dev/ttyUSB0",
							"sudo echo -n \"R\">/dev/ttyUSB0"};

int generateCommand(float minRad,float maxRad)
{
	//Both edges are lost, stop the robot
	if(minRad>0&&maxRad<0)
		return STOP;
	//Right edge is loat
	if(minRad>0)
		return RIGHT;
	//Left edge is lost
	if(maxRad<0)
		return LEFT;

	float leftEdgeAngle=fabs(minRad*180/PI);
	float rightEdgeAngle=fabs(maxRad*180/PI);
	if(fabs(leftEdgeAngle-rightEdgeAngle)>15)
	{
		if(leftEdgeAngle>rightEdgeAngle)
			return RIGHT;
		else
			return LEFT;
	}
	else
		return FORWARD;
}

int main()
{
	//Initialize serialport to Arduino
	system("sudo stty -F "+CAM_PATH+" speed 115200 cs8 -parenb -cstopb -echo"。c_str());

	VideoCapture capture(CAM_PATH);
	//If this fails, try to open as a video camera, through the use of an integer param
	if (!capture.isOpened())
	{
		capture.open(atoi(CAM_PATH.c_str()));
	}

	double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH);			//the width of frames of the video
	double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT);		//the height of frames of the video
	clog<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl;

	//When all is ready, let the robot go forward
	system("sudo echo -n \"F\">/dev/ttyUSB0");

	Mat image;
	while(true)
	{
		capture>>image;
		if(image.empty())
			break;

		//Set the ROI for the image
		Rect roi(0,image.rows/3,image.cols,image.rows/3);
		Mat imgROI=image(roi);

		//Canny algorithm
		Mat contours;
		Canny(imgROI,contours,CANNY_LOWER_BOUND,CANNY_UPPER_COUND);
		#ifdef _DEBUG
		imshow(CANNY_WINDOW_NAME,contours);
		#endif

		vector<Vec2f> lines;
		HoughLines(contours,lines,1,PI/180,HOUGH_THRESHOLD);
		Mat result(imgROI.size(),CV_8U,Scalar(255));
		imgROI.copyTo(result);
		clog<<lines.size()<<endl;

		float maxRad=-PI/2;
		float minRad=PI/2;
		//Draw the lines and judge the slope
		for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it)
		{
			float rho=(*it)[0];			//First element is distance rho
			float theta=(*it)[1];		//Second element is angle theta
			if(theta>PI/2)
				theta-=PI;

			//Filter to remove vertical and horizontal lines,
			//and atan(0.09) equals about 5 degrees.
			if((theta>0.09&&theta<1.48)||(theta<-0.09&&theta>-1.48))
			{
				if(theta>maxRad)
					maxRad=theta;
				if(theta<minRad)
					minRad=theta;

				#ifndef _DEBUG
				//point of intersection of the line with first row
				Point pt1(rho/cos(theta),0);
				//point of intersection of the line with last row
				Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
				//Draw a line
				line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA);
				#endif
			}

			clog<<"Line: ("<<rho<<","<<theta<<")\n";
		}

		int nextOperation=generateCommand(minRad,maxRad);
		system(COMMANDS[nextOperation]);
		clog<<COMMANDS[nextOperation]<<endl;

		#ifdef _DEBUG
		stringstream overlayedText;
		overlayedText<<"Lines: "<<lines.size();
		putText(result,overlayedText.str(),Point(10,result.rows-10),2,0.8,Scalar(0,0,255),0);
		imshow(MAIN_WINDOW_NAME,result);
		#endif

		lines.clear();
		waitKey(1);
	}
	return 0;
}
<commit_msg>Fix typo<commit_after>#include <cstdlib>
#include <iostream>
#include <vector>

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define PI 3.1415926

//Uncomment this line at run-time to skip GUI rendering
#define _DEBUG

using namespace cv;
using namespace std;

const string CAM_PATH="/dev/video0";
const string MAIN_WINDOW_NAME="Processed Image";
const string CANNY_WINDOW_NAME="Canny";

const int CANNY_LOWER_BOUND=50;
const int CANNY_UPPER_COUND=250;
const int HOUGH_THRESHOLD=130;

const int FORWARD=0,STOP=1,LEFT=2,RIGHT=3;
const char COMMANDS[][32]={	"sudo echo -n \"F\">/dev/ttyUSB0",
							"sudo echo -n \"S\">/dev/ttyUSB0",
							"sudo echo -n \"L\">/dev/ttyUSB0",
							"sudo echo -n \"R\">/dev/ttyUSB0"};

int generateCommand(float minRad,float maxRad)
{
	//Both edges are lost, stop the robot
	if(minRad>0&&maxRad<0)
		return STOP;
	//Right edge is loat
	if(minRad>0)
		return RIGHT;
	//Left edge is lost
	if(maxRad<0)
		return LEFT;

	float leftEdgeAngle=fabs(minRad*180/PI);
	float rightEdgeAngle=fabs(maxRad*180/PI);
	if(fabs(leftEdgeAngle-rightEdgeAngle)>15)
	{
		if(leftEdgeAngle>rightEdgeAngle)
			return RIGHT;
		else
			return LEFT;
	}
	else
		return FORWARD;
}

int main()
{
	//Initialize serialport to Arduino
	system("sudo stty -F "+CAM_PATH+" speed 115200 cs8 -parenb -cstopb -echo".c_str());

	VideoCapture capture(CAM_PATH);
	//If this fails, try to open as a video camera, through the use of an integer param
	if (!capture.isOpened())
	{
		capture.open(atoi(CAM_PATH.c_str()));
	}

	double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH);			//the width of frames of the video
	double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT);		//the height of frames of the video
	clog<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl;

	//When all is ready, let the robot go forward
	system("sudo echo -n \"F\">/dev/ttyUSB0");

	Mat image;
	while(true)
	{
		capture>>image;
		if(image.empty())
			break;

		//Set the ROI for the image
		Rect roi(0,image.rows/3,image.cols,image.rows/3);
		Mat imgROI=image(roi);

		//Canny algorithm
		Mat contours;
		Canny(imgROI,contours,CANNY_LOWER_BOUND,CANNY_UPPER_COUND);
		#ifdef _DEBUG
		imshow(CANNY_WINDOW_NAME,contours);
		#endif

		vector<Vec2f> lines;
		HoughLines(contours,lines,1,PI/180,HOUGH_THRESHOLD);
		Mat result(imgROI.size(),CV_8U,Scalar(255));
		imgROI.copyTo(result);
		clog<<lines.size()<<endl;

		float maxRad=-PI/2;
		float minRad=PI/2;
		//Draw the lines and judge the slope
		for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it)
		{
			float rho=(*it)[0];			//First element is distance rho
			float theta=(*it)[1];		//Second element is angle theta
			if(theta>PI/2)
				theta-=PI;

			//Filter to remove vertical and horizontal lines,
			//and atan(0.09) equals about 5 degrees.
			if((theta>0.09&&theta<1.48)||(theta<-0.09&&theta>-1.48))
			{
				if(theta>maxRad)
					maxRad=theta;
				if(theta<minRad)
					minRad=theta;

				#ifndef _DEBUG
				//point of intersection of the line with first row
				Point pt1(rho/cos(theta),0);
				//point of intersection of the line with last row
				Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
				//Draw a line
				line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA);
				#endif
			}

			clog<<"Line: ("<<rho<<","<<theta<<")\n";
		}

		int nextOperation=generateCommand(minRad,maxRad);
		system(COMMANDS[nextOperation]);
		clog<<COMMANDS[nextOperation]<<endl;

		#ifdef _DEBUG
		stringstream overlayedText;
		overlayedText<<"Lines: "<<lines.size();
		putText(result,overlayedText.str(),Point(10,result.rows-10),2,0.8,Scalar(0,0,255),0);
		imshow(MAIN_WINDOW_NAME,result);
		#endif

		lines.clear();
		waitKey(1);
	}
	return 0;
}
<|endoftext|>


<commit_before>30c2511e-2748-11e6-a274-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>30cf25ba-2748-11e6-b263-e0f84713e7b8<|endoftext|>


<commit_before>98e5a0c0-4b02-11e5-8b02-28cfe9171a43<commit_msg>Fix that bug where things didn't work but now they should<commit_after>98f3bbe1-4b02-11e5-8cf5-28cfe9171a43<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;
  if ((fp = fopen(filename, "rb")) == NULL) {
    return 1;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return 2;
  };
  fclose(fp);
  return 0;
}

static char *strpad(const char *string, char pad, size_t fieldSize);

char *strpad(const char *string, char pad, size_t fieldSize) {
  size_t ssize = strlen(string);
  size_t padSize = fieldSize - ssize;
  assert(padSize > 0);
  char padding[64];
  memset(padding, pad, 62);
  padding[63] = 0;
  char *padded = (char *) malloc(fieldSize + 1);
  strncpy(padded, string, fieldSize);
  strncat(padded, padding, padSize);
//  memset(padded, pad, fieldSize);
  padded[fieldSize] = 0;
//  strcpy(padded , string);
  return padded;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    maze.setFloodType(Maze::RUNLENGTH_FLOOD);
    barney.setSearchMethod(MazeSearcher::SEARCH_NORMAL);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
      std::cout << "";
      ReadRealWallsFromFile(glob_result.gl_pathv[i]);
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100 * costDifference) / openCost;

      if (residual < 5) {
//        MazePrinter::printVisitedDirs(barney.map());
        char *name = strpad(glob_result.gl_pathv[i], ' ', 43);
        std::cout << name;
        delete name;
        std::cout.width(6);
        std::cout << std::right;
        std::cout << steps << " steps";
        std::cout << " delta " << costDifference << " (" << residual << "%)";
        if (costDifference == 0) {
        onePassCount++;
            std::cout << " <---- ";
        std::cout << std::endl;
        } else if (residual < 5 && residual >= 0) {
            chancerCount++;
            std::cout << " ***** ";
        std::cout << std::endl;
          }
        }
      }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
    printf(" you should provide the name of at least one maze file on the command line\n");
  }
  return (EXIT_SUCCESS);
}

<commit_msg>improve test maze evaluation<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.c
 * Author: peterharrison
 *
 * Created on 07 February 2016, 23:47
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
#include "mazeprinter.h"
#include "mazesearcher.h"
#include <glob.h>

uint8_t wallData[1024];

int ReadRealWallsFromFile(char *filename) {
  FILE *fp;
  if ((fp = fopen(filename, "rb")) == NULL) {
    return 1;
  }
  if (fread(wallData, 1, 256, fp) < 256) {
    fclose(fp);
    return 2;
  };
  fclose(fp);
  return 0;
}

static char *strpad(const char *string, char pad, size_t fieldSize);

char *strpad(const char *string, char pad, size_t fieldSize) {
  size_t ssize = strlen(string);
  size_t padSize = fieldSize - ssize;
  assert(padSize > 0);
  char padding[128];
  memset(padding, pad, 126);
  padding[127] = 0;
  char *padded = (char *) malloc(fieldSize + 1);
  strncpy(padded, string, fieldSize);
  strncat(padded, padding, padSize);
//  memset(padded, pad, fieldSize);
  padded[fieldSize] = 0;
//  strcpy(padded , string);
  return padded;
}

/*
 *
 */
int main(int argc, char **argv) {
  MazeSearcher barney;
  glob_t glob_result;
  glob("./mazefiles/*", GLOB_TILDE, NULL, &glob_result);
  if (argc > 1) {
    Maze maze(16);
    int onePassCount = 0;
    int chancerCount = 0;
    printf("   FULL  MODOPEN   MODALL\n");
    maze.setFloodType(Maze::RUNLENGTH_FLOOD);
    barney.setSearchMethod(MazeSearcher::SEARCH_NORMAL);
    for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {
      std::cout << "";
      ReadRealWallsFromFile(glob_result.gl_pathv[i]);
      maze.load(wallData);
      maze.copyMazeFromFileData(wallData, 256);
      maze.flood(0x77);
      barney.setRealMaze(&maze);
      barney.map()->resetToEmptyMaze();
      barney.setLocation(0x00);
      int steps = barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      steps += barney.searchTo(0x77);
      steps += barney.searchTo(0x00);
      barney.map()->testForSolution();
      int costDifference = barney.map()->costDifference();
      int openCost = barney.map()->openMazeCost();
      int residual = (100 * costDifference) / openCost;

      if (residual > 5) {
        MazePrinter::printVisitedDirs(barney.map());
      }
      char *name = strpad(glob_result.gl_pathv[i], ' ', 50);
      std::cout << name;
      delete name;
      std::cout.width(6);
      std::cout << std::right;
      std::cout << steps << " steps";
      std::cout << " delta " << costDifference << " (" << residual << "%)";
      if (costDifference == 0) {
        onePassCount++;
        std::cout << " <---- ";
      } else if (residual < 5 && residual >= 0) {
        chancerCount++;
        std::cout << " ***** ";
      }
        std::cout << std::endl;

    }

    printf("\n%d mazes:\n", glob_result.gl_pathc);
    printf(" one Pass mazes: %3d\n", onePassCount);
    printf(" Possible chancer  mazes: %3d\n", chancerCount);

  } else {
    printf(" you should provide the name of at least one maze file on the command line\n");
  }
  return (EXIT_SUCCESS);
}

<|endoftext|>


<commit_before>f9a3cb99-2747-11e6-858a-e0f84713e7b8<commit_msg>updated some files<commit_after>f9aecbd9-2747-11e6-921d-e0f84713e7b8<|endoftext|>


<commit_before>/* **************************************************************
This code file is to remove duplicates from a given integer values
in the form of a linked list or an array.
***************************************************************/

#include<iostream>
#include<cstdio>
#include "list.h"
using namespace std;
int size=0;
int main()
{
    cout<<"\nEnter Size of the list: ";
    cin>>size;
    list m;

    m.populate();
    cout<<endl;
    cout<<"Initial List: ";
    m.display();
    m.purging();
    cout<<"\nPurged List : ";
    m.display();
    cout<<endl;

return 0;
}
<commit_msg>Update main.cpp<commit_after>/* **************************************************************
This code file is to remove duplicates from a given integer values
in the form of a linked list or an array.
***************************************************************/

#include<iostream>
#include<cstdio>
#include "list.h"
using namespace std;
int size=0;
int main()
{
    cout<<"\nEnter Size of the list: ";
    cin>>size;
    list m;

    if (size<=0)
    {return 0;}
    else
    {
    m.populate();
    cout<<endl;
    cout<<"Initial List: ";
    m.display();
    m.purging();
    cout<<"\nPurged List : ";
    m.display();
    cout<<endl;
    }
return 0;
}
<|endoftext|>


<commit_before>#include "src\htl\hvector.h"
#include <iostream>

int main()
{
	htl::vector<int> a;
	a.push_back(1);
	a.push_back(2);
	a.push_back(3);
	for(htl::vector<int>::iterator it = a.begin(); it != a.end(); it++)
	{
		std::cout << *it;
	}
	getchar();
	getchar();
}<commit_msg>little modification in vector test<commit_after>#include "src\htl\hvector.h"
#include <iostream>

int main()
{
	htl::vector<int> a;
	a.push_back(1);
	a.push_back(2);
	a.push_back(3);
	for(htl::vector<int>::iterator it = a.begin(); it != a.end(); it++)
	{
		std::cout << *it << std::endl;
	}
	getchar();
	getchar();
}<|endoftext|>


<commit_before>5936e182-2748-11e6-9162-e0f84713e7b8<commit_msg>more fixes<commit_after>5943d928-2748-11e6-a630-e0f84713e7b8<|endoftext|>


<commit_before>#include "stream.h"
#include "fft.hpp"

#include<ncurses.h>

#include<vector>
#include<complex>
#include<thread>
#include<atomic>
#include<algorithm>

const int MIN_SAMPLE_COUNT = 32;
const int MAX_SAMPLE_COUNT = 1 << 16;

const int FREQUENCY_CHANGE_STEP = 100;
const int THRESHOLD_CHANGE_STEP = 100;

const int SAMPLE_RATE = 44100;

short buffer[MAX_SAMPLE_COUNT];

int main() {
	initscr();
	raw();
	noecho();
	timeout(100);

	int min_frequency = 0;
	int max_frequency = 20000;
	int threshold = 1000;
	int sample_count = 1 << 15;

	std::vector<std::complex<double>> data(sample_count);

	std::thread sample_thread;

	bool running = true;
	std::atomic<bool> auto_sample(false);
	while(running) {
		clear();
		printw("Threshold: %d\n", threshold);
		printw("Frequency: %d - %d Hz\n", min_frequency, max_frequency);
		printw("Sample count: %d\n", sample_count);
		printw("=====================\n");

		std::vector<std::pair<double, double>> frequencies;
		for(int i = 0; i < (int) data.size() / 2; ++i) {
			double freq = (double) SAMPLE_RATE / data.size() * i;
			if(freq < min_frequency || freq > max_frequency)
				continue;
			double amp = abs(data[i]) * 2 / sample_count;
			if(amp < threshold)
				continue;
			frequencies.push_back({amp, freq});
		}
		std::sort(frequencies.begin(), frequencies.end(), [](auto x, auto y) { return x.first > y.first; });
		for(auto& f : frequencies) printw("%lfHz\n", f.second);

		if(auto_sample) {
			attron(A_BOLD);
			mvprintw(3, 3, " AUTO Sampling ");
			attroff(A_BOLD);
		}

		refresh();

		switch(getch()) {
			case 'q': // quit
				running = false;
				break;

			case 's': // make a sample
				if(auto_sample) break;

				attron(A_BOLD);
				mvprintw(3, 3, " Sampling ... ");
				attroff(A_BOLD);
				refresh();

				open_stream();
				read_stream(buffer, sizeof(short) * sample_count);
				free_stream();

				data.resize(sample_count);
				for(int i = 0; i < sample_count; ++i)
					data[i] = (double) buffer[i];
				fft(data);

				break;
			case 'S':
				if(auto_sample) {
					auto_sample = false;
					free_stream();
					sample_thread.join();
				} else {
					auto_sample = true;
					open_stream();

					sample_thread = std::thread([&] {
						while(auto_sample) {
							read_stream(buffer, sizeof(short) * sample_count);

							data.resize(sample_count);
							for(int i = 0; i < sample_count; ++i)
								data[i] = (double) buffer[i];
							fft(data);
						}
					});
				}
				break;

			case 'z':
				if(min_frequency - FREQUENCY_CHANGE_STEP >= 0)
					min_frequency -= FREQUENCY_CHANGE_STEP;
				break;
			case 'x':
				if(min_frequency + FREQUENCY_CHANGE_STEP < max_frequency)
					min_frequency += FREQUENCY_CHANGE_STEP;
				break;
			case 'c':
				if(max_frequency - FREQUENCY_CHANGE_STEP > min_frequency)
					max_frequency -= FREQUENCY_CHANGE_STEP;
				break;
			case 'v':
				if(max_frequency + FREQUENCY_CHANGE_STEP <= 20000)
					max_frequency += FREQUENCY_CHANGE_STEP;
				break;

			case '[':
				if(threshold - THRESHOLD_CHANGE_STEP >= 0)
					threshold -= THRESHOLD_CHANGE_STEP;
				break;
			case ']':
				threshold += THRESHOLD_CHANGE_STEP;
				break;

			case 'w':
				if(sample_count > MIN_SAMPLE_COUNT)
					sample_count >>= 1;
				break;
			case 'e':
				if(sample_count < MAX_SAMPLE_COUNT)
					sample_count <<= 1;
				break;
		}
	}

	if(auto_sample) {
		auto_sample = false;
		free_stream();
		sample_thread.join();
	}

	endwin();
}
<commit_msg>Fix race condition when exiting auto sample mode<commit_after>#include "stream.h"
#include "fft.hpp"

#include<ncurses.h>

#include<vector>
#include<complex>
#include<thread>
#include<atomic>
#include<algorithm>

const int MIN_SAMPLE_COUNT = 32;
const int MAX_SAMPLE_COUNT = 1 << 16;

const int FREQUENCY_CHANGE_STEP = 100;
const int THRESHOLD_CHANGE_STEP = 100;

const int SAMPLE_RATE = 44100;

short buffer[MAX_SAMPLE_COUNT];

int main() {
	initscr();
	raw();
	noecho();
	timeout(100);

	int min_frequency = 0;
	int max_frequency = 20000;
	int threshold = 1000;
	int sample_count = 1 << 15;

	std::vector<std::complex<double>> data(sample_count);

	std::thread sample_thread;

	bool running = true;
	std::atomic<bool> auto_sample(false);
	while(running) {
		clear();
		printw("Threshold: %d\n", threshold);
		printw("Frequency: %d - %d Hz\n", min_frequency, max_frequency);
		printw("Sample count: %d\n", sample_count);
		printw("=====================\n");

		std::vector<std::pair<double, double>> frequencies;
		for(int i = 0; i < (int) data.size() / 2; ++i) {
			double freq = (double) SAMPLE_RATE / data.size() * i;
			if(freq < min_frequency || freq > max_frequency)
				continue;
			double amp = abs(data[i]) * 2 / sample_count;
			if(amp < threshold)
				continue;
			frequencies.push_back({amp, freq});
		}
		std::sort(frequencies.begin(), frequencies.end(), [](auto x, auto y) { return x.first > y.first; });
		for(auto& f : frequencies) printw("%lfHz\n", f.second);

		if(auto_sample) {
			attron(A_BOLD);
			mvprintw(3, 3, " AUTO Sampling ");
			attroff(A_BOLD);
		}

		refresh();

		switch(getch()) {
			case 'q': // quit
				running = false;
				break;

			case 's': // make a sample
				if(auto_sample) break;

				attron(A_BOLD);
				mvprintw(3, 3, " Sampling ... ");
				attroff(A_BOLD);
				refresh();

				open_stream();
				read_stream(buffer, sizeof(short) * sample_count);
				free_stream();

				data.resize(sample_count);
				for(int i = 0; i < sample_count; ++i)
					data[i] = (double) buffer[i];
				fft(data);

				break;
			case 'S':
				if(auto_sample) {
					auto_sample = false;
					sample_thread.join();
					free_stream();
				} else {
					auto_sample = true;
					open_stream();

					sample_thread = std::thread([&] {
						while(auto_sample) {
							read_stream(buffer, sizeof(short) * sample_count);

							data.resize(sample_count);
							for(int i = 0; i < sample_count; ++i)
								data[i] = (double) buffer[i];
							fft(data);
						}
					});
				}
				break;

			case 'z':
				if(min_frequency - FREQUENCY_CHANGE_STEP >= 0)
					min_frequency -= FREQUENCY_CHANGE_STEP;
				break;
			case 'x':
				if(min_frequency + FREQUENCY_CHANGE_STEP < max_frequency)
					min_frequency += FREQUENCY_CHANGE_STEP;
				break;
			case 'c':
				if(max_frequency - FREQUENCY_CHANGE_STEP > min_frequency)
					max_frequency -= FREQUENCY_CHANGE_STEP;
				break;
			case 'v':
				if(max_frequency + FREQUENCY_CHANGE_STEP <= 20000)
					max_frequency += FREQUENCY_CHANGE_STEP;
				break;

			case '[':
				if(threshold - THRESHOLD_CHANGE_STEP >= 0)
					threshold -= THRESHOLD_CHANGE_STEP;
				break;
			case ']':
				threshold += THRESHOLD_CHANGE_STEP;
				break;

			case 'w':
				if(sample_count > MIN_SAMPLE_COUNT)
					sample_count >>= 1;
				break;
			case 'e':
				if(sample_count < MAX_SAMPLE_COUNT)
					sample_count <<= 1;
				break;
		}
	}

	if(auto_sample) {
		auto_sample = false;
		sample_thread.join();
		free_stream();
	}

	endwin();
}
<|endoftext|>


<commit_before>2df5aa1c-ad5c-11e7-874b-ac87a332f658<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>2e513d59-ad5c-11e7-b122-ac87a332f658<|endoftext|>


<commit_before>9c539d82-4b02-11e5-9af3-28cfe9171a43<commit_msg>my cat is cute<commit_after>9c6010c7-4b02-11e5-81a1-28cfe9171a43<|endoftext|>


<commit_before>b7c84c66-ad5c-11e7-acfa-ac87a332f658<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>b8383aab-ad5c-11e7-9773-ac87a332f658<|endoftext|>