<commit_before>//% Rollup drumkit userspace driver
//% Alex Grabovski <hurufu@gmail.com>
//% 2014-04-21
//% WTFPL

#include <iostream>
#include <csignal>
#include <unistd.h>

#include <libusb.h>
#include <jack/jack.h>
#include <jack/midiport.h>

#define DRUMKIT_VENDOR_ID 0x1941
#define DRUMKIT_PRODUCT_ID 0x8021

#define NOF_PADS 6

// Error codes
#define SUCCESS 0
#define ERR_ANSWER_LENGTH_MISMATCH 0xff
#define ERR_TRANSFER_FAILED 0xfe
#define ERR_LIBUSB_SPECIFIC 0xfd
#define ERR_JACK_SPECIFIC 0xfc
#define ERR_BAD_ARGUMENT 0xfb
#define ERR_UNKNOWN 0xfa

// Program state flags
int r = SUCCESS;
int verbatim = 0;
bool run = true;

struct jack_callback_arg {
    jack_port_t * output_port;
    char pad_map[NOF_PADS];
    bool pad_states[NOF_PADS];
    int loop_buffer;
};

libusb_device_handle * open_device(int vendor, int product);
static int process(jack_nframes_t nframes, void * arg);
static void signal_handler(int);
void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback);

int main (int ac, char ** av)
{
    int transfered;
    jack_nframes_t nframes;
    const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit";
    char * pad_str = NULL;

    libusb_device_handle * usb_drumkit_handle = NULL;
    jack_client_t * jack_midi_drum = NULL;
    volatile unsigned char raw[8];

    struct jack_callback_arg drumkit_callback;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_map[i] = 0x20 + i;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_states[i] = false;
    drumkit_callback.loop_buffer = 0;

    option_handler(ac, av, &drumkit_callback);

    r = libusb_init(NULL);
    if (r != SUCCESS) {
        std::cerr << "libusb_init: " << libusb_strerror((enum libusb_error)r) << "\n";
        return ERR_LIBUSB_SPECIFIC;
    }
    libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);
    usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID);
    if ( usb_drumkit_handle == NULL ) {
        std::cerr << "Unable to open drumkit! Probably it isn't connected.\n";
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }
    r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1);
    if (r != SUCCESS) {
        std::cerr << "libusb_set_auto_detach_kernel_driver: " << libusb_strerror((enum libusb_error)r) << "\n";
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }
    r = libusb_claim_interface(usb_drumkit_handle, 0);
    if (r != SUCCESS) {
        std::cerr << "libusb_claim_interface: " << libusb_strerror((enum libusb_error)r) << "\n";
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }

    jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL);
    if (jack_midi_drum == NULL) {
        std::cerr << "Unable to initiate jack client! Is JACK server running?\n";
        libusb_release_interface(usb_drumkit_handle, 0); // Check exit codes
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_JACK_SPECIFIC;
    }
    drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
    nframes = jack_get_buffer_size(jack_midi_drum);
    jack_set_process_callback(jack_midi_drum, process, &drumkit_callback);
    r = jack_activate(jack_midi_drum);
    if (r != SUCCESS) {
        std::cerr << "Cannot activate client --- " << r << "\n";
        jack_client_close(jack_midi_drum);
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_JACK_SPECIFIC;
    }

    signal(SIGQUIT, signal_handler);
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);

    while(run) {
        unsigned char p = 0;
        for(int i = 0; i <= drumkit_callback.loop_buffer; i++)
        {
            r = libusb_interrupt_transfer(usb_drumkit_handle, 0x81, (unsigned char*) raw, sizeof(raw), &transfered, 0);
            if(r >= 0) {
                if (transfered != sizeof(raw)) {
                    std::cerr << "Answer length mismatch.\n";
                    r = ERR_ANSWER_LENGTH_MISMATCH;
                    break;
                }
                for (int j = 0; j < transfered; j++)
                    p |= raw[j];
            }
            else {
                std::cerr << libusb_strerror((enum libusb_error)r) << ".\n";
                r = ERR_TRANSFER_FAILED;
                break;
            }
        }
        for (int i = 0; i < NOF_PADS; i++) {
            drumkit_callback.pad_states[i] = p & 1;
            p >>= 1;
        }
    }

    jack_deactivate(jack_midi_drum);
    jack_client_close(jack_midi_drum);
    libusb_release_interface(usb_drumkit_handle, 0);
    libusb_close(usb_drumkit_handle);
    libusb_exit(NULL);

    return r;
}

void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback)
{
    //FIXME I dont have enough stamina to write getopt, and I don't want getopt
    // to be larger than actual driver! I have a plan 'bout ultimate™ getopt,
    // but I don't think I'll make it soon... And yeah next routine is
    // dnagerous, but I like danger :P.
    char c;
    int p_tmp = -1;
    while ((c = getopt (ac, av, "hv:p:n:b:")) != -1) {
        switch (c) {
            case 'h':
                std::cout << "!!WARNING CODE IS VERY UNMATURE, INCORRECT VALUES WILL CAUSE UNPREDICTABLE RESULTS!!\n"
                    << "Usage:\n"
                    << "\t-h\t\tOutput this message and exit\n"
                    << "\t-v <level>\tVerbosity level (default 0)\n"
                    << "\t-p <number>\tAsign to pad 0..5\n"
                    << "\t-n <note>\tnote in range 0..127\n"
                    << "\t-b <integer>\t Select size of loop_buffer (default 0)\n";
                exit(0);
            case 'v':
                verbatim = atoi(optarg);
                break;
            case 'p':
                p_tmp = atoi(optarg);
                break;
            case 'n':
                drumkit_callback->pad_map[p_tmp]=atoi(optarg);
                break;
            case 'b':
                drumkit_callback->loop_buffer = atoi(optarg);
                break;
            case '?':
                exit(ERR_BAD_ARGUMENT);
            default:
                abort();
        }
    }
    if (verbatim)
        std::cout << "Selected loop_buffer: " << drumkit_callback->loop_buffer << std::endl;

    if (p_tmp != -1) {
        std::cout << "Reassigned mapping:";
        for(int q=0; q<NOF_PADS; q++)
            std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q];
        std::cout << std::endl;
    }
}

static void signal_handler(int sig)
{
    run = false;
    std::cerr << "Signal " << sig << " received, exiting ..." << std::endl;
}

static int process(jack_nframes_t nframes, void * arg)
{
    jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg;
    void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes);
    unsigned char * midi_buffer;
    jack_midi_clear_buffer(port_buf);
    static bool was_free[6];

    for (int i = 0; i < 6; i++)
    if (drumkit_callback.pad_states[i]) {
        if (was_free[i]) {
            was_free[i] = false;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x99;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x7F;
        }
    } else {
        if (!was_free[i]) {
            was_free[i] = true;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x89;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x00;
        }
    }

    return 0;
}

libusb_device_handle * open_device(int vendor, int product)
{
    libusb_device ** devices;
    libusb_device_descriptor desc;
    libusb_config_descriptor * config;
    libusb_device_handle * devh;
    int r;

    int cnt = libusb_get_device_list(NULL, &devices);
    if (cnt < 0) {
        std::cerr << "libusb_get_device_list: " << libusb_strerror((enum libusb_error)cnt) << "\n";
        return NULL;
    }

    for (int i = 0; i < cnt; i++) {
        libusb_get_device_descriptor(devices[i], &desc);
        if (desc.idVendor == vendor && desc.idProduct == product) {
            if (verbatim)
                std::cout << "Rollup Drumkit connected!\n";

            r = libusb_get_config_descriptor(devices[i], 0, &config);
            if (r < 0) {
                std::cerr << "libusb_get_config_descriptor: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }

            r = libusb_open(devices[i], &devh);
            if (r < 0) {
                std::cerr << "libusb_open: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
        }
    }
    libusb_free_device_list(devices, 1);
    return devh;
}

<commit_msg>Added version<commit_after>//% Rollup drumkit userspace driver
//% Alex Grabovski <hurufu@gmail.com>
//% 2014-04-21
//% WTFPL

#include <iostream>
#include <csignal>
#include <unistd.h>

#include <libusb.h>
#include <jack/jack.h>
#include <jack/midiport.h>

#define DRUMKIT_VENDOR_ID 0x1941
#define DRUMKIT_PRODUCT_ID 0x8021
#define VERSION 0.2

#define NOF_PADS 6

// Error codes
#define SUCCESS 0
#define ERR_ANSWER_LENGTH_MISMATCH 0xff
#define ERR_TRANSFER_FAILED 0xfe
#define ERR_LIBUSB_SPECIFIC 0xfd
#define ERR_JACK_SPECIFIC 0xfc
#define ERR_BAD_ARGUMENT 0xfb
#define ERR_UNKNOWN 0xfa

// Program state flags
int r = SUCCESS;
int verbatim = 0;
bool run = true;

struct jack_callback_arg {
    jack_port_t * output_port;
    char pad_map[NOF_PADS];
    bool pad_states[NOF_PADS];
    int loop_buffer;
};

libusb_device_handle * open_device(int vendor, int product);
static int process(jack_nframes_t nframes, void * arg);
static void signal_handler(int);
void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback);

int main (int ac, char ** av)
{
    int transfered;
    jack_nframes_t nframes;
    const char jack_midi_drum_str[] = "Dreamlink Foldup Drumk Kit";
    char * pad_str = NULL;

    libusb_device_handle * usb_drumkit_handle = NULL;
    jack_client_t * jack_midi_drum = NULL;
    volatile unsigned char raw[8];

    struct jack_callback_arg drumkit_callback;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_map[i] = 0x20 + i;
    for (int i=0; i < NOF_PADS; i++)
        drumkit_callback.pad_states[i] = false;
    drumkit_callback.loop_buffer = 0;

    option_handler(ac, av, &drumkit_callback);

    r = libusb_init(NULL);
    if (r != SUCCESS) {
        std::cerr << "libusb_init: " << libusb_strerror((enum libusb_error)r) << "\n";
        return ERR_LIBUSB_SPECIFIC;
    }
    libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);
    usb_drumkit_handle = open_device(DRUMKIT_VENDOR_ID, DRUMKIT_PRODUCT_ID);
    if ( usb_drumkit_handle == NULL ) {
        std::cerr << "Unable to open drumkit! Probably it isn't connected.\n";
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }
    r = libusb_set_auto_detach_kernel_driver(usb_drumkit_handle, 1);
    if (r != SUCCESS) {
        std::cerr << "libusb_set_auto_detach_kernel_driver: " << libusb_strerror((enum libusb_error)r) << "\n";
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }
    r = libusb_claim_interface(usb_drumkit_handle, 0);
    if (r != SUCCESS) {
        std::cerr << "libusb_claim_interface: " << libusb_strerror((enum libusb_error)r) << "\n";
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_LIBUSB_SPECIFIC;
    }

    jack_midi_drum = jack_client_open(jack_midi_drum_str, JackNullOption, NULL);
    if (jack_midi_drum == NULL) {
        std::cerr << "Unable to initiate jack client! Is JACK server running?\n";
        libusb_release_interface(usb_drumkit_handle, 0); // Check exit codes
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_JACK_SPECIFIC;
    }
    drumkit_callback.output_port = jack_port_register(jack_midi_drum, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
    nframes = jack_get_buffer_size(jack_midi_drum);
    jack_set_process_callback(jack_midi_drum, process, &drumkit_callback);
    r = jack_activate(jack_midi_drum);
    if (r != SUCCESS) {
        std::cerr << "Cannot activate client --- " << r << "\n";
        jack_client_close(jack_midi_drum);
        libusb_close(usb_drumkit_handle);
        libusb_exit(NULL);
        return ERR_JACK_SPECIFIC;
    }

    signal(SIGQUIT, signal_handler);
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);

    while(run) {
        unsigned char p = 0;
        for(int i = 0; i <= drumkit_callback.loop_buffer; i++)
        {
            r = libusb_interrupt_transfer(usb_drumkit_handle, 0x81, (unsigned char*) raw, sizeof(raw), &transfered, 0);
            if(r >= 0) {
                if (transfered != sizeof(raw)) {
                    std::cerr << "Answer length mismatch.\n";
                    r = ERR_ANSWER_LENGTH_MISMATCH;
                    break;
                }
                for (int j = 0; j < transfered; j++)
                    p |= raw[j];
            }
            else {
                std::cerr << libusb_strerror((enum libusb_error)r) << ".\n";
                r = ERR_TRANSFER_FAILED;
                break;
            }
        }
        for (int i = 0; i < NOF_PADS; i++) {
            drumkit_callback.pad_states[i] = p & 1;
            p >>= 1;
        }
    }

    jack_deactivate(jack_midi_drum);
    jack_client_close(jack_midi_drum);
    libusb_release_interface(usb_drumkit_handle, 0);
    libusb_close(usb_drumkit_handle);
    libusb_exit(NULL);

    return r;
}

void option_handler(int ac, char ** av, jack_callback_arg * drumkit_callback)
{
    //FIXME I dont have enough stamina to write getopt, and I don't want getopt
    // to be larger than actual driver! I have a plan 'bout ultimate™ getopt,
    // but I don't think I'll make it soon... And yeah next routine is
    // dnagerous, but I like danger :P.
    char c;
    int p_tmp = -1;
    while ((c = getopt (ac, av, "Vhv:p:n:b:")) != -1) {
        switch (c) {
            case 'V':
                std::cout << "Verison " << VERSION << std::endl;
                exit(0);
            case 'h':
                std::cout << "!!WARNING CODE IS VERY UNMATURE, INCORRECT VALUES WILL CAUSE UNPREDICTABLE RESULTS!!\n"
                    << "Usage:\n"
                    << "\t-h\t\tOutput this message and exit\n"
                    << "\t-v <level>\tVerbosity level (default 0)\n"
                    << "\t-p <number>\tAsign to pad 0..5\n"
                    << "\t-n <note>\tnote in range 0..127\n"
                    << "\t-b <integer>\t Select size of loop_buffer (default 0)\n";
                exit(0);
            case 'v':
                verbatim = atoi(optarg);
                break;
            case 'p':
                p_tmp = atoi(optarg);
                break;
            case 'n':
                drumkit_callback->pad_map[p_tmp]=atoi(optarg);
                break;
            case 'b':
                drumkit_callback->loop_buffer = atoi(optarg);
                break;
            case '?':
                exit(ERR_BAD_ARGUMENT);
            default:
                abort();
        }
    }
    if (verbatim)
        std::cout << "Selected loop_buffer: " << drumkit_callback->loop_buffer << std::endl;

    if (p_tmp != -1) {
        std::cout << "Reassigned mapping:";
        for(int q=0; q<NOF_PADS; q++)
            std::cout << "\tPad" << q << ": " << (int) drumkit_callback->pad_map[q];
        std::cout << std::endl;
    }
}

static void signal_handler(int sig)
{
    run = false;
    std::cerr << "Signal " << sig << " received, exiting ..." << std::endl;
}

static int process(jack_nframes_t nframes, void * arg)
{
    jack_callback_arg drumkit_callback = *(jack_callback_arg*) arg;
    void * port_buf = jack_port_get_buffer(drumkit_callback.output_port, nframes);
    unsigned char * midi_buffer;
    jack_midi_clear_buffer(port_buf);
    static bool was_free[6];

    for (int i = 0; i < 6; i++)
    if (drumkit_callback.pad_states[i]) {
        if (was_free[i]) {
            was_free[i] = false;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x99;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x7F;
        }
    } else {
        if (!was_free[i]) {
            was_free[i] = true;
            midi_buffer = jack_midi_event_reserve(port_buf, 0, 3);
            midi_buffer[0] = 0x89;
            midi_buffer[1] = drumkit_callback.pad_map[i];
            midi_buffer[2] = 0x00;
        }
    }

    return 0;
}

libusb_device_handle * open_device(int vendor, int product)
{
    libusb_device ** devices;
    libusb_device_descriptor desc;
    libusb_config_descriptor * config;
    libusb_device_handle * devh;
    int r;

    int cnt = libusb_get_device_list(NULL, &devices);
    if (cnt < 0) {
        std::cerr << "libusb_get_device_list: " << libusb_strerror((enum libusb_error)cnt) << "\n";
        return NULL;
    }

    for (int i = 0; i < cnt; i++) {
        libusb_get_device_descriptor(devices[i], &desc);
        if (desc.idVendor == vendor && desc.idProduct == product) {
            if (verbatim)
                std::cout << "Rollup Drumkit connected!\n";

            r = libusb_get_config_descriptor(devices[i], 0, &config);
            if (r < 0) {
                std::cerr << "libusb_get_config_descriptor: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }

            r = libusb_open(devices[i], &devh);
            if (r < 0) {
                std::cerr << "libusb_open: " << libusb_strerror((enum libusb_error)r) << "\n";
                return NULL;
            }
        }
    }
    libusb_free_device_list(devices, 1);
    return devh;
}

<|endoftext|>


<commit_before>e4552b51-ad5c-11e7-8804-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>e4a9f126-ad5c-11e7-9250-ac87a332f658<|endoftext|>


<commit_before>#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtCore/QStringList>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QPushButton>
#include <iostream>

using namespace std;

class CustomDialog : public QDialog
{
	public:
    CustomDialog(const QStringList& items)
    {
        setLayout(new QHBoxLayout());

        box = new QComboBox;
        box->addItems(items);
        layout()->addWidget(box);
		setWindowTitle("Wybierz port");
		resize(300,50);
        QPushButton* ok = new QPushButton("ok");
        layout()->addWidget(ok);
        connect(ok, &QPushButton::clicked, this, [this]()
        {
           accept();
        });
    }

    QComboBox* comboBox() { return box; }

	private:
    QComboBox* box;
};

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QSerialPort rs;
	QStringList itemList;
	Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
    {
        itemList<<port.portName();
        qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
    }
	CustomDialog dialog(itemList);
	if (dialog.exec() == QDialog::Accepted)
	{
		// take proper action here
		rs.setPortName(dialog.comboBox()->currentText());
	}

    QWidget w;
    w.resize(800,600);
    w.show();

    /*QComboBox box(&w);
    Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
    {
        box.addItem(port.portName());
    }
    box.move(10,10);*/

    //rs.setPortName(box.currentText());
    rs.open (QIODevice::ReadWrite);
	rs.setBaudRate (QSerialPort::Baud57600);
	rs.setDataBits (QSerialPort::Data8);
	rs.setStopBits (QSerialPort::OneStop);
	rs.setParity (QSerialPort::NoParity);
	rs.setFlowControl (QSerialPort::NoFlowControl);

    //box.show();

    cout<<rs.error()<<endl;

    rs.close();
    return a.exec();
}
<commit_msg>Porządki w kodzie.<commit_after>#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtCore/QStringList>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QPushButton>
#include <iostream>

using namespace std;

class CustomDialog : public QDialog
{
	public:
    CustomDialog(const QStringList& items)
    {
        setLayout(new QHBoxLayout());

        box = new QComboBox;
        box->addItems(items);
        layout()->addWidget(box);
		setWindowTitle("Wybierz port");
		resize(300,50);
        QPushButton* ok = new QPushButton("ok");
        layout()->addWidget(ok);
        connect(ok, &QPushButton::clicked, this, [this]()
        {
           accept();
        });
    }

    QComboBox* comboBox() { return box; }

	private:
    QComboBox* box;
};

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QSerialPort rs;
	QStringList itemList;
	Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
    {
        itemList<<port.portName();
        qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
    }
	CustomDialog dialog(itemList);
	if (dialog.exec() == QDialog::Accepted)
	{
		rs.setPortName(dialog.comboBox()->currentText());
	}

    QWidget w;
    w.resize(800,600);
    w.show();

    rs.open (QIODevice::ReadWrite);
	rs.setBaudRate (QSerialPort::Baud57600);
	rs.setDataBits (QSerialPort::Data8);
	rs.setStopBits (QSerialPort::OneStop);
	rs.setParity (QSerialPort::NoParity);
	rs.setFlowControl (QSerialPort::NoFlowControl);

    cout<<rs.error()<<endl;

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


<commit_before>96a584eb-4b02-11e5-b893-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>96b38c17-4b02-11e5-8e7b-28cfe9171a43<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "TiNetwork.h"

#include "TiSocketObject.h"
#include "TiHTTPClientObject.h"
#include "TiGenericFunctionObject.h"
#include "V8Utils.h"
#include <QUrl>

TiNetwork::TiNetwork()
    : TiProxy("Network")
{
    objectFactory_ = NULL;
}

TiNetwork::TiNetwork(NativeObjectFactory* objectFactory)
    : TiProxy("Network")
{
    objectFactory_ = objectFactory;
}

TiNetwork::~TiNetwork()
{
}

void TiNetwork::addObjectToParent(TiObject* parent, NativeObjectFactory* objectFactory)
{
    TiNetwork* obj = new TiNetwork(objectFactory);
    parent->addMember(obj);
    obj->setAttachedObject(parent);
    obj->release();
}

void TiNetwork::onCreateStaticMembers()
{
    TiProxy::onCreateStaticMembers();
    TiSocketObject::addObjectToParent(this, objectFactory_);
    TiHTTPClientObject::addObjectToParent(this, objectFactory_);
    // TODO: Add class methods, constants, properties
    TiGenericFunctionObject::addGenericFunctionToParent(this, "createHTTPClient", this, _createHTTPClient);
    TiGenericFunctionObject::addGenericFunctionToParent(this, "encodeURIComponent", this, _encodeURIComponent);

}

Handle<Value> TiNetwork::_encodeURIComponent(void* userContext, TiObject* /*caller*/, const Arguments& args)
{
	HandleScope scope;
	if(args.Length() > 0 && args[0]->IsString())
	{
		QByteArray url = QUrl::toPercentEncoding(titanium::V8ValueToQString(args[0]));
		return scope.Close(String::New(url.data()));
	}
	return Undefined();
}

Handle<Value> TiNetwork::_createHTTPClient(void* userContext, TiObject* /*caller*/, const Arguments& args)
{
    HandleScope handleScope;
    TiNetwork* obj = (TiNetwork*) userContext;
    Handle<ObjectTemplate> global = getObjectTemplateFromJsObject(args.Holder());
    Handle<Object> result = global->NewInstance();
    TiHTTPClientObject* newHTTP = TiHTTPClientObject::createHTTPClient(obj->objectFactory_);
    newHTTP->setValue(result);
    if ((args.Length() > 0) && (args[0]->IsObject()))
    {
        Local<Object> settingsObj = Local<Object>::Cast(args[0]);
        newHTTP->setParametersFromObject(newHTTP, settingsObj);
    }
    setTiObjectToJsObject(result, newHTTP);
    return handleScope.Close(result);
}

<commit_msg>[TIMOB-14442] Added networkType and networkTypeName to Ti.Network<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "TiNetwork.h"

#include "TiSocketObject.h"
#include "TiHTTPClientObject.h"
#include "TiGenericFunctionObject.h"
#include "TiPropertySetGetObject.h"
#include <QNetworkConfigurationManager>
#include "V8Utils.h"
#include <QUrl>

TiNetwork::TiNetwork()
    : TiProxy("Network")
{
    objectFactory_ = NULL;
}

TiNetwork::TiNetwork(NativeObjectFactory* objectFactory)
    : TiProxy("Network")
{
    objectFactory_ = objectFactory;
}

TiNetwork::~TiNetwork()
{
}

void TiNetwork::addObjectToParent(TiObject* parent, NativeObjectFactory* objectFactory)
{
    TiNetwork* obj = new TiNetwork(objectFactory);
    parent->addMember(obj);
    obj->setAttachedObject(parent);
    obj->release();
}

static Handle<Value> _getNetworkType(void*)
{
    QNetworkConfigurationManager *qncm = new QNetworkConfigurationManager();
    QList<QNetworkConfiguration> activeConfigs = qncm->allConfigurations(QNetworkConfiguration::Active);
    foreach (QNetworkConfiguration qnc, activeConfigs){
    	int type = 0;
    	switch(qnc.bearerType())
    	{
    	    case QNetworkConfiguration::BearerUnknown	: type = 0; break;
    	    case QNetworkConfiguration::BearerEthernet	: type = 1; break;
    	    case QNetworkConfiguration::BearerWLAN		: type = 2; break;
    	    case QNetworkConfiguration::Bearer2G		: type = 3; break;
    	    case QNetworkConfiguration::BearerCDMA2000	: type = 4; break;
    	    case QNetworkConfiguration::BearerWCDMA		: type = 5; break;
    	    case QNetworkConfiguration::BearerHSPA		: type = 6; break;
    	    case QNetworkConfiguration::BearerBluetooth	: type = 7; break;

    	}
    	return Number::New(type);
    }
    return Null();

}

static Handle<Value> _getNetworkTypeName(void*)
{
    QNetworkConfigurationManager *qncm = new QNetworkConfigurationManager();
    QList<QNetworkConfiguration> activeConfigs = qncm->allConfigurations(QNetworkConfiguration::Active);
    foreach (QNetworkConfiguration qnc, activeConfigs){
    	QString typeName = qnc.bearerTypeName();
    	return String::New(typeName.toLocal8Bit().constData());
    }
    return Null();

}

void TiNetwork::onCreateStaticMembers()
{
    TiProxy::onCreateStaticMembers();
    TiSocketObject::addObjectToParent(this, objectFactory_);
    TiHTTPClientObject::addObjectToParent(this, objectFactory_);
    // TODO: Add class methods, constants, properties
    TiGenericFunctionObject::addGenericFunctionToParent(this, "createHTTPClient", this, _createHTTPClient);
    TiGenericFunctionObject::addGenericFunctionToParent(this, "encodeURIComponent", this, _encodeURIComponent);

    TiPropertySetGetObject::createProperty(this, "networkTypeName", this, NULL, _getNetworkTypeName);
    TiPropertySetGetObject::createProperty(this, "networkType", this, NULL, _getNetworkType);
}

Handle<Value> TiNetwork::_encodeURIComponent(void* userContext, TiObject* /*caller*/, const Arguments& args)
{
	HandleScope scope;
	if(args.Length() > 0 && args[0]->IsString())
	{
		QByteArray url = QUrl::toPercentEncoding(titanium::V8ValueToQString(args[0]));
		return scope.Close(String::New(url.data()));
	}
	return Undefined();
}

Handle<Value> TiNetwork::_createHTTPClient(void* userContext, TiObject* /*caller*/, const Arguments& args)
{
    HandleScope handleScope;
    TiNetwork* obj = (TiNetwork*) userContext;
    Handle<ObjectTemplate> global = getObjectTemplateFromJsObject(args.Holder());
    Handle<Object> result = global->NewInstance();
    TiHTTPClientObject* newHTTP = TiHTTPClientObject::createHTTPClient(obj->objectFactory_);
    newHTTP->setValue(result);
    if ((args.Length() > 0) && (args[0]->IsObject()))
    {
        Local<Object> settingsObj = Local<Object>::Cast(args[0]);
        newHTTP->setParametersFromObject(newHTTP, settingsObj);
    }
    setTiObjectToJsObject(result, newHTTP);
    return handleScope.Close(result);
}

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Alex Palcuie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

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

#include <string>
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stdexcept>

using std::string;
using std::to_string;
using std::reverse;
using std::vector;

class BigNumber {
  public:
    vector<char> integerPart, fractionaryPart;
    bool sign = 0;

    explicit BigNumber(int x) : BigNumber(to_string(x)) { }
    BigNumber(int integerPart, int fractionaryPart) :
        BigNumber(to_string(integerPart) + "." + to_string(fractionaryPart)) { }

    explicit BigNumber(string v) {
        int i = 0;
        if (v[i] == '-') {
            sign = 1;
            i++;
        }
        while (i < v.size()) {
            if (isdigit(v[i])) {
                integerPart.push_back(v[i]);
            } else {
                if (v[i] != '.')
                    throw std::runtime_error("NaN");
                break;
            }
            i++;
        }
        if (v[i] == '.') {
            i++;
            while (i < v.size()) {
                if (isdigit(v[i]))
                    fractionaryPart.push_back(v[i]);
                else
                    throw std::runtime_error("NaN");
                i++;
            }
        }
        reverse(integerPart.begin(), integerPart.end());
        if (fractionaryPart.size())
            reverse(fractionaryPart.begin(), fractionaryPart.end());
    }

    string toString() {
        string answer;
        if (sign)
            answer += "-";
        string x = string(integerPart.data(), integerPart.size());
        reverse(x.begin(), x.end());
        answer += x;
        if (fractionaryPart.size()) {
            answer += ".";
            string x = string(fractionaryPart.data(), fractionaryPart.size());
            reverse(x.begin(), x.end());
            answer += x;
        }
        return answer;
    }

    void plus_one() {
        int i = 0;
        while (integerPart[i] == '9' && integerPart.size() > i) {
            // printf("i = %d\n", i);
            integerPart[i] = '0';
            i++;
        }
        if (integerPart.size() == i)
            integerPart.push_back('1');
        else
            integerPart[i]++;
    }

    void add(BigNumber x) {
        reverse(x.fractionaryPart.begin(), x.fractionaryPart.end());

        bool carry = 0;
        std::tie(carry, fractionaryPart) = addTwoVectors(fractionaryPart,
                                                         x.fractionaryPart);
        if (carry)
            plus_one();
        std::tie(carry, integerPart) = addTwoVectors(integerPart,
                                                     x.integerPart);
        if (carry)
            integerPart.push_back('1');
    }

  private:
    const int BASE = 10;

    std::tuple<bool, vector<char>> addTwoVectors(vector<char> base,
                                                 vector<char> visitor) {
        // TODO(alex): change these reverses
        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        while (base.size() < visitor.size())
            base.push_back('0');
        while (visitor.size() < base.size())
            visitor.push_back('0');

        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        bool carry = 0;
        for (int i = 0; i < base.size(); i++) {
            base[i] += visitor[i] + carry - '0';
            if (base[i] > '9') {
                carry = 1;
                base[i] -= '9';
            } else {
                carry = 0;
            }
        }

        return make_tuple(carry, base);
    }
};

int main() {
    assert(BigNumber(6, 9).toString() == "6.9");
    assert(BigNumber(3).toString() == "3");
    assert(BigNumber(-5).toString() == "-5");

    vector<string> v = {"10", "10.3", "-10.555", "69.34433434", "0", "2"};

    for (int i = 0; i < v.size(); i++)
        assert(BigNumber(v[i]).toString() == v[i]);

    BigNumber nineteen = BigNumber(19);
    nineteen.plus_one();
    assert(nineteen.toString() == "20");

    BigNumber x = BigNumber(8);
    x.plus_one();
    assert(x.toString() == "9");
    x.plus_one();
    assert(x.toString() == "10");
    BigNumber y = BigNumber("10.6");
    y.plus_one();
    assert(y.toString() == "11.6");

    BigNumber ten = BigNumber("5.1");
    ten.add(BigNumber("3.2"));
    assert(ten.toString() == "8.3");

    return 0;
}
<commit_msg>Fix the add<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Alex Palcuie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

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

#include <string>
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stdexcept>

using std::string;
using std::to_string;
using std::reverse;
using std::vector;

class BigNumber {
  public:
    vector<char> integerPart, fractionaryPart;
    bool sign = 0;

    explicit BigNumber(int x) : BigNumber(to_string(x)) { }
    BigNumber(int integerPart, int fractionaryPart) :
        BigNumber(to_string(integerPart) + "." + to_string(fractionaryPart)) { }

    explicit BigNumber(string v) {
        int i = 0;
        if (v[i] == '-') {
            sign = 1;
            i++;
        }
        while (i < v.size()) {
            if (isdigit(v[i])) {
                integerPart.push_back(v[i]);
            } else {
                if (v[i] != '.')
                    throw std::runtime_error("NaN");
                break;
            }
            i++;
        }
        if (v[i] == '.') {
            i++;
            while (i < v.size()) {
                if (isdigit(v[i]))
                    fractionaryPart.push_back(v[i]);
                else
                    throw std::runtime_error("NaN");
                i++;
            }
        }
        reverse(integerPart.begin(), integerPart.end());
        if (fractionaryPart.size())
            reverse(fractionaryPart.begin(), fractionaryPart.end());
    }

    string toString() {
        string answer;
        if (sign)
            answer += "-";
        string x = string(integerPart.data(), integerPart.size());
        reverse(x.begin(), x.end());
        answer += x;
        if (fractionaryPart.size()) {
            answer += ".";
            string x = string(fractionaryPart.data(), fractionaryPart.size());
            reverse(x.begin(), x.end());
            answer += x;
        }
        return answer;
    }

    void plus_one() {
        int i = 0;
        while (integerPart[i] == '9' && integerPart.size() > i) {
            // printf("i = %d\n", i);
            integerPart[i] = '0';
            i++;
        }
        if (integerPart.size() == i)
            integerPart.push_back('1');
        else
            integerPart[i]++;
    }

    void add(BigNumber x) {
        bool carry = 0;
        std::tie(carry, fractionaryPart) = addTwoVectors(fractionaryPart,
                                                         x.fractionaryPart);
        if (carry)
            plus_one();
        std::tie(carry, integerPart) = addTwoVectors(integerPart,
                                                     x.integerPart);
        if (carry)
            integerPart.push_back('1');
    }

  private:
    const int BASE = 10;

    std::tuple<bool, vector<char>> addTwoVectors(vector<char> base,
                                                 vector<char> visitor) {
        // TODO(alex): change these reverses
        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        while (base.size() < visitor.size())
            base.push_back('0');
        while (visitor.size() < base.size())
            visitor.push_back('0');

        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        bool carry = 0;
        for (int i = 0; i < base.size(); i++) {
            base[i] += visitor[i] + carry - '0';
            if (base[i] > '9') {
                carry = 1;
                base[i] -= '9';
            } else {
                carry = 0;
            }
        }

        return make_tuple(carry, base);
    }
};

int main() {
    assert(BigNumber(6, 9).toString() == "6.9");
    assert(BigNumber(3).toString() == "3");
    assert(BigNumber(-5).toString() == "-5");

    vector<string> v = {"10", "10.3", "-10.555", "69.34433434", "0", "2"};

    for (int i = 0; i < v.size(); i++)
        assert(BigNumber(v[i]).toString() == v[i]);

    BigNumber nineteen = BigNumber(19);
    nineteen.plus_one();
    assert(nineteen.toString() == "20");

    BigNumber x = BigNumber(8);
    x.plus_one();
    assert(x.toString() == "9");
    x.plus_one();
    assert(x.toString() == "10");
    BigNumber y = BigNumber("10.6");
    y.plus_one();
    assert(y.toString() == "11.6");

    BigNumber ten = BigNumber("5.1");
    ten.add(BigNumber("3.2"));
    assert(ten.toString() == "8.3");

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <vector>
#include "gen.hpp"
#include "info.hpp"
//Shark package manager

//Shamelessy stolen from some stack overflow thread
char* getField(char** begin, char** end, const std::string& option)
{
	char** itr = std::find(begin, end, option);

	if(itr != end && ++itr != end)
	{
		return *itr;
	}
	return 0;
}

bool getFlag(char** begin, char** end, const std::string& option)
{
	return std::find(begin, end, option) != end;
}

std::string root;
int Install(std::string package);
int main(int argc, char* argv[])
{
	//Set the default values
	root="/";
	if(getFlag(argv, argv+argc, "--root"))
	{
		root = (std::string)getField(argv, argv+argc, "--root");
		std::cout << "Using " << root << " as /\n";
	}
	if(root == "/")
	{
		std::cout << "Error: no fake root set (safe mode)\n";
		return 1;
	}
	if(getFlag(argv, argv+argc, "-I"))
	{
		return Install(getField(argv, argv+argc, "-I"));
	}
	if(getFlag(argv, argv+argc, "--gen-dirs"))
	{
		GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), "");
	}
	if(getFlag(argv, argv+argc, "--gen-links"))
	{
		GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p"));
	}
	if(getFlag(argv, argv+argc, "--gen-files"))
	{
		GenFiles(root, getField(argv, argv+argc, "--gen-files"), "");
	}
	if(getFlag(argv, argv+argc, "--nuke"))
	{
		if(root == "/")
		{
			std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n";
			return 1;
		}
		std::stringstream nukecmd;
		nukecmd << "rm -rf " << root << "*";
		//std::cout << nukecmd.str() << std::endl;
		system(nukecmd.str().c_str());
	}
	return 0;
}

int Install(std::string package)
{
	//untar a file into /usr/pkg
	std::cout << "Extracting tarball\n";
	std::stringstream tarball;
	tarball << "tar xf " << package  << " -C "<< root << "usr/pkg";
	if(system(tarball.str().c_str()))
	{
		return 1;
	}
	std::string packagename = package;
	int slash = packagename.find_last_of("/");
	if(slash)
	{
		packagename = package.substr(slash+1);
	}
	int dot = packagename.find(".tar");
	if(dot)
	{
		packagename = packagename.substr(0, dot);
	}
	std::cout << "Verifying the package (not really)\n";
	std::cout << "Loading the package info\n";
	std::stringstream infofile;
	infofile << root << "usr/pkg/" << packagename << "/info";
	int res;
	std::map<std::string, std::string> info = LoadInfo(infofile.str(), res);
	if(res != 0)
		return res;
	std::string pkgname = info["PKG_NAME"];
	std::string ver = info["PKG_VER"];
	std::cout << "Loading the file list\n";
	std::vector<std::string> filelist;
	std::ifstream files;
	std::stringstream filesfile;
	filesfile << root << "usr/pkg/" << packagename << "/files";
	files.open(filesfile.str().c_str());
	if(!files.is_open())
	{
		std::cout << "Error: no file list found. Malformed packge\n";
		return 1;
	}
	std::string line;
	while(files.good())
	{
		std::getline(files, line);
		if(line == "EOF")
			break;
		filelist.push_back(line);
	}
	files.close();

	std::cout << "Looking for conflicts\n";
	for(int i = 0; i < filelist.size(); i++)
	{
		std::stringstream filename;
		filename << root << "usr/pkgdb/" << filelist[i];
		std::ifstream f;
		f.open(filename.str().c_str());
		if(f.is_open())
		{
			//we are probably conflicting, but make sure
			std::string pkg;
			getline(f, pkg);
			if(pkg != pkgname)
			{
				std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n";
				return 1;
			}
		}
	}
	std::cout << "Installing package " << packagename << std::endl;
	//TODO:load the info file, add it to the package DB
	//make the directories from dirs
	std::ifstream dirs;
	std::stringstream dirsfile;
	dirsfile << root << "usr/pkg/" << packagename << "/dirs";
	dirs.open(dirsfile.str().c_str());
	if(dirs.is_open()) //assume that nothing needs to be made if there is no file
	{
		std::string dir;
		while(dirs.good())
		{
			std::getline(dirs, dir);
			if(dir == "EOF")
				break;
			std::stringstream d;
			d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir;
			system(d.str().c_str());
		}
	}
	//copy any files that need copying
	for(int i=0; i < filelist.size(); i++)
	{
		std::stringstream f;
		f << "cp -fd " << root << "usr/pkg/" << packagename << "/" << filelist[i] << " " << root << filelist[i];
		//std::cout << f.str() << std::endl;
		system(f.str().c_str());
		//update the package db
		std::stringstream dbcmd;
		dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i];
		//std::cout << dbcmd.str() << "\n";
		system(dbcmd.str().c_str());
	}
	//install the info file
	std::stringstream infocmd;
	infocmd << "cp -fd " << root << "usr/pkg/" << packagename << "/info " << root << "usr/pkg/" << pkgname;
	//std::cout << infocmd.str() << std::endl;
	system(infocmd.str().c_str());
	files.close();
	return 0;
}
<commit_msg>Changed the way to install packages. Use -UI to untar and install a package<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <vector>
#include "gen.hpp"
#include "info.hpp"
//Shark package manager

//Shamelessy stolen from some stack overflow thread
char* getField(char** begin, char** end, const std::string& option)
{
	char** itr = std::find(begin, end, option);

	if(itr != end && ++itr != end)
	{
		return *itr;
	}
	return 0;
}

bool getFlag(char** begin, char** end, const std::string& option)
{
	return std::find(begin, end, option) != end;
}

std::string root;
int Install(std::string package);
int Untar(std::string tarball);
int Download(std::string package, std::string ver = "");
int main(int argc, char* argv[])
{
	//Set the default values
	root="/";
	if(getFlag(argv, argv+argc, "--root"))
	{
		root = (std::string)getField(argv, argv+argc, "--root");
		std::cout << "Using " << root << " as /\n";
	}
	if(root == "/")
	{
		std::cout << "Error: no fake root set (safe mode)\n";
		return 1;
	}
	if(getFlag(argv, argv+argc, "-U"))
	{
		return Untar(getField(argv, argv+argc, "-U"));
	}
	if(getFlag(argv, argv+argc, "-UI"))
	{
		std::string pkg = getField(argv, argv+argc, "-UI");
		if(Untar(pkg) != 0)
		{
			return 1;
		}
		int slash = pkg.find_last_of("/");
		if(slash != std::string::npos)
		{
			pkg = pkg.substr(slash+1);
		}
		int dot = pkg.find(".tar");
		if(dot != std::string::npos)
		{
			pkg = pkg.substr(0, dot);
		}
		return Install(pkg);
	}
	if(getFlag(argv, argv+argc, "-I"))
	{
		return Install(getField(argv, argv+argc, "-I"));
	}
	if(getFlag(argv, argv+argc, "--gen-dirs"))
	{
		GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), "");
	}
	if(getFlag(argv, argv+argc, "--gen-links"))
	{
		GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p"));
	}
	if(getFlag(argv, argv+argc, "--gen-files"))
	{
		GenFiles(root, getField(argv, argv+argc, "--gen-files"), "");
	}
	if(getFlag(argv, argv+argc, "--nuke"))
	{
		if(root == "/")
		{
			std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n";
			return 1;
		}
		std::stringstream nukecmd;
		nukecmd << "rm -rf " << root << "*";
		//std::cout << nukecmd.str() << std::endl;
		system(nukecmd.str().c_str());
	}
	return 0;
}

int Install(std::string package)
{
	std::cout << "Verifying the package (not really)\n";
	std::cout << "Loading the package info\n";
	std::stringstream infofile;
	infofile << root << "usr/pkg/" << package << "/info";
	int res;
	std::map<std::string, std::string> info = LoadInfo(infofile.str(), res);
	if(res != 0)
		return res;
	std::string pkgname = info["PKG_NAME"];
	std::string ver = info["PKG_VER"];
	std::cout << "Loading the file list\n";
	std::vector<std::string> filelist;
	std::ifstream files;
	std::stringstream filesfile;
	filesfile << root << "usr/pkg/" << package << "/files";
	files.open(filesfile.str().c_str());
	if(!files.is_open())
	{
		std::cout << "Error: no file list found. Malformed packge\n";
		return 1;
	}
	std::string line;
	while(files.good())
	{
		std::getline(files, line);
		if(line == "EOF")
			break;
		filelist.push_back(line);
	}
	files.close();

	std::cout << "Looking for conflicts\n";
	for(int i = 0; i < filelist.size(); i++)
	{
		std::stringstream filename;
		filename << root << "usr/pkgdb/" << filelist[i];
		std::ifstream f;
		f.open(filename.str().c_str());
		if(f.is_open())
		{
			//we are probably conflicting, but make sure
			std::string pkg;
			getline(f, pkg);
			if(pkg != pkgname)
			{
				std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n";
				return 1;
			}
		}
	}
	std::cout << "Installing package " << package << std::endl;
	//TODO:load the info file, add it to the package DB
	//make the directories from dirs
	std::ifstream dirs;
	std::stringstream dirsfile;
	dirsfile << root << "usr/pkg/" << package << "/dirs";
	dirs.open(dirsfile.str().c_str());
	if(dirs.is_open()) //assume that nothing needs to be made if there is no file
	{
		std::string dir;
		while(dirs.good())
		{
			std::getline(dirs, dir);
			if(dir == "EOF")
				break;
			std::stringstream d;
			d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir;
			system(d.str().c_str());
		}
	}
	//copy any files that need copying
	for(int i=0; i < filelist.size(); i++)
	{
		std::stringstream f;
		f << "cp -fd " << root << "usr/pkg/" << package << "/" << filelist[i] << " " << root << filelist[i];
		//std::cout << f.str() << std::endl;
		system(f.str().c_str());
		//update the package db
		std::stringstream dbcmd;
		dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i];
		//std::cout << dbcmd.str() << "\n";
		system(dbcmd.str().c_str());
	}
	//install the info file
	std::stringstream infocmd;
	infocmd << "cp -fd " << root << "usr/pkg/" << package << "/info " << root << "usr/pkg/" << pkgname;
	//std::cout << infocmd.str() << std::endl;
	system(infocmd.str().c_str());
	files.close();
	return 0;
}

int Untar(std::string tarball)
{
	std::cout << "Extracting tarball\n";
	std::stringstream tar;
	tar << "tar xf " << tarball << " -C "<< root << "usr/pkg";
	if(system(tar.str().c_str()))
	{
		return 1;
	}
	return 0;
}
<|endoftext|>


<commit_before>d38c04ae-2747-11e6-8e83-e0f84713e7b8<commit_msg>Typical bobby<commit_after>d3988121-2747-11e6-9d6b-e0f84713e7b8<|endoftext|>


<commit_before>#pragma once
#include "game_framework/bind_game_framework_and_augs.h"
#include "augs/augmentations.h"
#include "game_framework/game_overworld.h"

using namespace augs;

#include "game_framework/scene_builders/testbed.h"

int main(int argc, char** argv) {
	augs::init();
	//augs::run_tests();

	game_overworld hypersomnia_overworld;
	hypersomnia_overworld.configure_scripting();
	hypersomnia_overworld.call_window_script("config.lua");

	hypersomnia_overworld.set_scene_builder(std::unique_ptr<scene_builder>(new scene_builders::testbed));
	hypersomnia_overworld.initialize_scene();

	hypersomnia_overworld.main_game_loop();

	augs::deinit();
	return 0;
}<commit_msg>run tests<commit_after>#pragma once
#include "game_framework/bind_game_framework_and_augs.h"
#include "augs/augmentations.h"
#include "game_framework/game_overworld.h"

using namespace augs;

#include "game_framework/scene_builders/testbed.h"

int main(int argc, char** argv) {
	augs::init();
	augs::run_tests();

	game_overworld hypersomnia_overworld;
	hypersomnia_overworld.configure_scripting();
	hypersomnia_overworld.call_window_script("config.lua");

	hypersomnia_overworld.set_scene_builder(std::unique_ptr<scene_builder>(new scene_builders::testbed));
	hypersomnia_overworld.initialize_scene();

	hypersomnia_overworld.main_game_loop();

	augs::deinit();
	return 0;
}<|endoftext|>


<commit_before>#include <rapp-robots-api/vision/vision.hpp>
#include <rapp-robots-api/communication/communication.hpp>
#include <rapp-robots-api/navigation/navigation.hpp>

#include <opencv2/opencv.hpp>

//#define DEBUG

#ifdef DEBUG
#define SHOW_DBG_PIC(x) cv::imshow("Out", x); cv::waitKey(-1);
#else
#define SHOW_DBG_PIC(x) ;
#endif

namespace rr = rapp::robot;

int main(int argc, char * argv[]) {
	rr::communication com(argc, argv);
	rr::vision vis(argc, argv);
	rr::navigation nav(argc, argv);

	// load camera info for default/main/front-facing camera
	rr::vision::camera_info cam = vis.load_camera_info(0);

	// inform user
	com.text_to_speech("Give me a second...");

	// take picture of empty scene
	auto picture = vis.capture_image(0, rapp::robot::vision::vga4, "png");
	cv::Mat bg = cv::imdecode(picture->bytearray(), -1);

	// inform user
	com.text_to_speech("Put object on scene and say OK");
	std::string word;
	do {
		word = com.word_spotting( { "ok" } );
	} while (word!="ok");

	// take picture of scene with object
	picture = vis.capture_image(0, rapp::robot::vision::vga4, "png");
	cv::Mat fg = cv::imdecode(picture->bytearray(), -1);

	if (fg.empty() || bg.empty()) {
		std::cerr << "No input files\n";
		com.text_to_speech("Sorry, something went wrong.");
		return 0;
	}

	cv::Mat diff = (bg - fg) + (fg - bg);

	SHOW_DBG_PIC(diff);

	cv::cvtColor(diff, diff, CV_BGR2GRAY);

	SHOW_DBG_PIC(diff);

	cv::threshold(diff, diff, 64, 255, cv::THRESH_BINARY);

	SHOW_DBG_PIC(diff);

	std::vector< std::vector<cv::Point> > contours;
	std::vector<cv::Vec4i> hierarchy;

	cv::findContours( diff, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

	cv::Rect bounding_rect;
	float max_area = 0;
	for( size_t i = 0; i < contours.size(); i++ ) {
		if (cv::contourArea(contours[i]) > max_area) {
			max_area = cv::contourArea(contours[i]);
			bounding_rect = cv::boundingRect( cv::Mat(contours[i]) );
		}
	}

	cv::imwrite("new_object_cut.png", fg(bounding_rect));
	cv::rectangle(fg, bounding_rect.tl(), bounding_rect.br(), cv::Scalar(255, 0, 0), 2, 8, 0);

	SHOW_DBG_PIC(fg);

	cv::imwrite("new_object.png", fg);

	com.text_to_speech("Great, I know new object!");

	return 0;
}
<commit_msg>Move head<commit_after>#include <rapp-robots-api/vision/vision.hpp>
#include <rapp-robots-api/communication/communication.hpp>
#include <rapp-robots-api/navigation/navigation.hpp>

#include <opencv2/opencv.hpp>

//#define DEBUG

#ifdef DEBUG
#define SHOW_DBG_PIC(x) cv::imshow("Out", x); cv::waitKey(-1);
#else
#define SHOW_DBG_PIC(x) ;
#endif

namespace rr = rapp::robot;

int main(int argc, char * argv[]) {
	rr::communication com(argc, argv);
	rr::vision vis(argc, argv);
	rr::navigation nav(argc, argv);

	// look straight ahead
	nav.move_joint({"Head"}, {0.0f, 0.0f}, 0.5);

	// load camera info for default/main/front-facing camera
	rr::vision::camera_info cam = vis.load_camera_info(0);

	// inform user
	com.text_to_speech("Give me a second...");

	// take picture of empty scene
	auto picture = vis.capture_image(0, rapp::robot::vision::vga4, "png");
	cv::Mat bg = cv::imdecode(picture->bytearray(), -1);

	// inform user
	com.text_to_speech("Put object on scene and say OK");
	std::string word;
	do {
		word = com.word_spotting( { "ok" } );
	} while (word!="ok");

	// take picture of scene with object
	picture = vis.capture_image(0, rapp::robot::vision::vga4, "png");
	cv::Mat fg = cv::imdecode(picture->bytearray(), -1);

	if (fg.empty() || bg.empty()) {
		std::cerr << "No input files\n";
		com.text_to_speech("Sorry, something went wrong.");
		return 0;
	}

	cv::Mat diff = (bg - fg) + (fg - bg);

	SHOW_DBG_PIC(diff);

	cv::cvtColor(diff, diff, CV_BGR2GRAY);

	SHOW_DBG_PIC(diff);

	cv::threshold(diff, diff, 64, 255, cv::THRESH_BINARY);

	SHOW_DBG_PIC(diff);

	std::vector< std::vector<cv::Point> > contours;
	std::vector<cv::Vec4i> hierarchy;

	cv::findContours( diff, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

	cv::Rect bounding_rect;
	float max_area = 0;
	for( size_t i = 0; i < contours.size(); i++ ) {
		if (cv::contourArea(contours[i]) > max_area) {
			max_area = cv::contourArea(contours[i]);
			bounding_rect = cv::boundingRect( cv::Mat(contours[i]) );
		}
	}

	cv::imwrite("new_object_cut.png", fg(bounding_rect));
	cv::rectangle(fg, bounding_rect.tl(), bounding_rect.br(), cv::Scalar(255, 0, 0), 2, 8, 0);

	SHOW_DBG_PIC(fg);

	cv::imwrite("new_object.png", fg);

	com.text_to_speech("Great, I know new object!");

	// crouch and turn off all the motors
	nav.rest("Crouch");

	return 0;
}
<|endoftext|>


<commit_before>74f74185-ad58-11e7-ac95-ac87a332f658<commit_msg>My Backup<commit_after>755cfd11-ad58-11e7-8d83-ac87a332f658<|endoftext|>


<commit_before>/*
     Copyright (C) 2014 Muller Romain

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QFileDialog>
#include <QtGui/QImage>

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

    QDialog *win = new QDialog;

    QString ImgI = QFileDialog::getOpenFileName(win, "Choisir l'image à convertire", QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), "Images (*.png *.jpg *.jpeg)");

    if(ImgI.isEmpty() || ImgI.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouvée !", "Impossible de trouvée le fichier !");
        exit(EXIT_FAILURE);
    }

     QString ImgO = QFileDialog::getSaveFileName(win, "Choisir l'emplacement de sauvegarde", ImgI, "Images (*.png *.jpg *.jpeg)");

    if(ImgO.isEmpty() || ImgO.isNull())
    {
        ImgO = ImgI;
    }

    QImage tmpImg(ImgI);

    for(int x(0); x < tmpImg.width(); x++)
    {
        for(int y(0); y < tmpImg.height(); y++)
        {
            QRgb rgb = tmpImg.pixel(x, y);

            if(rgb > 0xFFC8C8C8)
            {
                tmpImg.setPixel(x, y, 0xFFFFFF);
            }
        }
    }

    tmpImg.save(ImgO);

    QMessageBox::information(win, "Yeah !", "Finis !");

    exit(EXIT_SUCCESS);

    return app.exec();
}
<commit_msg>Add error manager on main.cpp<commit_after>/*
     Copyright (C) 2014 Muller Romain

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QFileDialog>
#include <QtGui/QImage>

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

    QDialog *win = new QDialog;

    QString ImgI = QFileDialog::getOpenFileName(win, "Choisir l'image à convertire", QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), "Images (*.png *.jpg *.jpeg)");

    if(ImgI.isEmpty() || ImgI.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouvée !", "Impossible de trouvée le fichier !");
        exit(EXIT_FAILURE);
    }

     QString ImgO = QFileDialog::getSaveFileName(win, "Choisir l'emplacement de sauvegarde", ImgI, "Images (*.png *.jpg *.jpeg)");

    if(ImgO.isEmpty() || ImgO.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouvée !", "Impossible de trouvée le fichier !");
        exit(EXIT_FAILURE);
    }

    QImage tmpImg(ImgI);

    for(int x(0); x < tmpImg.width(); x++)
    {
        for(int y(0); y < tmpImg.height(); y++)
        {
            QRgb rgb = tmpImg.pixel(x, y);

            if(rgb > 0xFFC8C8C8)
            {
                tmpImg.setPixel(x, y, 0xFFFFFF);
            }
        }
    }

    tmpImg.save(ImgO);

    QMessageBox::information(win, "Yeah !", "Finis !");

    exit(EXIT_SUCCESS);

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


<commit_before>#include <iostream>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "lib/TriangleMesh.hpp"
#include "lib/Object.hpp"

#include "file_format/HPIFile.hpp"

bool quit = false;
Matrix ProjectionMatrix;
Object * TempObj[9];
ShaderProgram * DefaultShaders;

const int ScreenWidth=640;
const int ScreenHeight=480;

TriangleMesh * CreateCubeMesh();
/**
* Log an SDL error with some error message to the output stream of our choice
* @param os The output stream to write the message too
* @param msg The error message to write, format will be msg error: SDL_GetError()
*/
void logSDLError(std::ostream &os, const std::string &msg)
{
    os << msg << " error: " << SDL_GetError() << std::endl;
}

void handleKeys( unsigned char key, int x, int y )
{
	//Toggle quad
	if( key == 'q' )
	{
	    quit=true;
	}
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for(int i=0;i<9;i++)
    {
	TempObj[i]->RotateY(30.0f/60.0f);
//	TempObj[i]->RotateX(60.0f/60.0f*(60.0f/framerate));
	TempObj[i]->Render();
    }

}

void setup()
{
    glClearColor( 0.f, 0.f, 0.f, 1.f );
    ProjectionMatrix.SetProjectionMatrix(60,float(ScreenWidth)/ScreenHeight,1.0f,100.0f);

    DefaultShaders=new ShaderProgram("default");

    ProjectionMatrix.Upload(DefaultShaders->GetUniformLocation("ProjectionMatrix"));

    float CubeColor[]={1.0f,0.0f,0.0f};
    float CubePos[]={0.0f,0.0f,-12.0f};

    for(int i=0;i<9;i++)
    {
	CubePos[0]=i*2.0f-9.0f;
	TempObj[i]=new Object(CreateCubeMesh(),CubeColor,CubePos,Object::WhiteOutLine,0.5f);
	TempObj[i]->SetShader(DefaultShaders);

	// TempObj[i]->RotateZ(5.0f*i);
	TempObj[i]->RotateX(20);
	// TempObj[i]->RotateY(5.0f*i);
	TempObj[i]->Scale(i/10.0f+0.5f,0.5f,0.5f);
    }

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    // ExitOnGLError("ERROR: Could not set OpenGL depth testing options");

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);

}

int main(int argc, char **argv)
{
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
	std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
	return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

    SDL_Window *win = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL);
    if (win == nullptr)
    {
	std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
	return 1;
    }

    SDL_GLContext gContext = SDL_GL_CreateContext( win );

    if( SDL_GL_SetSwapInterval( 1 ) < 0 )
    {
	std::cout<< "Warning: Unable to set VSync! SDL Error: "<<SDL_GetError()<<std::endl;
    }

    glewExperimental = GL_TRUE;
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
	std::cout<< "Error initializing GLEW! "<< glewGetErrorString( glewError )<<std::endl;
	return 1;
    }

    setup();

    HPI *hpi=new HPI("data/totala1.hpi");

    delete hpi;

    //Event handler
    SDL_Event e;

    //Enable text input
    SDL_StartTextInput();

    //While application is running
    while( !quit )
    {
	//Handle events on queue
	while( SDL_PollEvent( &e ) != 0 )
	{
	    //User requests quit
	    if( e.type == SDL_QUIT )
	    {
		quit = true;
	    }
	    //Handle keypress with current mouse position
	    else if( e.type == SDL_TEXTINPUT )
	    {
		int x = 0, y = 0;
		SDL_GetMouseState( &x, &y );
		handleKeys( e.text.text[ 0 ], x, y );
	    }
	}

	//Render quad
	render();

	//Update screen
	SDL_GL_SwapWindow( win );
    }
    SDL_StopTextInput();

    SDL_DestroyWindow(win);
    SDL_Quit();

    return 0;
}

void Normalize(GLfloat v[3])
{
    float size=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
    for(int i=0;i<3;i++)
	v[i]/=size;
}

void SubDivideSphere(GLfloat Vertices[],int depth)
{
    if(depth==0)
	return;
    int newvertoffset=1;
    if(depth>=2)
	newvertoffset=pow(4,depth-2)*3;
    int vertoffset= newvertoffset*4;
    if(depth==1)
	vertoffset=3;

    vertoffset*=3;
    newvertoffset*=3;
    GLfloat * v1=&Vertices[vertoffset*0];
    GLfloat * v2=&Vertices[vertoffset*1];
    GLfloat * v3=&Vertices[vertoffset*2];
    GLfloat v12[]={(v1[0]+v2[0])/2.0f,(v1[1]+v2[1])/2.0f,(v1[2]+v2[2])/2.0f};
    GLfloat v23[]={(v2[0]+v3[0])/2.0f,(v2[1]+v3[1])/2.0f,(v2[2]+v3[2])/2.0f};
    GLfloat v31[]={(v1[0]+v3[0])/2.0f,(v1[1]+v3[1])/2.0f,(v1[2]+v3[2])/2.0f};

    Normalize(v12);
    Normalize(v23);
    Normalize(v31);
    memcpy(&Vertices[(vertoffset*0+newvertoffset*1)],v12,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*0+newvertoffset*2)],v31,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*1+newvertoffset*1)],v23,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*1+newvertoffset*2)],v12,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*2+newvertoffset*1)],v31,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*2+newvertoffset*2)],v23,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*3+newvertoffset*0)],v12,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*3+newvertoffset*1)],v23,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*3+newvertoffset*2)],v31,sizeof(GLfloat)*3);

    for(int i=0;i<4;i++)
    {
	SubDivideSphere(&Vertices[(vertoffset*i)],depth-1);
    }

}

TriangleMesh * CreateGeodesicSphere(int depth)
{

    const float X = 0.525731112119133606f;
    const float Z = 0.850650808352039932f;

    float vertices[] ={-X,0.0f,Z,  X,0.0f,Z,   -X,0.0f,-Z,  X,0.0f,-Z,
		       0.0f,Z,X,   0.0f,Z,-X,  0.0f,-Z,X,  0.0f,-Z,-X,
		       Z,X,0.0,   -Z,X,0.0f,  Z,-X,0.0f,  -Z,-X,0.0f};

    GLuint indices[] ={1,4,0,   4,9,0,  4,5,9,  8,5,4,  1,8,4,
		    1,10,8,  10,3,8,  8,3,5,  3,2,5,  3,7,2,
		    3,10,7,  10,6,7,  6,11,7,  6,0,11,  6,1,0,
		    10,1,6,  11,0,9,  2,11,9,  5,2,9,  11,2,7};

    GLuint NumVertices=sizeof(indices)/sizeof(GLuint);
    int Multiplier=pow(4,depth);
    GLfloat * Vertices=new GLfloat[NumVertices*3*Multiplier];

    for(GLuint i=0;i<NumVertices/3;i++)
    {
	for(int j=0;j<3;j++)
	{
	    Vertices[i*3*3*Multiplier+0+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+0];
	    Vertices[i*3*3*Multiplier+1+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+1];
	    Vertices[i*3*3*Multiplier+2+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+2];
	}

    }
    for(GLuint i=0;i<NumVertices/3;i++)
	SubDivideSphere(&Vertices[i*3*3*Multiplier],depth);

    TriangleMesh * SphereMesh=new TriangleMesh(NumVertices*Multiplier,Vertices,Vertices);
    return SphereMesh;
}

TriangleMesh * CreateCubeMesh()
{
    static TriangleMesh * CubeMesh=0;
    if(!CubeMesh)
    {
	float vertices[]= {
	    -.5f, -.5f,  .5f, //0
	    -.5f,  .5f,  .5f,  //1
	    .5f,  .5f,  .5f, //2
	    .5f, -.5f,  .5f, //3
	    -.5f, -.5f, -.5f , //4
	    -.5f,  .5f, -.5f , //5
	    .5f,  .5f, -.5f ,  //6
	    .5f, -.5f, -.5f //7
	};

	const float normals[]={
	    0,0,1,
	    0,-1,0,
	    -1,0,0,
	    1,0,0,
	    0,1,0,
	    0,0,-1
	};

	const GLuint indices[36] =
	    {
		0,2,1,  0,3,2,
		4,3,0,  4,7,3,
		4,1,5,  4,0,1,
		3,6,2,  3,7,6,
		1,6,5,  1,2,6,
		7,5,6,  7,4,5
	    };

	int NumVertices=sizeof(indices)/sizeof(GLuint);
	GLfloat * Vertices=new GLfloat[NumVertices*3];
	GLfloat * Normals=new GLfloat[NumVertices*3];

	for(int i=0;i<NumVertices;i++)
	{
	    Vertices[3*i+0]=vertices[indices[i]*3+0];
	    Vertices[3*i+1]=vertices[indices[i]*3+1];
	    Vertices[3*i+2]=vertices[indices[i]*3+2];

	    Normals[3*i+0]=normals[(i/6)*3+0];
	    Normals[3*i+1]=normals[(i/6)*3+1];
	    Normals[3*i+2]=normals[(i/6)*3+2];
	}

	CubeMesh = new TriangleMesh(NumVertices,Vertices,Normals);
    }
    return CubeMesh;
}

<commit_msg>move HPI test code to run on machines where sdl/opengl creation fails.<commit_after>#include <iostream>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "lib/TriangleMesh.hpp"
#include "lib/Object.hpp"

#include "file_format/HPIFile.hpp"

bool quit = false;
Matrix ProjectionMatrix;
Object * TempObj[9];
ShaderProgram * DefaultShaders;

const int ScreenWidth=640;
const int ScreenHeight=480;

TriangleMesh * CreateCubeMesh();
/**
* Log an SDL error with some error message to the output stream of our choice
* @param os The output stream to write the message too
* @param msg The error message to write, format will be msg error: SDL_GetError()
*/
void logSDLError(std::ostream &os, const std::string &msg)
{
    os << msg << " error: " << SDL_GetError() << std::endl;
}

void handleKeys( unsigned char key, int x, int y )
{
	//Toggle quad
	if( key == 'q' )
	{
	    quit=true;
	}
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for(int i=0;i<9;i++)
    {
	TempObj[i]->RotateY(30.0f/60.0f);
//	TempObj[i]->RotateX(60.0f/60.0f*(60.0f/framerate));
	TempObj[i]->Render();
    }

}

void setup()
{
    glClearColor( 0.f, 0.f, 0.f, 1.f );
    ProjectionMatrix.SetProjectionMatrix(60,float(ScreenWidth)/ScreenHeight,1.0f,100.0f);

    DefaultShaders=new ShaderProgram("default");

    ProjectionMatrix.Upload(DefaultShaders->GetUniformLocation("ProjectionMatrix"));

    float CubeColor[]={1.0f,0.0f,0.0f};
    float CubePos[]={0.0f,0.0f,-12.0f};

    for(int i=0;i<9;i++)
    {
	CubePos[0]=i*2.0f-9.0f;
	TempObj[i]=new Object(CreateCubeMesh(),CubeColor,CubePos,Object::WhiteOutLine,0.5f);
	TempObj[i]->SetShader(DefaultShaders);

	// TempObj[i]->RotateZ(5.0f*i);
	TempObj[i]->RotateX(20);
	// TempObj[i]->RotateY(5.0f*i);
	TempObj[i]->Scale(i/10.0f+0.5f,0.5f,0.5f);
    }

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    // ExitOnGLError("ERROR: Could not set OpenGL depth testing options");

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);

}

int main(int argc, char **argv)
{
    HPI *hpi=new HPI("data/totala1.hpi");

    delete hpi;

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
	std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
	return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

    SDL_Window *win = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL);
    if (win == nullptr)
    {
	std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
	return 1;
    }

    SDL_GLContext gContext = SDL_GL_CreateContext( win );

    if( SDL_GL_SetSwapInterval( 1 ) < 0 )
    {
	std::cout<< "Warning: Unable to set VSync! SDL Error: "<<SDL_GetError()<<std::endl;
    }

    glewExperimental = GL_TRUE;
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
	std::cout<< "Error initializing GLEW! "<< glewGetErrorString( glewError )<<std::endl;
	return 1;
    }

    setup();

    //Event handler
    SDL_Event e;

    //Enable text input
    SDL_StartTextInput();

    //While application is running
    while( !quit )
    {
	//Handle events on queue
	while( SDL_PollEvent( &e ) != 0 )
	{
	    //User requests quit
	    if( e.type == SDL_QUIT )
	    {
		quit = true;
	    }
	    //Handle keypress with current mouse position
	    else if( e.type == SDL_TEXTINPUT )
	    {
		int x = 0, y = 0;
		SDL_GetMouseState( &x, &y );
		handleKeys( e.text.text[ 0 ], x, y );
	    }
	}

	//Render quad
	render();

	//Update screen
	SDL_GL_SwapWindow( win );
    }
    SDL_StopTextInput();

    SDL_DestroyWindow(win);
    SDL_Quit();

    return 0;
}

void Normalize(GLfloat v[3])
{
    float size=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
    for(int i=0;i<3;i++)
	v[i]/=size;
}

void SubDivideSphere(GLfloat Vertices[],int depth)
{
    if(depth==0)
	return;
    int newvertoffset=1;
    if(depth>=2)
	newvertoffset=pow(4,depth-2)*3;
    int vertoffset= newvertoffset*4;
    if(depth==1)
	vertoffset=3;

    vertoffset*=3;
    newvertoffset*=3;
    GLfloat * v1=&Vertices[vertoffset*0];
    GLfloat * v2=&Vertices[vertoffset*1];
    GLfloat * v3=&Vertices[vertoffset*2];
    GLfloat v12[]={(v1[0]+v2[0])/2.0f,(v1[1]+v2[1])/2.0f,(v1[2]+v2[2])/2.0f};
    GLfloat v23[]={(v2[0]+v3[0])/2.0f,(v2[1]+v3[1])/2.0f,(v2[2]+v3[2])/2.0f};
    GLfloat v31[]={(v1[0]+v3[0])/2.0f,(v1[1]+v3[1])/2.0f,(v1[2]+v3[2])/2.0f};

    Normalize(v12);
    Normalize(v23);
    Normalize(v31);
    memcpy(&Vertices[(vertoffset*0+newvertoffset*1)],v12,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*0+newvertoffset*2)],v31,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*1+newvertoffset*1)],v23,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*1+newvertoffset*2)],v12,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*2+newvertoffset*1)],v31,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*2+newvertoffset*2)],v23,sizeof(GLfloat)*3);

    memcpy(&Vertices[(vertoffset*3+newvertoffset*0)],v12,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*3+newvertoffset*1)],v23,sizeof(GLfloat)*3);
    memcpy(&Vertices[(vertoffset*3+newvertoffset*2)],v31,sizeof(GLfloat)*3);

    for(int i=0;i<4;i++)
    {
	SubDivideSphere(&Vertices[(vertoffset*i)],depth-1);
    }

}

TriangleMesh * CreateGeodesicSphere(int depth)
{

    const float X = 0.525731112119133606f;
    const float Z = 0.850650808352039932f;

    float vertices[] ={-X,0.0f,Z,  X,0.0f,Z,   -X,0.0f,-Z,  X,0.0f,-Z,
		       0.0f,Z,X,   0.0f,Z,-X,  0.0f,-Z,X,  0.0f,-Z,-X,
		       Z,X,0.0,   -Z,X,0.0f,  Z,-X,0.0f,  -Z,-X,0.0f};

    GLuint indices[] ={1,4,0,   4,9,0,  4,5,9,  8,5,4,  1,8,4,
		    1,10,8,  10,3,8,  8,3,5,  3,2,5,  3,7,2,
		    3,10,7,  10,6,7,  6,11,7,  6,0,11,  6,1,0,
		    10,1,6,  11,0,9,  2,11,9,  5,2,9,  11,2,7};

    GLuint NumVertices=sizeof(indices)/sizeof(GLuint);
    int Multiplier=pow(4,depth);
    GLfloat * Vertices=new GLfloat[NumVertices*3*Multiplier];

    for(GLuint i=0;i<NumVertices/3;i++)
    {
	for(int j=0;j<3;j++)
	{
	    Vertices[i*3*3*Multiplier+0+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+0];
	    Vertices[i*3*3*Multiplier+1+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+1];
	    Vertices[i*3*3*Multiplier+2+j*((Multiplier/4)*3)*3]=vertices[indices[i*3+j]*3+2];
	}

    }
    for(GLuint i=0;i<NumVertices/3;i++)
	SubDivideSphere(&Vertices[i*3*3*Multiplier],depth);

    TriangleMesh * SphereMesh=new TriangleMesh(NumVertices*Multiplier,Vertices,Vertices);
    return SphereMesh;
}

TriangleMesh * CreateCubeMesh()
{
    static TriangleMesh * CubeMesh=0;
    if(!CubeMesh)
    {
	float vertices[]= {
	    -.5f, -.5f,  .5f, //0
	    -.5f,  .5f,  .5f,  //1
	    .5f,  .5f,  .5f, //2
	    .5f, -.5f,  .5f, //3
	    -.5f, -.5f, -.5f , //4
	    -.5f,  .5f, -.5f , //5
	    .5f,  .5f, -.5f ,  //6
	    .5f, -.5f, -.5f //7
	};

	const float normals[]={
	    0,0,1,
	    0,-1,0,
	    -1,0,0,
	    1,0,0,
	    0,1,0,
	    0,0,-1
	};

	const GLuint indices[36] =
	    {
		0,2,1,  0,3,2,
		4,3,0,  4,7,3,
		4,1,5,  4,0,1,
		3,6,2,  3,7,6,
		1,6,5,  1,2,6,
		7,5,6,  7,4,5
	    };

	int NumVertices=sizeof(indices)/sizeof(GLuint);
	GLfloat * Vertices=new GLfloat[NumVertices*3];
	GLfloat * Normals=new GLfloat[NumVertices*3];

	for(int i=0;i<NumVertices;i++)
	{
	    Vertices[3*i+0]=vertices[indices[i]*3+0];
	    Vertices[3*i+1]=vertices[indices[i]*3+1];
	    Vertices[3*i+2]=vertices[indices[i]*3+2];

	    Normals[3*i+0]=normals[(i/6)*3+0];
	    Normals[3*i+1]=normals[(i/6)*3+1];
	    Normals[3*i+2]=normals[(i/6)*3+2];
	}

	CubeMesh = new TriangleMesh(NumVertices,Vertices,Normals);
    }
    return CubeMesh;
}

<|endoftext|>


<commit_before>266ddcd7-ad59-11e7-a4da-ac87a332f658<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>2702ba0c-ad59-11e7-972f-ac87a332f658<|endoftext|>


<commit_before>80ff8f51-4b02-11e5-bbe2-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>810c75e6-4b02-11e5-8af1-28cfe9171a43<|endoftext|>


<commit_before>///
/// [EntityFu](https://github.com/NatWeiss/EntityFu)
/// A simple, fast entity component system written in C++.
/// Under the MIT license.
///

#include "EntityFu.h"
#include <iostream>
#include <unistd.h>
using namespace std;

/// An example component.
struct HealthComponent : Entity::Component
{
	int hp, maxHP;

	HealthComponent(int _hp, int _maxHP)
	{
		hp = _hp;
		maxHP = _maxHP;
	}

	HealthComponent() : HealthComponent(0, 0) {}

	virtual bool isEmpty() const {return maxHP == 0;}

	static Cid cid;
};

/// Assign unique class IDs from 0 to `numClassIds` - 1
static Cid _id = 0;
Cid HealthComponent::cid = _id++;
Cid Entity::Component::numCids = _id; // also critical to assign `numClassIds`

/// An example `Ent`.
struct System::Ent
{
	Eid id;
	HealthComponent& health;
	/// Add more components your systems will use frequently

	Ent(Eid _id) :
		health(Entity::get<HealthComponent>(_id)),
		id(_id)
	{}
};

/// An example system.
struct HealthSystem : System
{
	static void tick(double fixedDelta)
	{
		// for this example, just decrement all health components each tick
		for (auto eid : Entity::getAll<HealthComponent>())
		{
			Ent e(eid);

			// this is overly pragmatic, but you get the drift of how to check if a component is valid
			if (e.health.isEmpty())
				continue;

			// decrement
			e.health.hp--;
			if (e.health.hp < 0)
				e.health.hp = 0;
			cout << "Entity " << (int)e.id << " has " << e.health.hp << "/" << e.health.maxHP << " hit points." << endl;

			// destroy entity if zero health
			if (e.health.hp <= 0)
				Entity::destroyNow(eid);
		}
	}
};

int main(int argc, const char * argv[])
{
	// create some entities
	Entity::create(new HealthComponent(100, 100));
	Entity::create(new HealthComponent(7, 7));

	// run the system
	while (Entity::count())
	{
		HealthSystem::tick(0.1);
		usleep(1000 * 100);
	}

	Entity::dealloc();
	cout << "Goodbye, World!\n";
    return 0;
}

<commit_msg>Fixed vector iterator assertion failure in example code due to removing HealthComponent.<commit_after>///
/// [EntityFu](https://github.com/NatWeiss/EntityFu)
/// A simple, fast entity component system written in C++.
/// Under the MIT license.
///

#include "EntityFu.h"
#include <iostream>
#include <unistd.h>
using namespace std;

/// An example component.
struct HealthComponent : Entity::Component
{
	int hp, maxHP;

	HealthComponent(int _hp, int _maxHP)
	{
		hp = _hp;
		maxHP = _maxHP;
	}

	HealthComponent() : HealthComponent(0, 0) {}

	virtual bool isEmpty() const {return maxHP == 0;}

	static Cid cid;
};

/// Assign unique class IDs from 0 to `numClassIds` - 1
static Cid _id = 0;
Cid HealthComponent::cid = _id++;
Cid Entity::Component::numCids = _id; // also critical to assign `numClassIds`

/// An example `Ent`.
struct System::Ent
{
	Eid id;
	HealthComponent& health;
	/// Add more components your systems will use frequently

	Ent(Eid _id) :
		health(Entity::get<HealthComponent>(_id)),
		id(_id)
	{}
};

/// An example system.
struct HealthSystem : System
{
	static void tick(double fixedDelta)
	{
		// create a copy of the vector<Eid> for all health components so we
		// don't cause an assertion failure: "vector iterator not incrementable"
		// for more speed you can instead loop over a reference as long as you schedule
		// Entity::destroyNow for after the loop
		auto all = Entity::getAll<HealthComponent>();

		// for this example, just decrement all health components each tick
		for (auto eid : all)
		{
			Ent e(eid);

			// this is overly pragmatic, but you get the drift of how to check if a component is valid
			if (e.health.isEmpty())
				continue;

			// decrement
			e.health.hp--;
			if (e.health.hp < 0)
				e.health.hp = 0;
			cout << "Entity " << (int)e.id << " has " << e.health.hp << "/" << e.health.maxHP << " hit points." << endl;

			// destroy entity if zero health
			if (e.health.hp <= 0)
				Entity::destroyNow(eid);
		}
	}
};

int main(int argc, const char * argv[])
{
	// create some entities
	Entity::create(new HealthComponent(100, 100));
	Entity::create(new HealthComponent(7, 7));

	// run the system
	while (Entity::count())
	{
		HealthSystem::tick(0.1);
		usleep(1000 * 100);
	}

	Entity::dealloc();
	cout << "Goodbye, World!\n";
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "curlbuffer.h"

#define BOARDLENGTH 1

using namespace std;

bool reactToPage( string BoardContent)
{
	if ( BoardContent.find( "<title>404 Not Found</title>") != -1)
	{
		return false;
	}
	return true;
}

void tryName( int i, string Test)
{
	string Alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
	for ( int j = 0; j < Alphabet.size(); j++)
	{
		if ( i == Test.size() - 1)
		{
			Test[i] = Alphabet[j];
			string BoardUrl = "http://8chan.co/";
			BoardUrl.append( Test);
			string BoardContent = ( string) getWebPage( ( char*) BoardUrl.c_str());
			if ( reactToPage( BoardContent))
			{
				cout << "Board /" << Test << "/ found (" << BoardUrl << ")\n";
			}
			else
			{
				cout << "Board /" << Test << "/ not found\n";
			}
		}
		if ( i < Test.size() - 1)
		{
			tryName( i + 1, Test);
		}
	}
}

int main()
{
	string Test;
	Test.resize( BOARDLENGTH);
	Test.assign( Test.size(), 'a');
	tryName( 0, Test);
	return 0;
}
<commit_msg>fixed more redundant board grabbing<commit_after>#include <iostream>
#include <string>
#include "curlbuffer.h"

#define BOARDLENGTH 3

using namespace std;

bool reactToPage( string BoardContent)
{
	if ( BoardContent.find( "<title>404 Not Found</title>") != -1)
	{
		return false;
	}
	return true;
}

void tryName( int i, string Test)
{
	string Alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
	for ( int j = 0; j < Alphabet.size(); j++)
	{
		Test[i] = Alphabet[j];
		if ( i == Test.size() - 1)
		{
			string BoardUrl = "http://8chan.co/";
			BoardUrl.append( Test);
			string BoardContent = ( string) getWebPage( ( char*) BoardUrl.c_str());
			if ( reactToPage( BoardContent))
			{
				cout << "Board /" << Test << "/ found (" << BoardUrl << ")\n";
			}
		}
		else
		{
			tryName( i + 1, Test);
		}
	}
}

int main()
{
	string Test;
	Test.resize( BOARDLENGTH);
	Test.assign( Test.size(), 'a');
	tryName( 0, Test);
	return 0;
}
<|endoftext|>


<commit_before>83c5df0a-4b02-11e5-bfb2-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>83d155ee-4b02-11e5-911e-28cfe9171a43<|endoftext|>


<commit_before>bbddd8cc-4b02-11e5-867d-28cfe9171a43<commit_msg>Did a thing<commit_after>bbea177a-4b02-11e5-ad28-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <sstream>
#include <map>

#define SPACE_DELIMITER " "
#define NCHAR 26

using namespace std;

void fillWeigthArray(int alphaWeight[]);
int score(string str, const int alphaWeight[]);
void getPrimes(int *primes, int n);
unsigned long long int getHash(string str, int primes[]);
string convertLongToString(unsigned long long int);
void insertInMap(string key, string value, map<string, string> & primeAnagram);
void writeMapToFile(std::map<string, string> primeAnagram);
void loadDict(string inFile, map<string, string> &primeAnagram, int primes[]);

int main(int argc, char **argv) {
	/*
	 if(argc < 3) {
	 cerr << "USAGE " << argv[0] << " DICTFILE CHARINHAND" << endl;
	 return -1;
	 }
	 */
	string inputFile = "sowpods.txt";

	string charsInHand = ""; //argv[2];
	int primes[NCHAR];
	map<string, string> primeAnagram;
	getPrimes(primes, NCHAR);
	loadDict(inputFile, primeAnagram, primes);
	writeMapToFile(primeAnagram);
	return 0;
}

void loadDict(string inFile, map<string, string> &primeAnagram, int primes[]) {
	string word;
	ifstream inputFile(inFile.c_str());
	if (inputFile.is_open()) {
		while (getline(inputFile, word)) {
			string hash = convertLongToString(getHash(word, primes));
			insertInMap(hash, word, primeAnagram);
		}
		inputFile.close();
	} else {
		cerr << "Unable to open file" << endl;
	}
}

unsigned long long int getHash(string str, int primes[]) {
	unsigned long long int hash = 1;
	for (int i = 0; i < str.length(); i++) {
		hash *= primes[str[i] - 'a'];
	}

	return hash;
}

void getPrimes(int *primes, int n) {
	int count = 1;
	primes[0] = 2;
	int curNum = 3;
	while (count < n) {
		bool isPrime = true;
		for (int i = 0; i < count && isPrime; i++) {
			if (curNum % primes[i] == 0) {
				isPrime = false;
			}
		}
		if (isPrime)
			primes[count++] = curNum;
		curNum += 2;
	}
}

string convertLongToString(unsigned long long int hash) {
	string hashString;
	stringstream strStream;
	strStream << hash;
	strStream >> hashString;
	return hashString;
}

void insertInMap(string key, string value, map<string, string> & primeAnagram) {
	map<string, string>::iterator it = primeAnagram.begin();

	if (primeAnagram.count(key)) {
		it = primeAnagram.find(key);
		it->second = it->second + SPACE_DELIMITER + value;
	} else {
		primeAnagram.insert(std::pair<string, string>(key, value));
	}
}
void writeMapToFile(map<string, string> primeAnagram) {
	ofstream outFile("Anagram_Pairs.txt");
	if (outFile.is_open()) {
		for (map<string, string>::iterator it = primeAnagram.begin();
				it != primeAnagram.end(); ++it) {
			if ((it->second).find_first_of(SPACE_DELIMITER)
					< (it->second).length()) {
				outFile << it->second << '\n';
			}
		}
		outFile.close();
		cout << "Written to file" << endl;
	} else {
		cerr << "Unable to open file" << endl;
	}
}

int score(string str, const int alphaWeight[]) {
	int wordScore = 0;

	for (unsigned int i = 0; i < str.length(); ++i) {
		int index = toupper(str[i]) - 'A';
		wordScore += alphaWeight[index];
	}

	return wordScore;
}

void fillWeigthArray(int alphaWeight[]) {
	for (int i = 0; i < NCHAR; ++i) {
		alphaWeight[i] = i + 1;
	}
}

<commit_msg>Fix:Major<commit_after>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <sstream>
#include <map>

#define SPACE_DELIMITER " "
#define NCHAR 26

using namespace std;

void fillWeigthArray(int alphaWeight[]);
int score(string str, const int alphaWeight[]);
void getPrimes(int *primes, int n);
unsigned long long int getHash(string str, int primes[]);
void insertInMap(unsigned long long key, string value, map<unsigned long long, string> & primeAnagram);
void loadDict(string inFile, map<unsigned long long, string> &primeAnagram, int primes[]);
string getMaxScoreWord(string charsInHand, int wiegthArray[], map<unsigned long long, string> primeAnagram);

//void writeMapToFile(map<unsigned long long, string> primeAnagram) ;

int main(int argc, char **argv) {
	/*
	 if(argc < 3) {
	 cerr << "USAGE " << argv[0] << " DICTFILE CHARINHAND" << endl;
	 return -1;
	 }
	 */
	string inputFile = "sowpods.txt";
	string charsInHand = "ABCD"; //argv[2];
	int primes[NCHAR];
	map<unsigned long long, string> primeAnagram;

	getPrimes(primes, NCHAR);
	loadDict(inputFile, primeAnagram, primes);

	int wiegthArray[NCHAR]  = {};
	string validWord = getMaxScoreWord(charsInHand, wiegthArray, primeAnagram);

	cout << validWord <<endl;
	//writeMapToFile(primeAnagram);

	return 0;
}

string getMaxScoreWord(string charsInHand, int wiegthArray[], map<unsigned long long, string> primeAnagram){
	int maxScore = 0;
	string maxScoreWord;

	//TODO
	//Call recurive function
	return maxScoreWord;
}

void loadDict(string inFile, map<unsigned long long, string> &primeAnagram, int primes[]) {
	string word;
	ifstream inputFile(inFile.c_str());
	if (inputFile.is_open()) {
		while (getline(inputFile, word)) {
			unsigned long long hash = getHash(word, primes);
			insertInMap(hash, word, primeAnagram);
		}
		inputFile.close();
	} else {
		cerr << "Unable to open file" << endl;
	}
}

unsigned long long int getHash(string str, int primes[]) {
	unsigned long long int hash = 1;
	for (char c: str) {
		hash *= primes[c - 'a'];
	}

	return hash;
}

void getPrimes(int *primes, int n) {
	int count = 1;
	primes[0] = 2;
	int curNum = 3;
	while (count < n) {
		bool isPrime = true;
		for (int i = 0; i < count && isPrime; i++) {
			if (curNum % primes[i] == 0) {
				isPrime = false;
			}
		}
		if (isPrime)
			primes[count++] = curNum;
		curNum += 2;
	}
}

void insertInMap(unsigned long long key, string value, map<unsigned long long, string> & primeAnagram) {
	map<unsigned long long, string>::iterator it = primeAnagram.begin();

	if (primeAnagram.count(key)) {
		it = primeAnagram.find(key);
		it->second = it->second + SPACE_DELIMITER + value;
	} else {
		primeAnagram.insert(std::pair<unsigned long long, string>(key, value));
	}
}

int score(string str, const int alphaWeight[]) {
	int wordScore = 0;

	for (unsigned int i = 0; i < str.length(); ++i) {
		int index = toupper(str[i]) - 'A';
		wordScore += alphaWeight[index];
	}

	return wordScore;
}

void fillWeigthArray(int alphaWeight[]) {
	for (int i = 0; i < NCHAR; ++i) {
		alphaWeight[i] = i + 1;
	}
}

/*

void writeMapToFile(map<unsigned long long, string> primeAnagram) {
	ofstream outFile("Anagram_Pairs.txt");
	if (outFile.is_open()) {
		for (map<unsigned long long, string>::iterator it = primeAnagram.begin();
				it != primeAnagram.end(); ++it) {
			if ((it->second).find_first_of(SPACE_DELIMITER)
					< (it->second).length()) {
				outFile << it->second << '\n';
			}
		}
		outFile.close();
		cout << "Written to file" << endl;
	} else {
		cerr << "Unable to open file" << endl;
	}
}

*/
<|endoftext|>


<commit_before>776f0b5c-4b02-11e5-9bf0-28cfe9171a43<commit_msg>Did a thing<commit_after>777adda6-4b02-11e5-95c2-28cfe9171a43<|endoftext|>


<commit_before>#include "gameloop.hpp"
#include "glhead.hpp"
#include "input.hpp"

class MyDraw : public rs::IDrawProc {
	public:
		bool runU(uint64_t accum) override {
			glClearColor(0,0,(accum&0xff) / 255.0f,1);
			glClear(GL_COLOR_BUFFER_BIT);
			return true;
		}
};
class MyMain : public rs::IMainProc {
	rs::HLInput hlIk;
	rs::HLAct actQuit,
			actButton;
	public:
		MyMain() {
			hlIk = rs::Keyboard::OpenKeyboard();
			actQuit = mgr_input.addAction("quit");
			mgr_input.link(actQuit.get(), rs::InF::AsButton(hlIk.get(), SDL_SCANCODE_ESCAPE));
			actButton = mgr_input.addAction("button");
			mgr_input.link(actQuit.get(), rs::InF::AsButton(hlIk.get(), SDL_SCANCODE_A));
		}
		bool runU() override {
			if(mgr_input.isKeyPressed(actQuit.get()))
				return false;
			return true;
		}
		rs::IDrawProc* initDraw() override {
			return new MyDraw;
		}
};

using namespace rs;
int main(int argc, char **argv) {
	return GameLoop([](){ return new MyMain; }, "HelloSDL2", 640, 480, SDL_WINDOW_SHOWN, 4,2,24);
}
<commit_msg>gameloopを使った新たなテストコード<commit_after>#include "gameloop.hpp"
#include "glhead.hpp"
#include "input.hpp"
#include "glresource.hpp"
#include "spinner/vector.hpp"
#include "gpu.hpp"
#include "glx.hpp"

// void test0() {
// 	auto fc = mgr_ft.newFace(mgr_rw.fromFile("/home/slice/.fonts/msgothic.ttc", "r", true), 2);
// 	auto& f = fc.ref();
// 	f.setPixelSizes(0, 64);
// 	f.setSizeFromLine(16);
// 	f.prepareGlyph(U'𠀋', FTFace::RenderMode::Normal);
// 	const auto& a = f.getGlyphInfo();
//
// 	const void* data = a.data;
// 	int pitch = a.pitch;
// 	spn::ByteBuff buff;
// 	if(a.nlevel == 2) {
// 		buff = Convert1Bit_8Bit(data, a.width, pitch, a.height);
// 		pitch *= 8;
// 		data = &buff[0];
// 	}
// 	buff = Convert8Bit_Packed24Bit(data, a.width, pitch, a.height);
// 	auto sf = Surface::Create(std::move(buff), 0, a.width, a.height, Color::RGB8);
// 	sf->saveAsPNG(mgr_rw.fromFile("/tmp/kusoge.png","w",true));
// 	auto& gi = f.getGlyphInfo();
// }
// 	CCoreID id = gen.makeCoreID("MS Gothic", CCoreID(0, 16, 0, false, 0));
// 	HLText hlText = gen.createText(id, "HELLO,WORLD");

// MainThread と DrawThread 間のデータ置き場
struct Mth_DthData {
	rs::HLInput hlIk;
	rs::HLAct actQuit,
			actButton,
			actLeft,
			actRight,
			actUp,
			actDown;
};
#define shared (Mth_Dth::_ref())
class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {};

class MyDraw : public rs::IDrawProc {
	rs::HLFx	_hlFx;
	rs::HLVb 	_hlVb;
	rs::HLIb 	_hlIb;
	rs::HLTex 	_hlTex;
	public:
		MyDraw() {
			struct TmpV {
				spn::Vec3 pos;
				spn::Vec4 tex;
			};
			TmpV tmpV[] = {
				{
					spn::Vec3{-1,-1,0},
					spn::Vec4{0,1,0,0}
				},
				{
					spn::Vec3{-1,1,0},
					spn::Vec4{0,0,0,0}
				},
				{
					spn::Vec3{1,1,0},
					spn::Vec4{1,0,0,0}
				},
				{
					spn::Vec3{1,-1,0},
					spn::Vec4{1,1,0,0}
				}
			};
			// インデックス定義
			GLubyte tmpI[] = {
				0,1,2,
				2,3,0
			};
			mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/")));
			_hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW);
			_hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV));
			_hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW);
			_hlIb.ref()->use()->initData(tmpI, countof(tmpI));
			_hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png"));
			_hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true);

			rs::GPUInfo info;
			info.onDeviceReset();
			std::cout << info;

			_hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx"));
			auto& pFx = *_hlFx.ref();
			GLint techID = pFx.getTechID("TheTech");
			pFx.setTechnique(techID, true);
			GLint passID = pFx.getPassID("P0");
			pFx.setPass(passID);
			// 頂点フォーマット定義
			rs::SPVDecl decl(new rs::VDecl{
				{0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION},
				{0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0}
			});
			pFx.setVDecl(std::move(decl));
			pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal"));

			_hlTex.ref()->save("/tmp/test.png");
			rs::SetSwapInterval(1);
		}
		bool runU(uint64_t accum) override {
			glClearColor(0,0,1,1);//(accum&0xff) / 255.0f,1);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
			int w = 640,
				h = 480;
			glViewport(0,0,w,h);

			static float angle = 0,
						angleX = 0;
			spn::Mat44 m4 = spn::Mat44::RotationX(spn::DEGtoRAD(angle));
			m4 *= spn::Mat44::RotationY(spn::DEGtoRAD(angleX));
			m4 *= spn::Mat44::PerspectiveFovLH(spn::DEGtoRAD(60), float(w)/h, 0.01f, 100.0f);

			auto* pFx = _hlFx.ref().get();
			GLint id = pFx->getUniformID("mTrans");
			pFx->setUniform(m4, id);
			id = pFx->getUniformID("tDiffuse");
			pFx->setUniform(_hlTex, id);

			auto lk = shared.lock();
			constexpr float speed = 1.f;
			if(mgr_input.isKeyPressing(lk->actUp))
				angle += speed;
			if(mgr_input.isKeyPressing(lk->actDown))
				angle -= speed;
			if(mgr_input.isKeyPressing(lk->actLeft))
				angleX -= speed;
			if(mgr_input.isKeyPressing(lk->actRight))
				angleX += speed;

			pFx->setVStream(_hlVb.get(), 0);
			pFx->setIStream(_hlIb.get());
			pFx->drawIndexed(GL_TRIANGLES, 6, 0);
			return true;
		}
};
class MyMain : public rs::IMainProc {
	Mth_Dth _mth;
	public:
		MyMain() {
			auto lk = shared.lock();
			lk->hlIk = rs::Keyboard::OpenKeyboard();

			lk->actQuit = mgr_input.addAction("quit");
			mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE));
			lk->actButton = mgr_input.addAction("button");
			mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT));

			lk->actLeft = mgr_input.addAction("left");
			lk->actRight = mgr_input.addAction("right");
			lk->actUp = mgr_input.addAction("up");
			lk->actDown = mgr_input.addAction("down");
			mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A));
			mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D));
			mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W));
			mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S));
		}
		bool runU() override {
			auto lk = shared.lock();
			if(mgr_input.isKeyPressed(lk->actQuit))
				return false;
			return true;
		}
		rs::IDrawProc* initDraw() override {
			return new MyDraw;
		}
};

using namespace rs;
int main(int argc, char **argv) {
	return GameLoop([](){ return new MyMain; }, "HelloSDL2", 640, 480, SDL_WINDOW_SHOWN, 2,0,24);
}
<|endoftext|>